2
0

ListView.cpp 35 KB

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