ListView.cpp 35 KB

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