ListView.cpp 35 KB

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