1 /* 2 * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de. 3 * Distributed under the terms of the MIT License. 4 */ 5 #ifndef LIST_SELECTION_MODEL_H 6 #define LIST_SELECTION_MODEL_H 7 8 9 #include <SupportDefs.h> 10 11 #include <Array.h> 12 #include <ObjectList.h> 13 14 15 class ListSelectionModel { 16 public: 17 class Listener; 18 19 public: 20 ListSelectionModel(); 21 ListSelectionModel( 22 const ListSelectionModel& other); 23 ~ListSelectionModel(); 24 25 int32 CountSelectedItems() const 26 { return fSelectedItems.Count(); } 27 int32 SelectedItemAt(int32 index) const; 28 bool IsItemSelected(int32 itemIndex) const; 29 30 void Clear(); 31 bool SelectItem(int32 itemIndex, 32 bool extendSelection); 33 bool SelectItems(int32 itemIndex, int32 count, 34 bool extendSelection); 35 void DeselectItem(int32 itemIndex); 36 void DeselectItems(int32 itemIndex, int32 count); 37 38 void ItemsAdded(int32 itemIndex, int32 count); 39 void ItemsRemoved(int32 itemIndex, int32 count); 40 41 bool AddListener(Listener* listener); 42 void RemoveListener(Listener* listener); 43 44 ListSelectionModel& operator=(const ListSelectionModel& other); 45 46 private: 47 typedef BObjectList<Listener> ListenerList; 48 49 private: 50 int32 _FindItem(int32 itemIndex) const; 51 int32 _CountSelectedItemsInRange(int32 index, 52 int32 endItemIndex) const; 53 54 void _NotifyItemsSelected(int32 index, int32 count); 55 void _NotifyItemsDeselected(int32 index, 56 int32 count); 57 58 private: 59 Array<int32> fSelectedItems; 60 ListenerList fListeners; 61 }; 62 63 64 class ListSelectionModel::Listener { 65 public: 66 virtual ~Listener(); 67 68 virtual void ItemsSelected(ListSelectionModel* model, 69 int32 index, int32 count); 70 virtual void ItemsDeselected(ListSelectionModel* model, 71 int32 index, int32 count); 72 }; 73 74 75 inline bool 76 ListSelectionModel::IsItemSelected(int32 itemIndex) const 77 { 78 int32 index = _FindItem(itemIndex); 79 return index < fSelectedItems.Count() && fSelectedItems[index] == itemIndex; 80 } 81 82 83 inline int32 84 ListSelectionModel::SelectedItemAt(int32 index) const 85 { 86 return index >= 0 && index < fSelectedItems.Count() 87 ? fSelectedItems[index] : -1; 88 } 89 90 91 inline bool 92 ListSelectionModel::SelectItem(int32 itemIndex, bool extendSelection) 93 { 94 return SelectItems(itemIndex, 1, extendSelection); 95 } 96 97 98 inline void 99 ListSelectionModel::DeselectItem(int32 itemIndex) 100 { 101 DeselectItems(itemIndex, 1); 102 } 103 104 105 #endif // LIST_SELECTION_MODEL_H 106