ListView.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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("ListViewHierarchyOverlay");
  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, HandleFocusChanged));
  152. }
  153. ListView::~ListView()
  154. {
  155. }
  156. void ListView::RegisterObject(Context* context)
  157. {
  158. context->RegisterFactory<ListView>(UI_CATEGORY);
  159. COPY_BASE_ATTRIBUTES(HierarchyContainer, UIElement);
  160. COPY_BASE_ATTRIBUTES(ListView, ScrollView);
  161. ENUM_ACCESSOR_ATTRIBUTE(ListView, "Highlight Mode", GetHighlightMode, SetHighlightMode, HighlightMode, highlightModes, HM_FOCUS, AM_FILE);
  162. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Multiselect", GetMultiselect, SetMultiselect, bool, false, AM_FILE);
  163. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Hierarchy Mode", GetHierarchyMode, SetHierarchyMode, bool, false, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(ListView, VAR_INT, "Base Indent", GetBaseIndent, SetBaseIndent, int, 0, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Clear Sel. On Defocus", GetClearSelectionOnDefocus, SetClearSelectionOnDefocus, bool, false, AM_FILE);
  166. }
  167. void ListView::OnKey(int key, int buttons, int qualifiers)
  168. {
  169. // If no selection, can not move with keys
  170. unsigned numItems = GetNumItems();
  171. unsigned selection = GetSelection();
  172. // If either shift or ctrl held down, add to selection if multiselect enabled
  173. bool additive = multiselect_ && qualifiers & (QUAL_SHIFT | QUAL_CTRL);
  174. int delta = 0;
  175. int pageDirection = 1;
  176. if (selection != M_MAX_UNSIGNED && numItems)
  177. {
  178. switch (key)
  179. {
  180. case KEY_LEFT:
  181. case KEY_RIGHT:
  182. if (hierarchyMode_)
  183. {
  184. Expand(selection, key == KEY_RIGHT);
  185. return;
  186. }
  187. break;
  188. case KEY_RETURN:
  189. case KEY_RETURN2:
  190. case KEY_KP_ENTER:
  191. if (hierarchyMode_)
  192. {
  193. ToggleExpand(selection);
  194. return;
  195. }
  196. break;
  197. case KEY_UP:
  198. delta = -1;
  199. break;
  200. case KEY_DOWN:
  201. delta = 1;
  202. break;
  203. case KEY_PAGEUP:
  204. pageDirection = -1;
  205. // Fallthru
  206. case KEY_PAGEDOWN:
  207. {
  208. // Convert page step to pixels and see how many items have to be skipped to reach that many pixels
  209. int stepPixels = ((int)(pageStep_ * scrollPanel_->GetHeight())) - GetSelectedItem()->GetHeight();
  210. unsigned newSelection = selection;
  211. unsigned okSelection = selection;
  212. unsigned invisible = 0;
  213. while (newSelection < numItems)
  214. {
  215. UIElement* item = GetItem(newSelection);
  216. int height = 0;
  217. if (item->IsVisible())
  218. {
  219. height = item->GetHeight();
  220. okSelection = newSelection;
  221. }
  222. else
  223. ++invisible;
  224. if (stepPixels < height)
  225. break;
  226. stepPixels -= height;
  227. newSelection += pageDirection;
  228. }
  229. delta = okSelection - selection - pageDirection * invisible;
  230. }
  231. break;
  232. case KEY_HOME:
  233. delta = -(int)GetNumItems();
  234. break;
  235. case KEY_END:
  236. delta = GetNumItems();
  237. break;
  238. }
  239. }
  240. if (delta)
  241. {
  242. ChangeSelection(delta, additive);
  243. return;
  244. }
  245. using namespace UnhandledKey;
  246. VariantMap eventData;
  247. eventData[P_ELEMENT] = (void*)this;
  248. eventData[P_KEY] = key;
  249. eventData[P_BUTTONS] = buttons;
  250. eventData[P_QUALIFIERS] = qualifiers;
  251. SendEvent(E_UNHANDLEDKEY, eventData);
  252. }
  253. void ListView::OnResize()
  254. {
  255. ScrollView::OnResize();
  256. // When in hierarchy mode also need to resize the overlay container
  257. if (hierarchyMode_)
  258. overlayContainer_->SetSize(scrollPanel_->GetSize());
  259. }
  260. void ListView::AddItem(UIElement* item)
  261. {
  262. InsertItem(M_MAX_UNSIGNED, item);
  263. }
  264. void ListView::InsertItem(unsigned index, UIElement* item, UIElement* parentItem)
  265. {
  266. if (!item || item->GetParent() == contentElement_)
  267. return;
  268. // Enable input so that clicking the item can be detected
  269. item->SetEnabled(true);
  270. item->SetSelected(false);
  271. unsigned numItems = contentElement_->GetNumChildren();
  272. if (hierarchyMode_)
  273. {
  274. int baseIndent = baseIndent_;
  275. if (parentItem)
  276. {
  277. baseIndent = parentItem->GetIndent();
  278. SetItemHierarchyParent(parentItem, true);
  279. // Adjust the index to ensure it is within the children index limit of the parent item
  280. unsigned indexLimit = FindItem(parentItem);
  281. if (index <= indexLimit)
  282. index = indexLimit + 1;
  283. else
  284. {
  285. while (++indexLimit < numItems)
  286. {
  287. if (contentElement_->GetChild(indexLimit)->GetIndent() <= baseIndent)
  288. break;
  289. }
  290. if (index > indexLimit)
  291. index = indexLimit;
  292. }
  293. }
  294. item->SetIndent(baseIndent + 1);
  295. SetItemExpanded(item, item->IsVisible());
  296. // Use the 'overrided' version to insert the child item
  297. static_cast<HierarchyContainer*>(contentElement_.Get())->InsertChild(index, item);
  298. }
  299. else
  300. {
  301. if (index > numItems)
  302. index = numItems;
  303. contentElement_->InsertChild(index, item);
  304. }
  305. // If necessary, shift the following selections
  306. if (!selections_.Empty())
  307. {
  308. for (unsigned i = 0; i < selections_.Size(); ++i)
  309. {
  310. if (selections_[i] >= index)
  311. ++selections_[i];
  312. }
  313. UpdateSelectionEffect();
  314. }
  315. }
  316. void ListView::RemoveItem(UIElement* item, unsigned index)
  317. {
  318. if (!item)
  319. return;
  320. unsigned numItems = GetNumItems();
  321. for (unsigned i = index; i < numItems; ++i)
  322. {
  323. if (GetItem(i) == item)
  324. {
  325. item->SetSelected(false);
  326. selections_.Remove(i);
  327. unsigned removed = 1;
  328. if (hierarchyMode_)
  329. {
  330. // Remove any child items in hierarchy mode
  331. if (GetItemHierarchyParent(item))
  332. {
  333. int baseIndent = item->GetIndent();
  334. for (unsigned j = i + 1; ; ++j)
  335. {
  336. UIElement* childItem = GetItem(i + 1);
  337. if (!childItem)
  338. break;
  339. if (childItem->GetIndent() > baseIndent)
  340. {
  341. childItem->SetSelected(false);
  342. selections_.Erase(j);
  343. contentElement_->RemoveChildAtIndex(i + 1);
  344. overlayContainer_->RemoveChildAtIndex(i + 1);
  345. ++removed;
  346. }
  347. else
  348. break;
  349. }
  350. }
  351. // Check if the parent of removed item still has other children
  352. if (i > 0)
  353. {
  354. int baseIndent = item->GetIndent();
  355. UIElement* prevKin = GetItem(i - 1); // Could be parent or sibling
  356. if (prevKin->GetIndent() < baseIndent)
  357. {
  358. UIElement* nextKin = GetItem(i + 1); // Could be sibling or parent-sibling or 0 if index out of bound
  359. if (!nextKin || nextKin->GetIndent() < baseIndent)
  360. {
  361. // If we reach here then the parent has no other children
  362. SetItemHierarchyParent(prevKin, false);
  363. }
  364. }
  365. }
  366. // Remove the overlay at the same index
  367. overlayContainer_->RemoveChildAtIndex(i);
  368. }
  369. // If necessary, shift the following selections
  370. if (!selections_.Empty())
  371. {
  372. for (unsigned j = 0; j < selections_.Size(); ++j)
  373. {
  374. if (selections_[j] > i)
  375. selections_[j] -= removed;
  376. }
  377. UpdateSelectionEffect();
  378. }
  379. contentElement_->RemoveChildAtIndex(i);
  380. break;
  381. }
  382. }
  383. }
  384. void ListView::RemoveItem(unsigned index)
  385. {
  386. RemoveItem(GetItem(index), index);
  387. }
  388. void ListView::RemoveAllItems()
  389. {
  390. contentElement_->DisableLayoutUpdate();
  391. ClearSelection();
  392. contentElement_->RemoveAllChildren();
  393. if (hierarchyMode_)
  394. overlayContainer_->RemoveAllChildren();
  395. contentElement_->EnableLayoutUpdate();
  396. contentElement_->UpdateLayout();
  397. }
  398. void ListView::SetSelection(unsigned index)
  399. {
  400. PODVector<unsigned> indices;
  401. indices.Push(index);
  402. SetSelections(indices);
  403. EnsureItemVisibility(index);
  404. }
  405. void ListView::SetSelections(const PODVector<unsigned>& indices)
  406. {
  407. // Make a weak pointer to self to check for destruction as a response to events
  408. WeakPtr<ListView> self(this);
  409. unsigned numItems = GetNumItems();
  410. // Remove first items that should no longer be selected
  411. for (PODVector<unsigned>::Iterator i = selections_.Begin(); i != selections_.End();)
  412. {
  413. unsigned index = *i;
  414. if (!indices.Contains(index))
  415. {
  416. i = selections_.Erase(i);
  417. using namespace ItemSelected;
  418. VariantMap eventData;
  419. eventData[P_ELEMENT] = (void*)this;
  420. eventData[P_SELECTION] = index;
  421. SendEvent(E_ITEMDESELECTED, eventData);
  422. if (self.Expired())
  423. return;
  424. }
  425. else
  426. ++i;
  427. }
  428. bool added = false;
  429. // Then add missing items
  430. for (PODVector<unsigned>::ConstIterator i = indices.Begin(); i != indices.End(); ++i)
  431. {
  432. unsigned index = *i;
  433. if (index < numItems)
  434. {
  435. // In singleselect mode, resend the event even for the same selection
  436. bool duplicate = selections_.Contains(index);
  437. if (!duplicate || !multiselect_)
  438. {
  439. if (!duplicate)
  440. {
  441. selections_.Push(index);
  442. added = true;
  443. }
  444. using namespace ItemSelected;
  445. VariantMap eventData;
  446. eventData[P_ELEMENT] = (void*)this;
  447. eventData[P_SELECTION] = *i;
  448. SendEvent(E_ITEMSELECTED, eventData);
  449. if (self.Expired())
  450. return;
  451. }
  452. }
  453. // If no multiselect enabled, allow setting only one item
  454. if (!multiselect_)
  455. break;
  456. }
  457. // Re-sort selections if necessary
  458. if (added)
  459. Sort(selections_.Begin(), selections_.End());
  460. UpdateSelectionEffect();
  461. SendEvent(E_SELECTIONCHANGED);
  462. }
  463. void ListView::AddSelection(unsigned index)
  464. {
  465. // Make a weak pointer to self to check for destruction as a response to events
  466. WeakPtr<ListView> self(this);
  467. if (!multiselect_)
  468. SetSelection(index);
  469. else
  470. {
  471. if (index >= GetNumItems())
  472. return;
  473. if (!selections_.Contains(index))
  474. {
  475. selections_.Push(index);
  476. using namespace ItemSelected;
  477. VariantMap eventData;
  478. eventData[P_ELEMENT] = (void*)this;
  479. eventData[P_SELECTION] = index;
  480. SendEvent(E_ITEMSELECTED, eventData);
  481. if (self.Expired())
  482. return;
  483. Sort(selections_.Begin(), selections_.End());
  484. }
  485. EnsureItemVisibility(index);
  486. UpdateSelectionEffect();
  487. SendEvent(E_SELECTIONCHANGED);
  488. }
  489. }
  490. void ListView::RemoveSelection(unsigned index)
  491. {
  492. if (index >= GetNumItems())
  493. return;
  494. if (selections_.Remove(index))
  495. {
  496. using namespace ItemSelected;
  497. VariantMap eventData;
  498. eventData[P_ELEMENT] = (void*)this;
  499. eventData[P_SELECTION] = index;
  500. SendEvent(E_ITEMDESELECTED, eventData);
  501. }
  502. EnsureItemVisibility(index);
  503. UpdateSelectionEffect();
  504. SendEvent(E_SELECTIONCHANGED);
  505. }
  506. void ListView::ToggleSelection(unsigned index)
  507. {
  508. unsigned numItems = GetNumItems();
  509. if (index >= numItems)
  510. return;
  511. if (selections_.Contains(index))
  512. RemoveSelection(index);
  513. else
  514. AddSelection(index);
  515. }
  516. void ListView::ChangeSelection(int delta, bool additive)
  517. {
  518. if (selections_.Empty())
  519. return;
  520. if (!multiselect_)
  521. additive = false;
  522. // If going downwards, use the last selection as a base. Otherwise use first
  523. unsigned selection = delta > 0 ? selections_.Back() : selections_.Front();
  524. int direction = delta > 0 ? 1 : -1;
  525. unsigned numItems = GetNumItems();
  526. unsigned newSelection = selection;
  527. unsigned okSelection = selection;
  528. PODVector<unsigned> indices = selections_;
  529. while (delta != 0)
  530. {
  531. newSelection += direction;
  532. if (newSelection >= numItems)
  533. break;
  534. UIElement* item = GetItem(newSelection);
  535. if (item->IsVisible())
  536. {
  537. indices.Push(okSelection = newSelection);
  538. delta -= direction;
  539. }
  540. }
  541. if (!additive)
  542. SetSelection(okSelection);
  543. else
  544. SetSelections(indices);
  545. }
  546. void ListView::ClearSelection()
  547. {
  548. SetSelections(PODVector<unsigned>());
  549. }
  550. void ListView::SetHighlightMode(HighlightMode mode)
  551. {
  552. highlightMode_ = mode;
  553. UpdateSelectionEffect();
  554. }
  555. void ListView::SetMultiselect(bool enable)
  556. {
  557. multiselect_ = enable;
  558. }
  559. void ListView::SetHierarchyMode(bool enable)
  560. {
  561. if (enable == hierarchyMode_)
  562. return;
  563. hierarchyMode_ = enable;
  564. UIElement* container;
  565. if (enable)
  566. {
  567. overlayContainer_ = new UIElement(context_);
  568. overlayContainer_->SetName("LV_OverlayContainer");
  569. overlayContainer_->SetInternal(true);
  570. AddChild(overlayContainer_);
  571. overlayContainer_->SetSortChildren(false);
  572. overlayContainer_->SetClipChildren(true);
  573. container = new HierarchyContainer(context_, this, overlayContainer_);
  574. }
  575. else
  576. {
  577. if (overlayContainer_)
  578. {
  579. RemoveChild(overlayContainer_);
  580. overlayContainer_.Reset();
  581. }
  582. container = new UIElement(context_);
  583. }
  584. container->SetName("LV_ItemContainer");
  585. container->SetInternal(true);
  586. SetContentElement(container);
  587. container->SetEnabled(true);
  588. container->SetLayout(LM_VERTICAL);
  589. container->SetSortChildren(false);
  590. }
  591. void ListView::SetBaseIndent(int baseIndent)
  592. {
  593. baseIndent_ = baseIndent;
  594. UpdateLayout();
  595. }
  596. void ListView::SetClearSelectionOnDefocus(bool enable)
  597. {
  598. if (enable != clearSelectionOnDefocus_)
  599. {
  600. clearSelectionOnDefocus_ = enable;
  601. if (clearSelectionOnDefocus_)
  602. {
  603. SubscribeToEvent(this, E_DEFOCUSED, HANDLER(ListView, HandleDefocused));
  604. if (!HasFocus())
  605. ClearSelection();
  606. }
  607. else
  608. UnsubscribeFromEvent(this, E_DEFOCUSED);
  609. }
  610. }
  611. void ListView::Expand(unsigned index, bool enable, bool recursive)
  612. {
  613. if (!hierarchyMode_)
  614. return;
  615. unsigned numItems = GetNumItems();
  616. if (index >= numItems)
  617. return;
  618. UIElement* item = GetItem(index++);
  619. SetItemExpanded(item, enable);
  620. int baseIndent = item->GetIndent();
  621. PODVector<bool> expanded(baseIndent + 1);
  622. expanded[baseIndent] = enable;
  623. contentElement_->DisableLayoutUpdate();
  624. while (index < numItems)
  625. {
  626. item = GetItem(index++);
  627. int indent = item->GetIndent();
  628. if (indent <= baseIndent)
  629. break;
  630. // Propagate the state to children when it is recursive
  631. if (recursive)
  632. SetItemExpanded(item, enable);
  633. // Use the parent expanded flag to influence the visibility of its children
  634. bool visible = enable && expanded[indent - 1];
  635. item->SetVisible(visible);
  636. if (indent >= (int)expanded.Size())
  637. expanded.Resize(indent + 1);
  638. expanded[indent] = visible && GetItemExpanded(item);
  639. }
  640. contentElement_->EnableLayoutUpdate();
  641. contentElement_->UpdateLayout();
  642. }
  643. void ListView::ToggleExpand(unsigned index, bool recursive)
  644. {
  645. if (!hierarchyMode_)
  646. return;
  647. unsigned numItems = GetNumItems();
  648. if (index >= numItems)
  649. return;
  650. UIElement* item = GetItem(index);
  651. Expand(index, !GetItemExpanded(item), recursive);
  652. }
  653. unsigned ListView::GetNumItems() const
  654. {
  655. return contentElement_->GetNumChildren();
  656. }
  657. UIElement* ListView::GetItem(unsigned index) const
  658. {
  659. return contentElement_->GetChild(index);
  660. }
  661. PODVector<UIElement*> ListView::GetItems() const
  662. {
  663. PODVector<UIElement*> items;
  664. contentElement_->GetChildren(items);
  665. return items;
  666. }
  667. unsigned ListView::FindItem(UIElement* item) const
  668. {
  669. if (!item)
  670. return M_MAX_UNSIGNED;
  671. // Early-out by checking if the item belongs to the listview hierarchy at all
  672. if (item->GetParent() != contentElement_)
  673. return M_MAX_UNSIGNED;
  674. const Vector<SharedPtr<UIElement> >& children = contentElement_->GetChildren();
  675. // Binary search for list item based on screen coordinate Y
  676. if (item->GetHeight())
  677. {
  678. int itemY = item->GetScreenPosition().y_;
  679. int left = 0;
  680. int right = children.Size() - 1;
  681. while (right >= left)
  682. {
  683. int mid = (left + right) / 2;
  684. if (children[mid] == item)
  685. return mid;
  686. if (itemY < children[mid]->GetScreenPosition().y_)
  687. right = mid - 1;
  688. else
  689. left = mid + 1;
  690. }
  691. }
  692. // Fallback to linear search in case the coordinates/sizes were not yet initialized
  693. for (unsigned i = 0; i < children.Size(); ++i)
  694. {
  695. if (children[i] == item)
  696. return i;
  697. }
  698. return M_MAX_UNSIGNED;
  699. }
  700. unsigned ListView::GetSelection() const
  701. {
  702. if (selections_.Empty())
  703. return M_MAX_UNSIGNED;
  704. else
  705. return GetSelections().Front();
  706. }
  707. UIElement* ListView::GetSelectedItem() const
  708. {
  709. return contentElement_->GetChild(GetSelection());
  710. }
  711. PODVector<UIElement*> ListView::GetSelectedItems() const
  712. {
  713. PODVector<UIElement*> ret;
  714. for (PODVector<unsigned>::ConstIterator i = selections_.Begin(); i != selections_.End(); ++i)
  715. {
  716. UIElement* item = GetItem(*i);
  717. if (item)
  718. ret.Push(item);
  719. }
  720. return ret;
  721. }
  722. bool ListView::IsSelected(unsigned index) const
  723. {
  724. return selections_.Contains(index);
  725. }
  726. bool ListView::IsExpanded(unsigned index) const
  727. {
  728. return GetItemExpanded(contentElement_->GetChild(index));
  729. }
  730. bool ListView::FilterImplicitAttributes(XMLElement& dest) const
  731. {
  732. if (!ScrollView::FilterImplicitAttributes(dest))
  733. return false;
  734. XMLElement childElem = dest.GetChild("element"); // Horizontal scroll bar
  735. if (!childElem)
  736. return false;
  737. childElem = childElem.GetNext("element"); // Vertical scroll bar
  738. if (!childElem)
  739. return false;
  740. childElem = childElem.GetNext("element"); // Scroll panel
  741. if (!childElem)
  742. return false;
  743. XMLElement containerElem = childElem.GetChild("element"); // Item container
  744. if (!containerElem)
  745. return false;
  746. if (!RemoveChildXML(containerElem, "Name", "LV_ItemContainer"))
  747. return false;
  748. if (!RemoveChildXML(containerElem, "Is Enabled", "true"))
  749. return false;
  750. if (!RemoveChildXML(containerElem, "Layout Mode", "Vertical"))
  751. return false;
  752. if (!RemoveChildXML(containerElem, "Size"))
  753. return false;
  754. if (hierarchyMode_)
  755. {
  756. containerElem = childElem.GetNext("element"); // Overlay container
  757. if (!containerElem)
  758. return false;
  759. if (!RemoveChildXML(containerElem, "Name", "LV_OverlayContainer"))
  760. return false;
  761. if (!RemoveChildXML(containerElem, "Clip Children", "true"))
  762. return false;
  763. if (!RemoveChildXML(containerElem, "Size"))
  764. return false;
  765. }
  766. return true;
  767. }
  768. void ListView::UpdateSelectionEffect()
  769. {
  770. unsigned numItems = GetNumItems();
  771. bool highlighted = highlightMode_ == HM_ALWAYS || HasFocus();
  772. for (unsigned i = 0; i < numItems; ++i)
  773. {
  774. UIElement* item = GetItem(i);
  775. if (highlightMode_ != HM_NEVER && selections_.Contains(i))
  776. item->SetSelected(highlighted);
  777. else
  778. item->SetSelected(false);
  779. }
  780. }
  781. void ListView::EnsureItemVisibility(unsigned index)
  782. {
  783. EnsureItemVisibility(GetItem(index));
  784. }
  785. void ListView::EnsureItemVisibility(UIElement* item)
  786. {
  787. if (!item || !item->IsVisible())
  788. return;
  789. IntVector2 newView = GetViewPosition();
  790. IntVector2 currentOffset = item->GetPosition() - newView;
  791. const IntRect& clipBorder = scrollPanel_->GetClipBorder();
  792. IntVector2 windowSize(scrollPanel_->GetWidth() - clipBorder.left_ - clipBorder.right_, scrollPanel_->GetHeight() -
  793. clipBorder.top_ - clipBorder.bottom_);
  794. if (currentOffset.y_ < 0)
  795. newView.y_ += currentOffset.y_;
  796. if (currentOffset.y_ + item->GetHeight() > windowSize.y_)
  797. newView.y_ += currentOffset.y_ + item->GetHeight() - windowSize.y_;
  798. SetViewPosition(newView);
  799. }
  800. void ListView::HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
  801. {
  802. int button = eventData[UIMouseClick::P_BUTTON].GetInt();
  803. int buttons = eventData[UIMouseClick::P_BUTTONS].GetInt();
  804. int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
  805. UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  806. // Check if the clicked element belongs to the list
  807. unsigned i = FindItem(element);
  808. if (i >= GetNumItems())
  809. return;
  810. // If not editable, repeat the previous selection. This will send an event and allow eg. a dropdownlist to close
  811. if (!editable_)
  812. {
  813. SetSelections(selections_);
  814. return;
  815. }
  816. if (button == MOUSEB_LEFT)
  817. {
  818. // Single selection
  819. if (!multiselect_ || !qualifiers)
  820. SetSelection(i);
  821. // Check multiselect with shift & ctrl
  822. if (multiselect_)
  823. {
  824. if (qualifiers & QUAL_SHIFT)
  825. {
  826. if (selections_.Empty())
  827. SetSelection(i);
  828. else
  829. {
  830. unsigned first = selections_.Front();
  831. unsigned last = selections_.Back();
  832. PODVector<unsigned> newSelections = selections_;
  833. if (i == first || i == last)
  834. {
  835. for (unsigned j = first; j <= last; ++j)
  836. newSelections.Push(j);
  837. }
  838. else if (i < first)
  839. {
  840. for (unsigned j = i; j <= first; ++j)
  841. newSelections.Push(j);
  842. }
  843. else if (i < last)
  844. {
  845. if ((abs((int)i - (int)first)) <= (abs((int)i - (int)last)))
  846. {
  847. for (unsigned j = first; j <= i; ++j)
  848. newSelections.Push(j);
  849. }
  850. else
  851. {
  852. for (unsigned j = i; j <= last; ++j)
  853. newSelections.Push(j);
  854. }
  855. }
  856. else if (i > last)
  857. {
  858. for (unsigned j = last; j <= i; ++j)
  859. newSelections.Push(j);
  860. }
  861. SetSelections(newSelections);
  862. }
  863. }
  864. else if (qualifiers & QUAL_CTRL)
  865. ToggleSelection(i);
  866. }
  867. }
  868. // Propagate the click as an event. Also include right-clicks
  869. VariantMap clickEventData;
  870. clickEventData[ItemClicked::P_ELEMENT] = (void*)this;
  871. clickEventData[ItemClicked::P_ITEM] = (void*)element;
  872. clickEventData[ItemClicked::P_SELECTION] = i;
  873. clickEventData[ItemClicked::P_BUTTON] = button;
  874. clickEventData[ItemClicked::P_BUTTONS] = buttons;
  875. clickEventData[ItemClicked::P_QUALIFIERS] = qualifiers;
  876. SendEvent(E_ITEMCLICKED, clickEventData);
  877. }
  878. void ListView::HandleUIMouseDoubleClick(StringHash eventType, VariantMap& eventData)
  879. {
  880. int button = eventData[UIMouseClick::P_BUTTON].GetInt();
  881. int buttons = eventData[UIMouseClick::P_BUTTONS].GetInt();
  882. int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
  883. UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  884. // Check if the clicked element belongs to the list
  885. unsigned i = FindItem(element);
  886. if (i >= GetNumItems())
  887. return;
  888. VariantMap clickEventData;
  889. clickEventData[ItemDoubleClicked::P_ELEMENT] = (void*)this;
  890. clickEventData[ItemDoubleClicked::P_ITEM] = (void*)element;
  891. clickEventData[ItemDoubleClicked::P_SELECTION] = i;
  892. clickEventData[ItemDoubleClicked::P_BUTTON] = button;
  893. clickEventData[ItemDoubleClicked::P_BUTTONS] = buttons;
  894. clickEventData[ItemDoubleClicked::P_QUALIFIERS] = qualifiers;
  895. SendEvent(E_ITEMDOUBLECLICKED, clickEventData);
  896. }
  897. void ListView::HandleFocusChanged(StringHash eventType, VariantMap& eventData)
  898. {
  899. using namespace FocusChanged;
  900. UIElement* element = static_cast<UIElement*>(eventData[P_ELEMENT].GetPtr());
  901. while (element)
  902. {
  903. // If the focused element or its parent is in the list, scroll the list to make the item visible
  904. UIElement* parent = element->GetParent();
  905. if (parent == contentElement_)
  906. {
  907. EnsureItemVisibility(element);
  908. return;
  909. }
  910. element = parent;
  911. }
  912. }
  913. void ListView::HandleDefocused(StringHash eventType, VariantMap& eventData)
  914. {
  915. ClearSelection();
  916. }
  917. }