ListView.cpp 33 KB

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