ListView.cpp 35 KB

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