ListView.cpp 35 KB

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