Home | History | Annotate | Download | only in views
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "ui/views/view_model.h"
      6 
      7 #include "base/logging.h"
      8 #include "ui/views/view.h"
      9 
     10 namespace views {
     11 
     12 ViewModel::ViewModel() {
     13 }
     14 
     15 ViewModel::~ViewModel() {
     16   // view are owned by their parent, no need to delete them.
     17 }
     18 
     19 void ViewModel::Add(View* view, int index) {
     20   DCHECK_LE(index, static_cast<int>(entries_.size()));
     21   DCHECK_GE(index, 0);
     22   Entry entry;
     23   entry.view = view;
     24   entries_.insert(entries_.begin() + index, entry);
     25 }
     26 
     27 void ViewModel::Remove(int index) {
     28   if (index == -1)
     29     return;
     30 
     31   check_index(index);
     32   entries_.erase(entries_.begin() + index);
     33 }
     34 
     35 void ViewModel::Move(int index, int target_index) {
     36   DCHECK_LT(index, static_cast<int>(entries_.size()));
     37   DCHECK_GE(index, 0);
     38   DCHECK_LT(target_index, static_cast<int>(entries_.size()));
     39   DCHECK_GE(target_index, 0);
     40 
     41   if (index == target_index)
     42     return;
     43   Entry entry(entries_[index]);
     44   entries_.erase(entries_.begin() + index);
     45   entries_.insert(entries_.begin() + target_index, entry);
     46 }
     47 
     48 void ViewModel::MoveViewOnly(int index, int target_index) {
     49   if (index == target_index)
     50     return;
     51   if (target_index < index) {
     52     View* view = entries_[index].view;
     53     for (int i = index; i > target_index; --i)
     54       entries_[i].view = entries_[i - 1].view;
     55     entries_[target_index].view = view;
     56   } else {
     57     View* view = entries_[index].view;
     58     for (int i = index; i < target_index; ++i)
     59       entries_[i].view = entries_[i + 1].view;
     60     entries_[target_index].view = view;
     61   }
     62 }
     63 
     64 void ViewModel::Clear() {
     65   Entries entries;
     66   entries.swap(entries_);
     67   for (size_t i = 0; i < entries.size(); ++i)
     68     delete entries[i].view;
     69 }
     70 
     71 int ViewModel::GetIndexOfView(const View* view) const {
     72   for (size_t i = 0; i < entries_.size(); ++i) {
     73     if (entries_[i].view == view)
     74       return static_cast<int>(i);
     75   }
     76   return -1;
     77 }
     78 
     79 }  // namespace views
     80