ListView.cpp 34 KB

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