ListView.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "CheckBox.h"
  24. #include "Context.h"
  25. #include "InputEvents.h"
  26. #include "ListView.h"
  27. #include "Log.h"
  28. #include "Sort.h"
  29. #include "StringUtils.h"
  30. #include "UIEvents.h"
  31. #include "DebugNew.h"
  32. namespace Urho3D
  33. {
  34. static const char* highlightModes[] =
  35. {
  36. "Never",
  37. "Focus",
  38. "Always",
  39. 0
  40. };
  41. template<> HighlightMode Variant::Get<HighlightMode>() const
  42. {
  43. return (HighlightMode)GetInt();
  44. }
  45. static const ShortStringHash expandedHash("Expanded");
  46. extern const char* UI_CATEGORY;
  47. bool GetItemExpanded(UIElement* item)
  48. {
  49. return item ? item->GetVar(expandedHash).GetBool() : false;
  50. }
  51. void SetItemExpanded(UIElement* item, bool enable)
  52. {
  53. item->SetVar(expandedHash, enable);
  54. }
  55. static const ShortStringHash hierarchyParentHash("HierarchyParent");
  56. bool GetItemHierarchyParent(UIElement* item)
  57. {
  58. return item ? item->GetVar(hierarchyParentHash).GetBool() : false;
  59. }
  60. void SetItemHierarchyParent(UIElement* item, bool enable)
  61. {
  62. item->SetVar(hierarchyParentHash, enable);
  63. }
  64. /// Hierarchy container (used by ListView internally when in hierarchy mode).
  65. class HierarchyContainer : public UIElement
  66. {
  67. OBJECT(HierarchyContainer);
  68. public:
  69. /// Construct.
  70. HierarchyContainer(Context* context, ListView* listView, UIElement* overlayContainer) :
  71. UIElement(context),
  72. listView_(listView),
  73. overlayContainer_(overlayContainer)
  74. {
  75. SubscribeToEvent(this, E_LAYOUTUPDATED, HANDLER(HierarchyContainer, HandleLayoutUpdated));
  76. SubscribeToEvent(overlayContainer->GetParent(), E_VIEWCHANGED, HANDLER(HierarchyContainer, HandleViewChanged));
  77. SubscribeToEvent(E_UIMOUSECLICK, HANDLER(HierarchyContainer, HandleUIMouseClick));
  78. }
  79. /// Handle layout updated by adjusting the position of the overlays.
  80. void HandleLayoutUpdated(StringHash eventType, VariantMap& eventData)
  81. {
  82. // Adjust the container size for child clipping effect
  83. overlayContainer_->SetSize(GetParent()->GetSize());
  84. for (unsigned i = 0; i < children_.Size(); ++i)
  85. {
  86. const IntVector2& position = children_[i]->GetPosition();
  87. CheckBox* overlay = static_cast<CheckBox*>(overlayContainer_->GetChild(i));
  88. bool visible = children_[i]->IsVisible() && GetItemHierarchyParent(children_[i]);
  89. overlay->SetVisible(visible);
  90. if (visible)
  91. {
  92. overlay->SetPosition(position.x_, position.y_);
  93. overlay->SetChecked(GetItemExpanded(children_[i]));
  94. }
  95. }
  96. }
  97. /// Handle view changed by scrolling the overlays in tandem.
  98. void HandleViewChanged(StringHash eventType, VariantMap& eventData)
  99. {
  100. using namespace ViewChanged;
  101. int x = eventData[P_X].GetInt();
  102. int y = eventData[P_Y].GetInt();
  103. IntRect panelBorder = GetParent()->GetClipBorder();
  104. overlayContainer_->SetChildOffset(IntVector2(-x + panelBorder.left_, -y + panelBorder.top_));
  105. }
  106. /// Handle mouse click on overlays by toggling the expansion state of the corresponding item
  107. void HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
  108. {
  109. using namespace UIMouseClick;
  110. UIElement* overlay = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  111. if (overlay)
  112. {
  113. const Vector<SharedPtr<UIElement> >& children = overlayContainer_->GetChildren();
  114. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Find(SharedPtr<UIElement>(overlay));
  115. if (i != children.End())
  116. listView_->ToggleExpand(i - children.Begin());
  117. }
  118. }
  119. /// Insert a child element into a specific position in the child list.
  120. void InsertChild(unsigned index, UIElement* element)
  121. {
  122. // Insert the overlay at the same index position to the overlay container
  123. CheckBox* overlay = static_cast<CheckBox*>(overlayContainer_->CreateChild(CheckBox::GetTypeStatic(), String::EMPTY, index));
  124. overlay->SetStyle("HierarchyListViewOverlay");
  125. int baseIndent = listView_->GetBaseIndent();
  126. int indent = element->GetIndent() - baseIndent - 1;
  127. overlay->SetIndent(indent);
  128. overlay->SetFixedWidth((indent + 1) * element->GetIndentSpacing());
  129. // Then insert the element as child as per normal
  130. UIElement::InsertChild(index, element);
  131. }
  132. private:
  133. // Parent list view.
  134. ListView* listView_;
  135. // Container for overlay checkboxes.
  136. UIElement* overlayContainer_;
  137. };
  138. ListView::ListView(Context* context) :
  139. ScrollView(context),
  140. highlightMode_(HM_FOCUS),
  141. multiselect_(false),
  142. hierarchyMode_(true), // Init to true here so that the setter below takes effect
  143. baseIndent_(0),
  144. clearSelectionOnDefocus_(false)
  145. {
  146. resizeContentWidth_ = true;
  147. // By default list view is set to non-hierarchy mode
  148. SetHierarchyMode(false);
  149. SubscribeToEvent(E_UIMOUSECLICK, HANDLER(ListView, HandleUIMouseClick));
  150. SubscribeToEvent(E_UIMOUSEDOUBLECLICK, HANDLER(ListView, HandleUIMouseDoubleClick));
  151. SubscribeToEvent(E_FOCUSCHANGED, HANDLER(ListView, HandleItemFocusChanged));
  152. SubscribeToEvent(this, E_DEFOCUSED, HANDLER(ListView, HandleFocusChanged));
  153. SubscribeToEvent(this, E_FOCUSED, HANDLER(ListView, HandleFocusChanged));
  154. }
  155. ListView::~ListView()
  156. {
  157. }
  158. void ListView::RegisterObject(Context* context)
  159. {
  160. context->RegisterFactory<ListView>(UI_CATEGORY);
  161. COPY_BASE_ATTRIBUTES(HierarchyContainer, UIElement);
  162. COPY_BASE_ATTRIBUTES(ListView, ScrollView);
  163. ENUM_ACCESSOR_ATTRIBUTE(ListView, "Highlight Mode", GetHighlightMode, SetHighlightMode, HighlightMode, highlightModes, HM_FOCUS, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Multiselect", GetMultiselect, SetMultiselect, bool, false, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Hierarchy Mode", GetHierarchyMode, SetHierarchyMode, bool, false, AM_FILE);
  166. ACCESSOR_ATTRIBUTE(ListView, VAR_INT, "Base Indent", GetBaseIndent, SetBaseIndent, int, 0, AM_FILE);
  167. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Clear Sel. On Defocus", GetClearSelectionOnDefocus, SetClearSelectionOnDefocus, bool, false, AM_FILE);
  168. }
  169. void ListView::OnKey(int key, int buttons, int qualifiers)
  170. {
  171. // If no selection, can not move with keys
  172. unsigned numItems = GetNumItems();
  173. unsigned selection = GetSelection();
  174. // If either shift or ctrl held down, add to selection if multiselect enabled
  175. bool additive = multiselect_ && qualifiers & (QUAL_SHIFT | QUAL_CTRL);
  176. int delta = M_MAX_INT;
  177. int pageDirection = 1;
  178. if (numItems)
  179. {
  180. switch (key)
  181. {
  182. case KEY_LEFT:
  183. case KEY_RIGHT:
  184. if (selection != M_MAX_UNSIGNED && hierarchyMode_)
  185. {
  186. Expand(selection, key == KEY_RIGHT);
  187. return;
  188. }
  189. break;
  190. case KEY_RETURN:
  191. case KEY_RETURN2:
  192. case KEY_KP_ENTER:
  193. if (selection != M_MAX_UNSIGNED && hierarchyMode_)
  194. {
  195. ToggleExpand(selection);
  196. return;
  197. }
  198. break;
  199. case KEY_UP:
  200. delta = -1;
  201. break;
  202. case KEY_DOWN:
  203. delta = 1;
  204. break;
  205. case KEY_PAGEUP:
  206. pageDirection = -1;
  207. // Fallthru
  208. case KEY_PAGEDOWN:
  209. {
  210. // Convert page step to pixels and see how many items have to be skipped to reach that many pixels
  211. if (selection == M_MAX_UNSIGNED)
  212. selection = 0; // Assume as if first item is selected
  213. int stepPixels = ((int)(pageStep_ * scrollPanel_->GetHeight())) - contentElement_->GetChild(selection)->GetHeight();
  214. unsigned newSelection = selection;
  215. unsigned okSelection = selection;
  216. unsigned invisible = 0;
  217. while (newSelection < numItems)
  218. {
  219. UIElement* item = GetItem(newSelection);
  220. int height = 0;
  221. if (item->IsVisible())
  222. {
  223. height = item->GetHeight();
  224. okSelection = newSelection;
  225. }
  226. else
  227. ++invisible;
  228. if (stepPixels < height)
  229. break;
  230. stepPixels -= height;
  231. newSelection += pageDirection;
  232. }
  233. delta = okSelection - selection - pageDirection * invisible;
  234. }
  235. break;
  236. case KEY_HOME:
  237. delta = -(int)GetNumItems();
  238. break;
  239. case KEY_END:
  240. delta = GetNumItems();
  241. break;
  242. }
  243. }
  244. if (delta != M_MAX_INT)
  245. {
  246. ChangeSelection(delta, additive);
  247. return;
  248. }
  249. using namespace UnhandledKey;
  250. VariantMap eventData;
  251. eventData[P_ELEMENT] = (void*)this;
  252. eventData[P_KEY] = key;
  253. eventData[P_BUTTONS] = buttons;
  254. eventData[P_QUALIFIERS] = qualifiers;
  255. SendEvent(E_UNHANDLEDKEY, eventData);
  256. }
  257. void ListView::OnResize()
  258. {
  259. ScrollView::OnResize();
  260. // When in hierarchy mode also need to resize the overlay container
  261. if (hierarchyMode_)
  262. overlayContainer_->SetSize(scrollPanel_->GetSize());
  263. }
  264. void ListView::AddItem(UIElement* item)
  265. {
  266. InsertItem(M_MAX_UNSIGNED, item);
  267. }
  268. void ListView::InsertItem(unsigned index, UIElement* item, UIElement* parentItem)
  269. {
  270. if (!item || item->GetParent() == contentElement_)
  271. return;
  272. // Enable input so that clicking the item can be detected
  273. item->SetEnabled(true);
  274. item->SetSelected(false);
  275. unsigned numItems = contentElement_->GetNumChildren();
  276. if (hierarchyMode_)
  277. {
  278. int baseIndent = baseIndent_;
  279. if (parentItem)
  280. {
  281. baseIndent = parentItem->GetIndent();
  282. SetItemHierarchyParent(parentItem, true);
  283. // Adjust the index to ensure it is within the children index limit of the parent item
  284. unsigned indexLimit = FindItem(parentItem);
  285. if (index <= indexLimit)
  286. index = indexLimit + 1;
  287. else
  288. {
  289. while (++indexLimit < numItems)
  290. {
  291. if (contentElement_->GetChild(indexLimit)->GetIndent() <= baseIndent)
  292. break;
  293. }
  294. if (index > indexLimit)
  295. index = indexLimit;
  296. }
  297. }
  298. item->SetIndent(baseIndent + 1);
  299. SetItemExpanded(item, item->IsVisible());
  300. // Use the 'overrided' version to insert the child item
  301. static_cast<HierarchyContainer*>(contentElement_.Get())->InsertChild(index, item);
  302. }
  303. else
  304. {
  305. if (index > numItems)
  306. index = numItems;
  307. contentElement_->InsertChild(index, item);
  308. }
  309. // If necessary, shift the following selections
  310. if (!selections_.Empty())
  311. {
  312. for (unsigned i = 0; i < selections_.Size(); ++i)
  313. {
  314. if (selections_[i] >= index)
  315. ++selections_[i];
  316. }
  317. UpdateSelectionEffect();
  318. }
  319. }
  320. void ListView::RemoveItem(UIElement* item, unsigned index)
  321. {
  322. if (!item)
  323. return;
  324. unsigned numItems = GetNumItems();
  325. for (unsigned i = index; i < numItems; ++i)
  326. {
  327. if (GetItem(i) == item)
  328. {
  329. item->SetSelected(false);
  330. selections_.Remove(i);
  331. unsigned removed = 1;
  332. if (hierarchyMode_)
  333. {
  334. // Remove any child items in hierarchy mode
  335. if (GetItemHierarchyParent(item))
  336. {
  337. int baseIndent = item->GetIndent();
  338. for (unsigned j = i + 1; ; ++j)
  339. {
  340. UIElement* childItem = GetItem(i + 1);
  341. if (!childItem)
  342. break;
  343. if (childItem->GetIndent() > baseIndent)
  344. {
  345. childItem->SetSelected(false);
  346. selections_.Erase(j);
  347. contentElement_->RemoveChildAtIndex(i + 1);
  348. overlayContainer_->RemoveChildAtIndex(i + 1);
  349. ++removed;
  350. }
  351. else
  352. break;
  353. }
  354. }
  355. // Check if the parent of removed item still has other children
  356. if (i > 0)
  357. {
  358. int baseIndent = item->GetIndent();
  359. UIElement* prevKin = GetItem(i - 1); // Could be parent or sibling
  360. if (prevKin->GetIndent() < baseIndent)
  361. {
  362. UIElement* nextKin = GetItem(i + 1); // Could be sibling or parent-sibling or 0 if index out of bound
  363. if (!nextKin || nextKin->GetIndent() < baseIndent)
  364. {
  365. // If we reach here then the parent has no other children
  366. SetItemHierarchyParent(prevKin, false);
  367. }
  368. }
  369. }
  370. // Remove the overlay at the same index
  371. overlayContainer_->RemoveChildAtIndex(i);
  372. }
  373. // If necessary, shift the following selections
  374. if (!selections_.Empty())
  375. {
  376. for (unsigned j = 0; j < selections_.Size(); ++j)
  377. {
  378. if (selections_[j] > i)
  379. selections_[j] -= removed;
  380. }
  381. UpdateSelectionEffect();
  382. }
  383. contentElement_->RemoveChildAtIndex(i);
  384. break;
  385. }
  386. }
  387. }
  388. void ListView::RemoveItem(unsigned index)
  389. {
  390. RemoveItem(GetItem(index), index);
  391. }
  392. void ListView::RemoveAllItems()
  393. {
  394. contentElement_->DisableLayoutUpdate();
  395. ClearSelection();
  396. contentElement_->RemoveAllChildren();
  397. if (hierarchyMode_)
  398. overlayContainer_->RemoveAllChildren();
  399. contentElement_->EnableLayoutUpdate();
  400. contentElement_->UpdateLayout();
  401. }
  402. void ListView::SetSelection(unsigned index)
  403. {
  404. PODVector<unsigned> indices;
  405. indices.Push(index);
  406. SetSelections(indices);
  407. EnsureItemVisibility(index);
  408. }
  409. void ListView::SetSelections(const PODVector<unsigned>& indices)
  410. {
  411. // Make a weak pointer to self to check for destruction as a response to events
  412. WeakPtr<ListView> self(this);
  413. unsigned numItems = GetNumItems();
  414. // Remove first items that should no longer be selected
  415. for (PODVector<unsigned>::Iterator i = selections_.Begin(); i != selections_.End();)
  416. {
  417. unsigned index = *i;
  418. if (!indices.Contains(index))
  419. {
  420. i = selections_.Erase(i);
  421. using namespace ItemSelected;
  422. VariantMap eventData;
  423. eventData[P_ELEMENT] = (void*)this;
  424. eventData[P_SELECTION] = index;
  425. SendEvent(E_ITEMDESELECTED, eventData);
  426. if (self.Expired())
  427. return;
  428. }
  429. else
  430. ++i;
  431. }
  432. bool added = false;
  433. // Then add missing items
  434. for (PODVector<unsigned>::ConstIterator i = indices.Begin(); i != indices.End(); ++i)
  435. {
  436. unsigned index = *i;
  437. if (index < numItems)
  438. {
  439. // In singleselect mode, resend the event even for the same selection
  440. bool duplicate = selections_.Contains(index);
  441. if (!duplicate || !multiselect_)
  442. {
  443. if (!duplicate)
  444. {
  445. selections_.Push(index);
  446. added = true;
  447. }
  448. using namespace ItemSelected;
  449. VariantMap eventData;
  450. eventData[P_ELEMENT] = (void*)this;
  451. eventData[P_SELECTION] = *i;
  452. SendEvent(E_ITEMSELECTED, eventData);
  453. if (self.Expired())
  454. return;
  455. }
  456. }
  457. // If no multiselect enabled, allow setting only one item
  458. if (!multiselect_)
  459. break;
  460. }
  461. // Re-sort selections if necessary
  462. if (added)
  463. Sort(selections_.Begin(), selections_.End());
  464. UpdateSelectionEffect();
  465. SendEvent(E_SELECTIONCHANGED);
  466. }
  467. void ListView::AddSelection(unsigned index)
  468. {
  469. // Make a weak pointer to self to check for destruction as a response to events
  470. WeakPtr<ListView> self(this);
  471. if (!multiselect_)
  472. SetSelection(index);
  473. else
  474. {
  475. if (index >= GetNumItems())
  476. return;
  477. if (!selections_.Contains(index))
  478. {
  479. selections_.Push(index);
  480. using namespace ItemSelected;
  481. VariantMap eventData;
  482. eventData[P_ELEMENT] = (void*)this;
  483. eventData[P_SELECTION] = index;
  484. SendEvent(E_ITEMSELECTED, eventData);
  485. if (self.Expired())
  486. return;
  487. Sort(selections_.Begin(), selections_.End());
  488. }
  489. EnsureItemVisibility(index);
  490. UpdateSelectionEffect();
  491. SendEvent(E_SELECTIONCHANGED);
  492. }
  493. }
  494. void ListView::RemoveSelection(unsigned index)
  495. {
  496. if (index >= GetNumItems())
  497. return;
  498. if (selections_.Remove(index))
  499. {
  500. using namespace ItemSelected;
  501. VariantMap eventData;
  502. eventData[P_ELEMENT] = (void*)this;
  503. eventData[P_SELECTION] = index;
  504. SendEvent(E_ITEMDESELECTED, eventData);
  505. }
  506. EnsureItemVisibility(index);
  507. UpdateSelectionEffect();
  508. SendEvent(E_SELECTIONCHANGED);
  509. }
  510. void ListView::ToggleSelection(unsigned index)
  511. {
  512. unsigned numItems = GetNumItems();
  513. if (index >= numItems)
  514. return;
  515. if (selections_.Contains(index))
  516. RemoveSelection(index);
  517. else
  518. AddSelection(index);
  519. }
  520. void ListView::ChangeSelection(int delta, bool additive)
  521. {
  522. unsigned numItems = GetNumItems();
  523. if (selections_.Empty())
  524. {
  525. // Select first item if there is no selection yet
  526. if (numItems > 0)
  527. SetSelection(0);
  528. if (abs(delta) == 1)
  529. return;
  530. }
  531. if (!multiselect_)
  532. additive = false;
  533. // If going downwards, use the last selection as a base. Otherwise use first
  534. unsigned selection = delta > 0 ? selections_.Back() : selections_.Front();
  535. int direction = delta > 0 ? 1 : -1;
  536. unsigned newSelection = selection;
  537. unsigned okSelection = selection;
  538. PODVector<unsigned> indices = selections_;
  539. while (delta != 0)
  540. {
  541. newSelection += direction;
  542. if (newSelection >= numItems)
  543. break;
  544. UIElement* item = GetItem(newSelection);
  545. if (item->IsVisible())
  546. {
  547. indices.Push(okSelection = newSelection);
  548. delta -= direction;
  549. }
  550. }
  551. if (!additive)
  552. SetSelection(okSelection);
  553. else
  554. SetSelections(indices);
  555. }
  556. void ListView::ClearSelection()
  557. {
  558. SetSelections(PODVector<unsigned>());
  559. }
  560. void ListView::SetHighlightMode(HighlightMode mode)
  561. {
  562. highlightMode_ = mode;
  563. UpdateSelectionEffect();
  564. }
  565. void ListView::SetMultiselect(bool enable)
  566. {
  567. multiselect_ = enable;
  568. }
  569. void ListView::SetHierarchyMode(bool enable)
  570. {
  571. if (enable == hierarchyMode_)
  572. return;
  573. hierarchyMode_ = enable;
  574. UIElement* container;
  575. if (enable)
  576. {
  577. overlayContainer_ = new UIElement(context_);
  578. overlayContainer_->SetName("LV_OverlayContainer");
  579. overlayContainer_->SetInternal(true);
  580. AddChild(overlayContainer_);
  581. overlayContainer_->SetSortChildren(false);
  582. overlayContainer_->SetClipChildren(true);
  583. container = new HierarchyContainer(context_, this, overlayContainer_);
  584. }
  585. else
  586. {
  587. if (overlayContainer_)
  588. {
  589. RemoveChild(overlayContainer_);
  590. overlayContainer_.Reset();
  591. }
  592. container = new UIElement(context_);
  593. }
  594. container->SetName("LV_ItemContainer");
  595. container->SetInternal(true);
  596. SetContentElement(container);
  597. container->SetEnabled(true);
  598. container->SetSortChildren(false);
  599. }
  600. void ListView::SetBaseIndent(int baseIndent)
  601. {
  602. baseIndent_ = baseIndent;
  603. UpdateLayout();
  604. }
  605. void ListView::SetClearSelectionOnDefocus(bool enable)
  606. {
  607. if (enable != clearSelectionOnDefocus_)
  608. {
  609. clearSelectionOnDefocus_ = enable;
  610. if (clearSelectionOnDefocus_ && !HasFocus())
  611. ClearSelection();
  612. }
  613. }
  614. void ListView::Expand(unsigned index, bool enable, bool recursive)
  615. {
  616. if (!hierarchyMode_)
  617. return;
  618. unsigned numItems = GetNumItems();
  619. if (index >= numItems)
  620. return;
  621. UIElement* item = GetItem(index++);
  622. SetItemExpanded(item, enable);
  623. int baseIndent = item->GetIndent();
  624. PODVector<bool> expanded(baseIndent + 1);
  625. expanded[baseIndent] = enable;
  626. contentElement_->DisableLayoutUpdate();
  627. while (index < numItems)
  628. {
  629. item = GetItem(index++);
  630. int indent = item->GetIndent();
  631. if (indent <= baseIndent)
  632. break;
  633. // Propagate the state to children when it is recursive
  634. if (recursive)
  635. SetItemExpanded(item, enable);
  636. // Use the parent expanded flag to influence the visibility of its children
  637. bool visible = enable && expanded[indent - 1];
  638. item->SetVisible(visible);
  639. if (indent >= (int)expanded.Size())
  640. expanded.Resize(indent + 1);
  641. expanded[indent] = visible && GetItemExpanded(item);
  642. }
  643. contentElement_->EnableLayoutUpdate();
  644. contentElement_->UpdateLayout();
  645. }
  646. void ListView::ToggleExpand(unsigned index, bool recursive)
  647. {
  648. if (!hierarchyMode_)
  649. return;
  650. unsigned numItems = GetNumItems();
  651. if (index >= numItems)
  652. return;
  653. UIElement* item = GetItem(index);
  654. Expand(index, !GetItemExpanded(item), recursive);
  655. }
  656. unsigned ListView::GetNumItems() const
  657. {
  658. return contentElement_->GetNumChildren();
  659. }
  660. UIElement* ListView::GetItem(unsigned index) const
  661. {
  662. return contentElement_->GetChild(index);
  663. }
  664. PODVector<UIElement*> ListView::GetItems() const
  665. {
  666. PODVector<UIElement*> items;
  667. contentElement_->GetChildren(items);
  668. return items;
  669. }
  670. unsigned ListView::FindItem(UIElement* item) const
  671. {
  672. if (!item)
  673. return M_MAX_UNSIGNED;
  674. // Early-out by checking if the item belongs to the listview hierarchy at all
  675. if (item->GetParent() != contentElement_)
  676. return M_MAX_UNSIGNED;
  677. const Vector<SharedPtr<UIElement> >& children = contentElement_->GetChildren();
  678. // Binary search for list item based on screen coordinate Y
  679. if (contentElement_->GetLayoutMode() == LM_VERTICAL && item->GetHeight())
  680. {
  681. int itemY = item->GetScreenPosition().y_;
  682. int left = 0;
  683. int right = children.Size() - 1;
  684. while (right >= left)
  685. {
  686. int mid = (left + right) / 2;
  687. if (children[mid] == item)
  688. return mid;
  689. if (itemY < children[mid]->GetScreenPosition().y_)
  690. right = mid - 1;
  691. else
  692. left = mid + 1;
  693. }
  694. }
  695. // Fallback to linear search in case the coordinates/sizes were not yet initialized
  696. for (unsigned i = 0; i < children.Size(); ++i)
  697. {
  698. if (children[i] == item)
  699. return i;
  700. }
  701. return M_MAX_UNSIGNED;
  702. }
  703. unsigned ListView::GetSelection() const
  704. {
  705. if (selections_.Empty())
  706. return M_MAX_UNSIGNED;
  707. else
  708. return GetSelections().Front();
  709. }
  710. UIElement* ListView::GetSelectedItem() const
  711. {
  712. return contentElement_->GetChild(GetSelection());
  713. }
  714. PODVector<UIElement*> ListView::GetSelectedItems() const
  715. {
  716. PODVector<UIElement*> ret;
  717. for (PODVector<unsigned>::ConstIterator i = selections_.Begin(); i != selections_.End(); ++i)
  718. {
  719. UIElement* item = GetItem(*i);
  720. if (item)
  721. ret.Push(item);
  722. }
  723. return ret;
  724. }
  725. bool ListView::IsSelected(unsigned index) const
  726. {
  727. return selections_.Contains(index);
  728. }
  729. bool ListView::IsExpanded(unsigned index) const
  730. {
  731. return GetItemExpanded(contentElement_->GetChild(index));
  732. }
  733. bool ListView::FilterImplicitAttributes(XMLElement& dest) const
  734. {
  735. if (!ScrollView::FilterImplicitAttributes(dest))
  736. return false;
  737. XMLElement childElem = dest.GetChild("element"); // Horizontal scroll bar
  738. if (!childElem)
  739. return false;
  740. childElem = childElem.GetNext("element"); // Vertical scroll bar
  741. if (!childElem)
  742. return false;
  743. childElem = childElem.GetNext("element"); // Scroll panel
  744. if (!childElem)
  745. return false;
  746. XMLElement containerElem = childElem.GetChild("element"); // Item container
  747. if (!containerElem)
  748. return false;
  749. if (!RemoveChildXML(containerElem, "Name", "LV_ItemContainer"))
  750. return false;
  751. if (!RemoveChildXML(containerElem, "Is Enabled", "true"))
  752. return false;
  753. if (!RemoveChildXML(containerElem, "Layout Mode", "Vertical"))
  754. return false;
  755. if (!RemoveChildXML(containerElem, "Size"))
  756. return false;
  757. if (hierarchyMode_)
  758. {
  759. containerElem = childElem.GetNext("element"); // Overlay container
  760. if (!containerElem)
  761. return false;
  762. if (!RemoveChildXML(containerElem, "Name", "LV_OverlayContainer"))
  763. return false;
  764. if (!RemoveChildXML(containerElem, "Clip Children", "true"))
  765. return false;
  766. if (!RemoveChildXML(containerElem, "Size"))
  767. return false;
  768. }
  769. return true;
  770. }
  771. void ListView::UpdateSelectionEffect()
  772. {
  773. unsigned numItems = GetNumItems();
  774. bool highlighted = highlightMode_ == HM_ALWAYS || HasFocus();
  775. for (unsigned i = 0; i < numItems; ++i)
  776. {
  777. UIElement* item = GetItem(i);
  778. if (highlightMode_ != HM_NEVER && selections_.Contains(i))
  779. item->SetSelected(highlighted);
  780. else
  781. item->SetSelected(false);
  782. }
  783. }
  784. void ListView::EnsureItemVisibility(unsigned index)
  785. {
  786. EnsureItemVisibility(GetItem(index));
  787. }
  788. void ListView::EnsureItemVisibility(UIElement* item)
  789. {
  790. if (!item || !item->IsVisible())
  791. return;
  792. IntVector2 newView = GetViewPosition();
  793. IntVector2 currentOffset = item->GetPosition() - newView;
  794. const IntRect& clipBorder = scrollPanel_->GetClipBorder();
  795. IntVector2 windowSize(scrollPanel_->GetWidth() - clipBorder.left_ - clipBorder.right_, scrollPanel_->GetHeight() -
  796. clipBorder.top_ - clipBorder.bottom_);
  797. if (currentOffset.y_ < 0)
  798. newView.y_ += currentOffset.y_;
  799. if (currentOffset.y_ + item->GetHeight() > windowSize.y_)
  800. newView.y_ += currentOffset.y_ + item->GetHeight() - windowSize.y_;
  801. SetViewPosition(newView);
  802. }
  803. void ListView::HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
  804. {
  805. int button = eventData[UIMouseClick::P_BUTTON].GetInt();
  806. int buttons = eventData[UIMouseClick::P_BUTTONS].GetInt();
  807. int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
  808. UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  809. // Check if the clicked element belongs to the list
  810. unsigned i = FindItem(element);
  811. if (i >= GetNumItems())
  812. return;
  813. // If not editable, repeat the previous selection. This will send an event and allow eg. a dropdownlist to close
  814. if (!editable_)
  815. {
  816. SetSelections(selections_);
  817. return;
  818. }
  819. if (button == MOUSEB_LEFT)
  820. {
  821. // Single selection
  822. if (!multiselect_ || !qualifiers)
  823. SetSelection(i);
  824. // Check multiselect with shift & ctrl
  825. if (multiselect_)
  826. {
  827. if (qualifiers & QUAL_SHIFT)
  828. {
  829. if (selections_.Empty())
  830. SetSelection(i);
  831. else
  832. {
  833. unsigned first = selections_.Front();
  834. unsigned last = selections_.Back();
  835. PODVector<unsigned> newSelections = selections_;
  836. if (i == first || i == last)
  837. {
  838. for (unsigned j = first; j <= last; ++j)
  839. newSelections.Push(j);
  840. }
  841. else if (i < first)
  842. {
  843. for (unsigned j = i; j <= first; ++j)
  844. newSelections.Push(j);
  845. }
  846. else if (i < last)
  847. {
  848. if ((abs((int)i - (int)first)) <= (abs((int)i - (int)last)))
  849. {
  850. for (unsigned j = first; j <= i; ++j)
  851. newSelections.Push(j);
  852. }
  853. else
  854. {
  855. for (unsigned j = i; j <= last; ++j)
  856. newSelections.Push(j);
  857. }
  858. }
  859. else if (i > last)
  860. {
  861. for (unsigned j = last; j <= i; ++j)
  862. newSelections.Push(j);
  863. }
  864. SetSelections(newSelections);
  865. }
  866. }
  867. else if (qualifiers & QUAL_CTRL)
  868. ToggleSelection(i);
  869. }
  870. }
  871. // Propagate the click as an event. Also include right-clicks
  872. VariantMap clickEventData;
  873. clickEventData[ItemClicked::P_ELEMENT] = (void*)this;
  874. clickEventData[ItemClicked::P_ITEM] = (void*)element;
  875. clickEventData[ItemClicked::P_SELECTION] = i;
  876. clickEventData[ItemClicked::P_BUTTON] = button;
  877. clickEventData[ItemClicked::P_BUTTONS] = buttons;
  878. clickEventData[ItemClicked::P_QUALIFIERS] = qualifiers;
  879. SendEvent(E_ITEMCLICKED, clickEventData);
  880. }
  881. void ListView::HandleUIMouseDoubleClick(StringHash eventType, VariantMap& eventData)
  882. {
  883. int button = eventData[UIMouseClick::P_BUTTON].GetInt();
  884. int buttons = eventData[UIMouseClick::P_BUTTONS].GetInt();
  885. int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
  886. UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  887. // Check if the clicked element belongs to the list
  888. unsigned i = FindItem(element);
  889. if (i >= GetNumItems())
  890. return;
  891. VariantMap clickEventData;
  892. clickEventData[ItemDoubleClicked::P_ELEMENT] = (void*)this;
  893. clickEventData[ItemDoubleClicked::P_ITEM] = (void*)element;
  894. clickEventData[ItemDoubleClicked::P_SELECTION] = i;
  895. clickEventData[ItemDoubleClicked::P_BUTTON] = button;
  896. clickEventData[ItemDoubleClicked::P_BUTTONS] = buttons;
  897. clickEventData[ItemDoubleClicked::P_QUALIFIERS] = qualifiers;
  898. SendEvent(E_ITEMDOUBLECLICKED, clickEventData);
  899. }
  900. void ListView::HandleItemFocusChanged(StringHash eventType, VariantMap& eventData)
  901. {
  902. using namespace FocusChanged;
  903. UIElement* element = static_cast<UIElement*>(eventData[P_ELEMENT].GetPtr());
  904. while (element)
  905. {
  906. // If the focused element or its parent is in the list, scroll the list to make the item visible
  907. UIElement* parent = element->GetParent();
  908. if (parent == contentElement_)
  909. {
  910. EnsureItemVisibility(element);
  911. return;
  912. }
  913. element = parent;
  914. }
  915. }
  916. void ListView::HandleFocusChanged(StringHash eventType, VariantMap& eventData)
  917. {
  918. scrollPanel_->SetSelected(eventType == E_FOCUSED);
  919. if (clearSelectionOnDefocus_ && eventType == E_DEFOCUSED)
  920. ClearSelection();
  921. else if (highlightMode_ == HM_FOCUS)
  922. UpdateSelectionEffect();
  923. }
  924. }