ListView.cpp 35 KB

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