1 /* 2 * Copyright 2006, Haiku. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Stephan Aßmus <superstippi@gmx.de> 7 */ 8 9 #include "Selection.h" 10 11 #include <stdio.h> 12 13 #include <debugger.h> 14 15 #include "Selectable.h" 16 17 #define DEBUG 1 18 19 // constructor 20 Selection::Selection() 21 : fSelected(20) 22 { 23 } 24 25 // destructor 26 Selection::~Selection() 27 { 28 } 29 30 // Select 31 bool 32 Selection::Select(Selectable* object, bool extend) 33 { 34 AutoNotificationSuspender _(this); 35 36 if (!extend) 37 _DeselectAllExcept(object); 38 39 bool success = false; 40 41 if (!object->IsSelected()) { 42 43 #if DEBUG 44 if (fSelected.HasItem((void*)object)) 45 debugger("Selection::Select() - " 46 "unselected object in list!"); 47 #endif 48 49 if (fSelected.AddItem((void*)object)) { 50 object->_SetSelected(true); 51 success = true; 52 53 Notify(); 54 } else { 55 fprintf(stderr, "Selection::Select() - out of memory\n"); 56 } 57 } else { 58 59 #if DEBUG 60 if (!fSelected.HasItem((void*)object)) 61 debugger("Selection::Select() - " 62 "already selected object not in list!"); 63 #endif 64 65 success = true; 66 // object already in list 67 } 68 69 return success; 70 } 71 72 // Deselect 73 void 74 Selection::Deselect(Selectable* object) 75 { 76 if (object->IsSelected()) { 77 if (!fSelected.RemoveItem((void*)object)) 78 debugger("Selection::Deselect() - " 79 "selected object not within list!"); 80 object->_SetSelected(false); 81 82 Notify(); 83 } 84 } 85 86 // DeselectAll 87 void 88 Selection::DeselectAll() 89 { 90 _DeselectAllExcept(NULL); 91 } 92 93 // #pragma mark - 94 95 // SelectableAt 96 Selectable* 97 Selection::SelectableAt(int32 index) const 98 { 99 return (Selectable*)fSelected.ItemAt(index); 100 } 101 102 // SelectableAtFast 103 Selectable* 104 Selection::SelectableAtFast(int32 index) const 105 { 106 return (Selectable*)fSelected.ItemAtFast(index); 107 } 108 109 // CountSelected 110 int32 111 Selection::CountSelected() const 112 { 113 return fSelected.CountItems(); 114 } 115 116 // #pragma mark - 117 118 // _DeselectAllExcept 119 void 120 Selection::_DeselectAllExcept(Selectable* except) 121 { 122 bool notify = false; 123 bool containedExcept = false; 124 125 int32 count = fSelected.CountItems(); 126 for (int32 i = 0; i < count; i++) { 127 Selectable* object = (Selectable*)fSelected.ItemAtFast(i); 128 if (object != except) { 129 object->_SetSelected(false); 130 notify = true; 131 } else { 132 containedExcept = true; 133 } 134 } 135 136 fSelected.MakeEmpty(); 137 138 // if the "except" object was previously 139 // in the selection, add it again after 140 // making the selection list empty 141 if (containedExcept) 142 fSelected.AddItem(except); 143 144 if (notify) 145 Notify(); 146 } 147 148