ListView.cpp 35 KB

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