ListView.cpp 31 KB

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