ListView.cpp 36 KB

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