ListView.cpp 34 KB

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