ListView.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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. ""
  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, UIElement* overlayContainer) :
  71. UIElement(context),
  72. overlayContainer_(overlayContainer)
  73. {
  74. SubscribeToEvent(this, E_LAYOUTUPDATED, HANDLER(HierarchyContainer, HandleLayoutUpdated));
  75. SubscribeToEvent(overlayContainer->GetParent(), E_VIEWCHANGED, HANDLER(HierarchyContainer, HandleViewChanged));
  76. SubscribeToEvent(E_UIMOUSECLICK, HANDLER(HierarchyContainer, HandleUIMouseClick));
  77. }
  78. /// Handle layout updated by adjusting the position of the overlays.
  79. void HandleLayoutUpdated(StringHash eventType, VariantMap& eventData)
  80. {
  81. // Adjust the container size for child clipping effect
  82. overlayContainer_->SetSize(GetParent()->GetSize());
  83. for (unsigned i = 0; i < children_.Size(); ++i)
  84. {
  85. const IntVector2& position = children_[i]->GetPosition();
  86. CheckBox* overlay = static_cast<CheckBox*>(overlayContainer_->GetChild(i));
  87. bool visible = children_[i]->IsVisible() && GetItemHierarchyParent(children_[i]);
  88. overlay->SetVisible(visible);
  89. if (visible)
  90. {
  91. overlay->SetPosition(position.x_, position.y_);
  92. overlay->SetChecked(GetItemExpanded(children_[i]));
  93. }
  94. }
  95. }
  96. /// Handle view changed by scrolling the overlays in tandem.
  97. void HandleViewChanged(StringHash eventType, VariantMap& eventData)
  98. {
  99. using namespace ViewChanged;
  100. int x = eventData[P_X].GetInt();
  101. int y = eventData[P_Y].GetInt();
  102. IntRect panelBorder = GetParent()->GetClipBorder();
  103. overlayContainer_->SetChildOffset(IntVector2(-x + panelBorder.left_, -y + panelBorder.top_));
  104. }
  105. /// Handle mouse click on overlays by toggling the expansion state of the corresponding item
  106. void HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
  107. {
  108. using namespace UIMouseClick;
  109. UIElement* overlay = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  110. if (overlay)
  111. {
  112. const Vector<SharedPtr<UIElement> >& children = overlayContainer_->GetChildren();
  113. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Find(SharedPtr<UIElement>(overlay));
  114. if (i != children.End())
  115. static_cast<ListView*>(overlayContainer_->GetParent())->ToggleExpand(i - children.Begin());
  116. }
  117. }
  118. /// Insert a child element into a specific position in the child list.
  119. void InsertChild(unsigned index, UIElement* element)
  120. {
  121. // Insert the overlay at the same index position to the overlay container
  122. CheckBox* overlay = new CheckBox(context_);
  123. overlay->SetStyle(overlayContainer_->GetDefaultStyle(), "ListViewHierarchyOverlay");
  124. int baseIndent = static_cast<ListView*>(overlayContainer_->GetParent())->GetBaseIndent();
  125. int indent = element->GetIndent() - baseIndent - 1;
  126. overlay->SetIndent(indent);
  127. overlay->SetFixedWidth((indent + 1) * element->GetIndentSpacing());
  128. overlayContainer_->InsertChild(index, overlay);
  129. // Then insert the element as child as per normal
  130. UIElement::InsertChild(index, element);
  131. }
  132. private:
  133. UIElement* overlayContainer_;
  134. };
  135. OBJECTTYPESTATIC(HierarchyContainer);
  136. OBJECTTYPESTATIC(ListView);
  137. ListView::ListView(Context* context) :
  138. ScrollView(context),
  139. highlightMode_(HM_FOCUS),
  140. multiselect_(false),
  141. hierarchyMode_(true), // Init to true here so that the setter below takes effect
  142. baseIndent_(0),
  143. clearSelectionOnDefocus_(false),
  144. doubleClickInterval_(500),
  145. lastClickedItem_(M_MAX_UNSIGNED)
  146. {
  147. resizeContentWidth_ = true;
  148. // By default list view is set to non-hierarchy mode
  149. SetHierarchyMode(false);
  150. SubscribeToEvent(E_UIMOUSECLICK, HANDLER(ListView, HandleUIMouseClick));
  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. ACCESSOR_ATTRIBUTE(ListView, VAR_FLOAT, "Double Click Interval", GetDoubleClickInterval, SetDoubleClickInterval, float, 0.5f, AM_FILE);
  167. }
  168. void ListView::OnKey(int key, int buttons, int qualifiers)
  169. {
  170. // If no selection, can not move with keys
  171. unsigned numItems = GetNumItems();
  172. unsigned selection = GetSelection();
  173. // If either shift or ctrl held down, add to selection if multiselect enabled
  174. bool additive = multiselect_ && qualifiers & (QUAL_SHIFT | QUAL_CTRL);
  175. int delta = 0;
  176. int pageDirection = 1;
  177. if (selection != M_MAX_UNSIGNED && numItems)
  178. {
  179. switch (key)
  180. {
  181. case KEY_LEFT:
  182. case KEY_RIGHT:
  183. if (hierarchyMode_)
  184. {
  185. Expand(selection, key == KEY_RIGHT);
  186. return;
  187. }
  188. break;
  189. case KEY_RETURN:
  190. case KEY_RETURN2:
  191. case KEY_KP_ENTER:
  192. if (hierarchyMode_)
  193. {
  194. ToggleExpand(selection);
  195. return;
  196. }
  197. break;
  198. case KEY_UP:
  199. delta = -1;
  200. break;
  201. case KEY_DOWN:
  202. delta = 1;
  203. break;
  204. case KEY_PAGEUP:
  205. pageDirection = -1;
  206. // Fallthru
  207. case KEY_PAGEDOWN:
  208. {
  209. // Convert page step to pixels and see how many items have to be skipped to reach that many pixels
  210. int stepPixels = ((int)(pageStep_ * scrollPanel_->GetHeight())) - GetSelectedItem()->GetHeight();
  211. unsigned newSelection = selection;
  212. unsigned okSelection = selection;
  213. unsigned invisible = 0;
  214. while (newSelection < numItems)
  215. {
  216. UIElement* item = GetItem(newSelection);
  217. int height = 0;
  218. if (item->IsVisible())
  219. {
  220. height = item->GetHeight();
  221. okSelection = newSelection;
  222. }
  223. else
  224. ++invisible;
  225. if (stepPixels < height)
  226. break;
  227. stepPixels -= height;
  228. newSelection += pageDirection;
  229. }
  230. delta = okSelection - selection - pageDirection * invisible;
  231. }
  232. break;
  233. case KEY_HOME:
  234. delta = -(int)GetNumItems();
  235. break;
  236. case KEY_END:
  237. delta = GetNumItems();
  238. break;
  239. }
  240. }
  241. if (delta)
  242. {
  243. ChangeSelection(delta, additive);
  244. return;
  245. }
  246. using namespace UnhandledKey;
  247. VariantMap eventData;
  248. eventData[P_ELEMENT] = (void*)this;
  249. eventData[P_KEY] = key;
  250. eventData[P_BUTTONS] = buttons;
  251. eventData[P_QUALIFIERS] = qualifiers;
  252. SendEvent(E_UNHANDLEDKEY, eventData);
  253. }
  254. void ListView::OnResize()
  255. {
  256. ScrollView::OnResize();
  257. // When in hierarchy mode also need to resize the overlay container
  258. if (hierarchyMode_)
  259. overlayContainer_->SetSize(scrollPanel_->GetSize());
  260. }
  261. void ListView::AddItem(UIElement* item)
  262. {
  263. InsertItem(M_MAX_UNSIGNED, item);
  264. }
  265. void ListView::InsertItem(unsigned index, UIElement* item, UIElement* parentItem)
  266. {
  267. if (!item || item->GetParent() == contentElement_)
  268. return;
  269. // Enable input so that clicking the item can be detected
  270. item->SetEnabled(true);
  271. item->SetSelected(false);
  272. unsigned numItems = contentElement_->GetNumChildren();
  273. if (hierarchyMode_)
  274. {
  275. int baseIndent = baseIndent_;
  276. if (parentItem)
  277. {
  278. baseIndent = parentItem->GetIndent();
  279. SetItemHierarchyParent(parentItem, true);
  280. // Adjust the index to ensure it is within the children index limit of the parent item
  281. unsigned indexLimit = FindItem(parentItem);
  282. if (index <= indexLimit)
  283. index = indexLimit + 1;
  284. else
  285. {
  286. while (++indexLimit < numItems)
  287. {
  288. if (contentElement_->GetChild(indexLimit)->GetIndent() <= baseIndent)
  289. break;
  290. }
  291. if (index > indexLimit)
  292. index = indexLimit;
  293. }
  294. }
  295. item->SetIndent(baseIndent + 1);
  296. SetItemExpanded(item, item->IsVisible());
  297. // Use the 'overrided' version to insert the child item
  298. static_cast<HierarchyContainer*>(contentElement_.Get())->InsertChild(index, item);
  299. }
  300. else
  301. {
  302. if (index > numItems)
  303. index = numItems;
  304. contentElement_->InsertChild(index, item);
  305. }
  306. // If necessary, shift the following selections
  307. if (!selections_.Empty())
  308. {
  309. for (unsigned i = 0; i < selections_.Size(); ++i)
  310. {
  311. if (selections_[i] >= index)
  312. ++selections_[i];
  313. }
  314. UpdateSelectionEffect();
  315. }
  316. }
  317. void ListView::RemoveItem(UIElement* item, unsigned index)
  318. {
  319. if (!item)
  320. return;
  321. unsigned numItems = GetNumItems();
  322. for (unsigned i = index; i < numItems; ++i)
  323. {
  324. if (GetItem(i) == item)
  325. {
  326. item->SetSelected(false);
  327. selections_.Remove(i);
  328. unsigned removed = 1;
  329. if (hierarchyMode_)
  330. {
  331. // Remove any child items in hierarchy mode
  332. if (GetItemHierarchyParent(item))
  333. {
  334. int baseIndent = item->GetIndent();
  335. for (unsigned j = i + 1; ; ++j)
  336. {
  337. UIElement* childItem = GetItem(i + 1);
  338. if (!childItem)
  339. break;
  340. if (childItem->GetIndent() > baseIndent)
  341. {
  342. childItem->SetSelected(false);
  343. selections_.Erase(j);
  344. contentElement_->RemoveChildAtIndex(i + 1);
  345. overlayContainer_->RemoveChildAtIndex(i + 1);
  346. ++removed;
  347. }
  348. else
  349. break;
  350. }
  351. }
  352. // Check if the parent of removed item still has other children
  353. if (i > 0)
  354. {
  355. int baseIndent = item->GetIndent();
  356. UIElement* prevKin = GetItem(i - 1); // Could be parent or sibling
  357. if (prevKin->GetIndent() < baseIndent)
  358. {
  359. UIElement* nextKin = GetItem(i + 1); // Could be sibling or parent-sibling or 0 if index out of bound
  360. if (!nextKin || nextKin->GetIndent() < baseIndent)
  361. {
  362. // If we reach here then the parent has no other children
  363. SetItemHierarchyParent(prevKin, false);
  364. }
  365. }
  366. }
  367. // Remove the overlay at the same index
  368. overlayContainer_->RemoveChildAtIndex(i);
  369. }
  370. // If necessary, shift the following selections
  371. if (!selections_.Empty())
  372. {
  373. for (unsigned j = 0; j < selections_.Size(); ++j)
  374. {
  375. if (selections_[j] > i)
  376. selections_[j] -= removed;
  377. }
  378. UpdateSelectionEffect();
  379. }
  380. contentElement_->RemoveChildAtIndex(i);
  381. break;
  382. }
  383. }
  384. }
  385. void ListView::RemoveItem(unsigned index)
  386. {
  387. RemoveItem(GetItem(index), index);
  388. }
  389. void ListView::RemoveAllItems()
  390. {
  391. contentElement_->DisableLayoutUpdate();
  392. ClearSelection();
  393. contentElement_->RemoveAllChildren();
  394. if (hierarchyMode_)
  395. overlayContainer_->RemoveAllChildren();
  396. contentElement_->EnableLayoutUpdate();
  397. contentElement_->UpdateLayout();
  398. }
  399. void ListView::SetSelection(unsigned index)
  400. {
  401. PODVector<unsigned> indices;
  402. indices.Push(index);
  403. SetSelections(indices);
  404. EnsureItemVisibility(index);
  405. }
  406. void ListView::SetSelections(const PODVector<unsigned>& indices)
  407. {
  408. // Make a weak pointer to self to check for destruction as a response to events
  409. WeakPtr<ListView> self(this);
  410. unsigned numItems = GetNumItems();
  411. // Remove first items that should no longer be selected
  412. for (PODVector<unsigned>::Iterator i = selections_.Begin(); i != selections_.End();)
  413. {
  414. unsigned index = *i;
  415. if (!indices.Contains(index))
  416. {
  417. i = selections_.Erase(i);
  418. using namespace ItemSelected;
  419. VariantMap eventData;
  420. eventData[P_ELEMENT] = (void*)this;
  421. eventData[P_SELECTION] = index;
  422. SendEvent(E_ITEMDESELECTED, eventData);
  423. if (self.Expired())
  424. return;
  425. }
  426. else
  427. ++i;
  428. }
  429. bool added = false;
  430. // Then add missing items
  431. for (PODVector<unsigned>::ConstIterator i = indices.Begin(); i != indices.End(); ++i)
  432. {
  433. unsigned index = *i;
  434. if (index < numItems)
  435. {
  436. // In singleselect mode, resend the event even for the same selection
  437. bool duplicate = selections_.Contains(index);
  438. if (!duplicate || !multiselect_)
  439. {
  440. if (!duplicate)
  441. {
  442. selections_.Push(index);
  443. added = true;
  444. }
  445. using namespace ItemSelected;
  446. VariantMap eventData;
  447. eventData[P_ELEMENT] = (void*)this;
  448. eventData[P_SELECTION] = *i;
  449. SendEvent(E_ITEMSELECTED, eventData);
  450. if (self.Expired())
  451. return;
  452. }
  453. }
  454. // If no multiselect enabled, allow setting only one item
  455. if (!multiselect_)
  456. break;
  457. }
  458. // Re-sort selections if necessary
  459. if (added)
  460. Sort(selections_.Begin(), selections_.End());
  461. UpdateSelectionEffect();
  462. SendEvent(E_SELECTIONCHANGED);
  463. }
  464. void ListView::AddSelection(unsigned index)
  465. {
  466. // Make a weak pointer to self to check for destruction as a response to events
  467. WeakPtr<ListView> self(this);
  468. if (!multiselect_)
  469. SetSelection(index);
  470. else
  471. {
  472. if (index >= GetNumItems())
  473. return;
  474. if (!selections_.Contains(index))
  475. {
  476. selections_.Push(index);
  477. using namespace ItemSelected;
  478. VariantMap eventData;
  479. eventData[P_ELEMENT] = (void*)this;
  480. eventData[P_SELECTION] = index;
  481. SendEvent(E_ITEMSELECTED, eventData);
  482. if (self.Expired())
  483. return;
  484. Sort(selections_.Begin(), selections_.End());
  485. }
  486. EnsureItemVisibility(index);
  487. UpdateSelectionEffect();
  488. SendEvent(E_SELECTIONCHANGED);
  489. }
  490. }
  491. void ListView::RemoveSelection(unsigned index)
  492. {
  493. if (index >= GetNumItems())
  494. return;
  495. if (selections_.Remove(index))
  496. {
  497. using namespace ItemSelected;
  498. VariantMap eventData;
  499. eventData[P_ELEMENT] = (void*)this;
  500. eventData[P_SELECTION] = index;
  501. SendEvent(E_ITEMDESELECTED, eventData);
  502. }
  503. EnsureItemVisibility(index);
  504. UpdateSelectionEffect();
  505. SendEvent(E_SELECTIONCHANGED);
  506. }
  507. void ListView::ToggleSelection(unsigned index)
  508. {
  509. unsigned numItems = GetNumItems();
  510. if (index >= numItems)
  511. return;
  512. if (selections_.Contains(index))
  513. RemoveSelection(index);
  514. else
  515. AddSelection(index);
  516. }
  517. void ListView::ChangeSelection(int delta, bool additive)
  518. {
  519. if (selections_.Empty())
  520. return;
  521. if (!multiselect_)
  522. additive = false;
  523. // If going downwards, use the last selection as a base. Otherwise use first
  524. unsigned selection = delta > 0 ? selections_.Back() : selections_.Front();
  525. int direction = delta > 0 ? 1 : -1;
  526. unsigned numItems = GetNumItems();
  527. unsigned newSelection = selection;
  528. unsigned okSelection = selection;
  529. PODVector<unsigned> indices = selections_;
  530. while (delta != 0)
  531. {
  532. newSelection += direction;
  533. if (newSelection >= numItems)
  534. break;
  535. UIElement* item = GetItem(newSelection);
  536. if (item->IsVisible())
  537. {
  538. indices.Push(okSelection = newSelection);
  539. delta -= direction;
  540. }
  541. }
  542. if (!additive)
  543. SetSelection(okSelection);
  544. else
  545. SetSelections(indices);
  546. }
  547. void ListView::ClearSelection()
  548. {
  549. SetSelections(PODVector<unsigned>());
  550. }
  551. void ListView::SetHighlightMode(HighlightMode mode)
  552. {
  553. highlightMode_ = mode;
  554. UpdateSelectionEffect();
  555. }
  556. void ListView::SetMultiselect(bool enable)
  557. {
  558. multiselect_ = enable;
  559. }
  560. void ListView::SetHierarchyMode(bool enable)
  561. {
  562. if (enable == hierarchyMode_)
  563. return;
  564. hierarchyMode_ = enable;
  565. UIElement* container;
  566. if (enable)
  567. {
  568. overlayContainer_ = CreateChild<UIElement>("LV_OverlayContainer");
  569. overlayContainer_->SetInternal(true);
  570. overlayContainer_->SetSortChildren(false);
  571. overlayContainer_->SetClipChildren(true);
  572. container = new HierarchyContainer(context_, overlayContainer_);
  573. }
  574. else
  575. {
  576. if (overlayContainer_)
  577. {
  578. RemoveChild(overlayContainer_);
  579. overlayContainer_.Reset();
  580. }
  581. container = new UIElement(context_);
  582. }
  583. SetContentElement(container);
  584. container->SetInternal(true);
  585. container->SetName("LV_ItemContainer");
  586. container->SetEnabled(true);
  587. container->SetLayout(LM_VERTICAL);
  588. container->SetSortChildren(false);
  589. }
  590. void ListView::SetBaseIndent(int baseIndent)
  591. {
  592. baseIndent_ = baseIndent;
  593. UpdateLayout();
  594. }
  595. void ListView::SetClearSelectionOnDefocus(bool enable)
  596. {
  597. if (enable != clearSelectionOnDefocus_)
  598. {
  599. clearSelectionOnDefocus_ = enable;
  600. if (clearSelectionOnDefocus_)
  601. {
  602. SubscribeToEvent(this, E_DEFOCUSED, HANDLER(ListView, HandleDefocused));
  603. if (!HasFocus())
  604. ClearSelection();
  605. }
  606. else
  607. UnsubscribeFromEvent(this, E_DEFOCUSED);
  608. }
  609. }
  610. void ListView::SetDoubleClickInterval(float interval)
  611. {
  612. doubleClickInterval_ = Max((int)(interval * 1000.0f), 0);
  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. const Vector<SharedPtr<UIElement> >& children = contentElement_->GetChildren();
  673. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Find(SharedPtr<UIElement>(item));
  674. if (i != children.End())
  675. return i - children.Begin();
  676. else
  677. return M_MAX_UNSIGNED;
  678. }
  679. unsigned ListView::GetSelection() const
  680. {
  681. if (selections_.Empty())
  682. return M_MAX_UNSIGNED;
  683. else
  684. return GetSelections().Front();
  685. }
  686. UIElement* ListView::GetSelectedItem() const
  687. {
  688. return contentElement_->GetChild(GetSelection());
  689. }
  690. PODVector<UIElement*> ListView::GetSelectedItems() const
  691. {
  692. PODVector<UIElement*> ret;
  693. for (PODVector<unsigned>::ConstIterator i = selections_.Begin(); i != selections_.End(); ++i)
  694. {
  695. UIElement* item = GetItem(*i);
  696. if (item)
  697. ret.Push(item);
  698. }
  699. return ret;
  700. }
  701. bool ListView::IsSelected(unsigned index) const
  702. {
  703. return selections_.Contains(index);
  704. }
  705. bool ListView::IsExpanded(unsigned index) const
  706. {
  707. return GetItemExpanded(contentElement_->GetChild(index));
  708. }
  709. float ListView::GetDoubleClickInterval() const
  710. {
  711. return (float)doubleClickInterval_ / 1000.0f;
  712. }
  713. bool ListView::FilterImplicitAttributes(XMLElement& dest) const
  714. {
  715. if (!ScrollView::FilterImplicitAttributes(dest))
  716. return false;
  717. XMLElement childElem = dest.GetChild("element"); // Horizontal scroll bar
  718. if (!childElem)
  719. return false;
  720. childElem = childElem.GetNext("element"); // Vertical scroll bar
  721. if (!childElem)
  722. return false;
  723. childElem = childElem.GetNext("element"); // Scroll panel
  724. if (!childElem)
  725. return false;
  726. XMLElement containerElem = childElem.GetChild("element"); // Item container
  727. if (!containerElem)
  728. return false;
  729. if (!RemoveChildXML(containerElem, "Name", "LV_ItemContainer"))
  730. return false;
  731. if (!RemoveChildXML(containerElem, "Is Enabled", "true"))
  732. return false;
  733. if (!RemoveChildXML(containerElem, "Layout Mode", "Vertical"))
  734. return false;
  735. if (!RemoveChildXML(containerElem, "Size"))
  736. return false;
  737. if (hierarchyMode_)
  738. {
  739. containerElem = childElem.GetNext("element"); // Overlay container
  740. if (!containerElem)
  741. return false;
  742. if (!RemoveChildXML(containerElem, "Name", "LV_OverlayContainer"))
  743. return false;
  744. if (!RemoveChildXML(containerElem, "Clip Children", "true"))
  745. return false;
  746. if (!RemoveChildXML(containerElem, "Size"))
  747. return false;
  748. }
  749. return true;
  750. }
  751. void ListView::UpdateSelectionEffect()
  752. {
  753. unsigned numItems = GetNumItems();
  754. bool highlighted = highlightMode_ == HM_ALWAYS || HasFocus();
  755. for (unsigned i = 0; i < numItems; ++i)
  756. {
  757. UIElement* item = GetItem(i);
  758. if (highlightMode_ != HM_NEVER && selections_.Contains(i))
  759. item->SetSelected(highlighted);
  760. else
  761. item->SetSelected(false);
  762. }
  763. }
  764. void ListView::EnsureItemVisibility(unsigned index)
  765. {
  766. EnsureItemVisibility(GetItem(index));
  767. }
  768. void ListView::EnsureItemVisibility(UIElement* item)
  769. {
  770. if (!item || !item->IsVisible())
  771. return;
  772. IntVector2 newView = GetViewPosition();
  773. IntVector2 currentOffset = item->GetPosition() - newView;
  774. const IntRect& clipBorder = scrollPanel_->GetClipBorder();
  775. IntVector2 windowSize(scrollPanel_->GetWidth() - clipBorder.left_ - clipBorder.right_, scrollPanel_->GetHeight() -
  776. clipBorder.top_ - clipBorder.bottom_);
  777. if (currentOffset.y_ < 0)
  778. newView.y_ += currentOffset.y_;
  779. if (currentOffset.y_ + item->GetHeight() > windowSize.y_)
  780. newView.y_ += currentOffset.y_ + item->GetHeight() - windowSize.y_;
  781. SetViewPosition(newView);
  782. }
  783. void ListView::HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
  784. {
  785. if (eventData[UIMouseClick::P_BUTTON].GetInt() != MOUSEB_LEFT)
  786. return;
  787. int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
  788. UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  789. unsigned numItems = GetNumItems();
  790. for (unsigned i = 0; i < numItems; ++i)
  791. {
  792. if (element == GetItem(i))
  793. {
  794. // Check doubleclick
  795. bool isDoubleClick = false;
  796. if (!multiselect_ || !qualifiers)
  797. {
  798. if (!(isDoubleClick = doubleClickTimer_.GetMSec(true) < doubleClickInterval_ && lastClickedItem_ == i))
  799. lastClickedItem_ = i;
  800. SetSelection(i);
  801. }
  802. // Check multiselect with shift & ctrl
  803. if (multiselect_)
  804. {
  805. if (qualifiers & QUAL_SHIFT)
  806. {
  807. if (selections_.Empty())
  808. SetSelection(i);
  809. else
  810. {
  811. unsigned first = selections_.Front();
  812. unsigned last = selections_.Back();
  813. PODVector<unsigned> newSelections = selections_;
  814. if (i == first || i == last)
  815. {
  816. for (unsigned j = first; j <= last; ++j)
  817. newSelections.Push(j);
  818. }
  819. else if (i < first)
  820. {
  821. for (unsigned j = i; j <= first; ++j)
  822. newSelections.Push(j);
  823. }
  824. else if (i < last)
  825. {
  826. if ((abs((int)i - (int)first)) <= (abs((int)i - (int)last)))
  827. {
  828. for (unsigned j = first; j <= i; ++j)
  829. newSelections.Push(j);
  830. }
  831. else
  832. {
  833. for (unsigned j = i; j <= last; ++j)
  834. newSelections.Push(j);
  835. }
  836. }
  837. else if (i > last)
  838. {
  839. for (unsigned j = last; j <= i; ++j)
  840. newSelections.Push(j);
  841. }
  842. SetSelections(newSelections);
  843. }
  844. }
  845. else if (qualifiers & QUAL_CTRL)
  846. ToggleSelection(i);
  847. }
  848. if (isDoubleClick)
  849. {
  850. VariantMap eventData;
  851. eventData[ItemDoubleClicked::P_ELEMENT] = (void*)this;
  852. eventData[ItemDoubleClicked::P_SELECTION] = i;
  853. SendEvent(E_ITEMDOUBLECLICKED, eventData);
  854. }
  855. return;
  856. }
  857. }
  858. }
  859. void ListView::HandleFocusChanged(StringHash eventType, VariantMap& eventData)
  860. {
  861. using namespace FocusChanged;
  862. UIElement* element = static_cast<UIElement*>(eventData[P_ELEMENT].GetPtr());
  863. while (element)
  864. {
  865. // If the focused element or its parent is in the list, scroll the list to make the item visible
  866. UIElement* parent = element->GetParent();
  867. if (parent == contentElement_)
  868. {
  869. EnsureItemVisibility(element);
  870. return;
  871. }
  872. element = parent;
  873. }
  874. }
  875. void ListView::HandleDefocused(StringHash eventType, VariantMap& eventData)
  876. {
  877. ClearSelection();
  878. }
  879. }