ListView.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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. bool GetItemExpanded(UIElement* item)
  47. {
  48. return item ? item->GetVar(expandedHash).GetBool() : false;
  49. }
  50. void SetItemExpanded(UIElement* item, bool enable)
  51. {
  52. item->SetVar(expandedHash, enable);
  53. }
  54. static const ShortStringHash hierarchyParentHash("HierarchyParent");
  55. bool GetItemHierarchyParent(UIElement* item)
  56. {
  57. return item ? item->GetVar(hierarchyParentHash).GetBool() : false;
  58. }
  59. void SetItemHierarchyParent(UIElement* item, bool enable)
  60. {
  61. item->SetVar(hierarchyParentHash, enable);
  62. }
  63. /// Hierarchy container (used by ListView internally when in hierarchy mode).
  64. class HierarchyContainer : public UIElement
  65. {
  66. OBJECT(HierarchyContainer);
  67. public:
  68. /// Construct.
  69. HierarchyContainer(Context* context, UIElement* overlayContainer) :
  70. UIElement(context),
  71. overlayContainer_(overlayContainer)
  72. {
  73. SubscribeToEvent(this, E_LAYOUTUPDATED, HANDLER(HierarchyContainer, HandleLayoutUpdated));
  74. SubscribeToEvent(overlayContainer->GetParent(), E_VIEWCHANGED, HANDLER(HierarchyContainer, HandleViewChanged));
  75. SubscribeToEvent(E_UIMOUSECLICK, HANDLER(HierarchyContainer, HandleUIMouseClick));
  76. }
  77. /// Handle layout updated by adjusting the position of the overlays.
  78. void HandleLayoutUpdated(StringHash eventType, VariantMap& eventData)
  79. {
  80. // Adjust the container size for child clipping effect
  81. overlayContainer_->SetSize(GetParent()->GetSize());
  82. for (unsigned i = 0; i < children_.Size(); ++i)
  83. {
  84. const IntVector2& position = children_[i]->GetPosition();
  85. CheckBox* overlay = static_cast<CheckBox*>(overlayContainer_->GetChild(i));
  86. bool visible = children_[i]->IsVisible() && GetItemHierarchyParent(children_[i]);
  87. overlay->SetVisible(visible);
  88. if (visible)
  89. {
  90. overlay->SetPosition(position.x_, position.y_);
  91. overlay->SetChecked(GetItemExpanded(children_[i]));
  92. }
  93. }
  94. }
  95. /// Handle view changed by scrolling the overlays in tandem.
  96. void HandleViewChanged(StringHash eventType, VariantMap& eventData)
  97. {
  98. using namespace ViewChanged;
  99. int x = eventData[P_X].GetInt();
  100. int y = eventData[P_Y].GetInt();
  101. IntRect panelBorder = GetParent()->GetClipBorder();
  102. overlayContainer_->SetChildOffset(IntVector2(-x + panelBorder.left_, -y + panelBorder.top_));
  103. }
  104. /// Handle mouse click on overlays by toggling the expansion state of the corresponding item
  105. void HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
  106. {
  107. using namespace UIMouseClick;
  108. UIElement* overlay = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  109. if (overlay)
  110. {
  111. const Vector<SharedPtr<UIElement> >& children = overlayContainer_->GetChildren();
  112. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Find(SharedPtr<UIElement>(overlay));
  113. if (i != children.End())
  114. static_cast<ListView*>(overlayContainer_->GetParent())->ToggleExpand(i - children.Begin());
  115. }
  116. }
  117. /// Insert a child element into a specific position in the child list.
  118. void InsertChild(unsigned index, UIElement* element)
  119. {
  120. // Insert the overlay at the same index position to the overlay container
  121. CheckBox* overlay = new CheckBox(context_);
  122. overlay->SetStyle(overlayContainer_->GetDefaultStyle(), "ListViewHierarchyOverlay");
  123. int baseIndent = static_cast<ListView*>(overlayContainer_->GetParent())->GetBaseIndent();
  124. int indent = element->GetIndent() - baseIndent - 1;
  125. overlay->SetIndent(indent);
  126. overlay->SetFixedWidth((indent + 1) * element->GetIndentSpacing());
  127. overlayContainer_->InsertChild(index, overlay);
  128. // Then insert the element as child as per normal
  129. UIElement::InsertChild(index, element);
  130. }
  131. private:
  132. UIElement* overlayContainer_;
  133. };
  134. OBJECTTYPESTATIC(HierarchyContainer);
  135. OBJECTTYPESTATIC(ListView);
  136. ListView::ListView(Context* context) :
  137. ScrollView(context),
  138. highlightMode_(HM_FOCUS),
  139. multiselect_(false),
  140. hierarchyMode_(true), // Init to true here so that the setter below takes effect
  141. baseIndent_(0),
  142. clearSelectionOnDefocus_(false),
  143. doubleClickInterval_(500),
  144. lastClickedItem_(M_MAX_UNSIGNED)
  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_FOCUSCHANGED, HANDLER(ListView, HandleFocusChanged));
  151. }
  152. ListView::~ListView()
  153. {
  154. }
  155. void ListView::RegisterObject(Context* context)
  156. {
  157. context->RegisterFactory<ListView>();
  158. COPY_BASE_ATTRIBUTES(HierarchyContainer, UIElement);
  159. COPY_BASE_ATTRIBUTES(ListView, ScrollView);
  160. ENUM_ACCESSOR_ATTRIBUTE(ListView, "Highlight Mode", GetHighlightMode, SetHighlightMode, HighlightMode, highlightModes, HM_FOCUS, AM_FILE);
  161. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Multiselect", GetMultiselect, SetMultiselect, bool, false, AM_FILE);
  162. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Hierarchy Mode", GetHierarchyMode, SetHierarchyMode, bool, false, AM_FILE);
  163. ACCESSOR_ATTRIBUTE(ListView, VAR_INT, "Base Indent", GetBaseIndent, SetBaseIndent, int, 0, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Clear Sel. On Defocus", GetClearSelectionOnDefocus, SetClearSelectionOnDefocus, bool, false, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(ListView, VAR_FLOAT, "Double Click Interval", GetDoubleClickInterval, SetDoubleClickInterval, float, 0.5f, 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_ = CreateChild<UIElement>("LV_OverlayContainer");
  568. overlayContainer_->SetInternal(true);
  569. overlayContainer_->SetSortChildren(false);
  570. overlayContainer_->SetClipChildren(true);
  571. container = new HierarchyContainer(context_, overlayContainer_);
  572. }
  573. else
  574. {
  575. if (overlayContainer_)
  576. {
  577. RemoveChild(overlayContainer_);
  578. overlayContainer_.Reset();
  579. }
  580. container = new UIElement(context_);
  581. }
  582. SetContentElement(container);
  583. container->SetInternal(true);
  584. container->SetName("LV_ItemContainer");
  585. container->SetEnabled(true);
  586. container->SetLayout(LM_VERTICAL);
  587. container->SetSortChildren(false);
  588. }
  589. void ListView::SetBaseIndent(int baseIndent)
  590. {
  591. baseIndent_ = baseIndent;
  592. UpdateLayout();
  593. }
  594. void ListView::SetClearSelectionOnDefocus(bool enable)
  595. {
  596. if (enable != clearSelectionOnDefocus_)
  597. {
  598. clearSelectionOnDefocus_ = enable;
  599. if (clearSelectionOnDefocus_)
  600. {
  601. SubscribeToEvent(this, E_DEFOCUSED, HANDLER(ListView, HandleDefocused));
  602. if (!HasFocus())
  603. ClearSelection();
  604. }
  605. else
  606. UnsubscribeFromEvent(this, E_DEFOCUSED);
  607. }
  608. }
  609. void ListView::SetDoubleClickInterval(float interval)
  610. {
  611. doubleClickInterval_ = Max((int)(interval * 1000.0f), 0);
  612. }
  613. void ListView::Expand(unsigned index, bool enable, bool recursive)
  614. {
  615. if (!hierarchyMode_)
  616. return;
  617. unsigned numItems = GetNumItems();
  618. if (index >= numItems)
  619. return;
  620. UIElement* item = GetItem(index++);
  621. SetItemExpanded(item, enable);
  622. int baseIndent = item->GetIndent();
  623. PODVector<bool> expanded(baseIndent + 1);
  624. expanded[baseIndent] = enable;
  625. contentElement_->DisableLayoutUpdate();
  626. while (index < numItems)
  627. {
  628. item = GetItem(index++);
  629. int indent = item->GetIndent();
  630. if (indent <= baseIndent)
  631. break;
  632. // Propagate the state to children when it is recursive
  633. if (recursive)
  634. SetItemExpanded(item, enable);
  635. // Use the parent expanded flag to influence the visibility of its children
  636. bool visible = enable && expanded[indent - 1];
  637. item->SetVisible(visible);
  638. if (indent >= (int)expanded.Size())
  639. expanded.Resize(indent + 1);
  640. expanded[indent] = visible && GetItemExpanded(item);
  641. }
  642. contentElement_->EnableLayoutUpdate();
  643. contentElement_->UpdateLayout();
  644. }
  645. void ListView::ToggleExpand(unsigned index, bool recursive)
  646. {
  647. if (!hierarchyMode_)
  648. return;
  649. unsigned numItems = GetNumItems();
  650. if (index >= numItems)
  651. return;
  652. UIElement* item = GetItem(index);
  653. Expand(index, !GetItemExpanded(item), recursive);
  654. }
  655. unsigned ListView::GetNumItems() const
  656. {
  657. return contentElement_->GetNumChildren();
  658. }
  659. UIElement* ListView::GetItem(unsigned index) const
  660. {
  661. return contentElement_->GetChild(index);
  662. }
  663. PODVector<UIElement*> ListView::GetItems() const
  664. {
  665. PODVector<UIElement*> items;
  666. contentElement_->GetChildren(items);
  667. return items;
  668. }
  669. unsigned ListView::FindItem(UIElement* item) const
  670. {
  671. const Vector<SharedPtr<UIElement> >& children = contentElement_->GetChildren();
  672. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Find(SharedPtr<UIElement>(item));
  673. if (i != children.End())
  674. return i - children.Begin();
  675. else
  676. return M_MAX_UNSIGNED;
  677. }
  678. unsigned ListView::GetSelection() const
  679. {
  680. if (selections_.Empty())
  681. return M_MAX_UNSIGNED;
  682. else
  683. return GetSelections().Front();
  684. }
  685. UIElement* ListView::GetSelectedItem() const
  686. {
  687. return contentElement_->GetChild(GetSelection());
  688. }
  689. PODVector<UIElement*> ListView::GetSelectedItems() const
  690. {
  691. PODVector<UIElement*> ret;
  692. for (PODVector<unsigned>::ConstIterator i = selections_.Begin(); i != selections_.End(); ++i)
  693. {
  694. UIElement* item = GetItem(*i);
  695. if (item)
  696. ret.Push(item);
  697. }
  698. return ret;
  699. }
  700. bool ListView::IsSelected(unsigned index) const
  701. {
  702. return selections_.Contains(index);
  703. }
  704. bool ListView::IsExpanded(unsigned index) const
  705. {
  706. return GetItemExpanded(contentElement_->GetChild(index));
  707. }
  708. float ListView::GetDoubleClickInterval() const
  709. {
  710. return (float)doubleClickInterval_ / 1000.0f;
  711. }
  712. bool ListView::FilterImplicitAttributes(XMLElement& dest) const
  713. {
  714. if (!ScrollView::FilterImplicitAttributes(dest))
  715. return false;
  716. XMLElement childElem = dest.GetChild("element"); // Horizontal scroll bar
  717. if (!childElem)
  718. return false;
  719. childElem = childElem.GetNext("element"); // Vertical scroll bar
  720. if (!childElem)
  721. return false;
  722. childElem = childElem.GetNext("element"); // Scroll panel
  723. if (!childElem)
  724. return false;
  725. XMLElement containerElem = childElem.GetChild("element"); // Item container
  726. if (!containerElem)
  727. return false;
  728. if (!RemoveChildXML(containerElem, "Name", "LV_ItemContainer"))
  729. return false;
  730. if (!RemoveChildXML(containerElem, "Is Enabled", "true"))
  731. return false;
  732. if (!RemoveChildXML(containerElem, "Layout Mode", "Vertical"))
  733. return false;
  734. if (!RemoveChildXML(containerElem, "Size"))
  735. return false;
  736. if (hierarchyMode_)
  737. {
  738. containerElem = childElem.GetNext("element"); // Overlay container
  739. if (!containerElem)
  740. return false;
  741. if (!RemoveChildXML(containerElem, "Name", "LV_OverlayContainer"))
  742. return false;
  743. if (!RemoveChildXML(containerElem, "Clip Children", "true"))
  744. return false;
  745. if (!RemoveChildXML(containerElem, "Size"))
  746. return false;
  747. }
  748. return true;
  749. }
  750. void ListView::UpdateSelectionEffect()
  751. {
  752. unsigned numItems = GetNumItems();
  753. bool highlighted = highlightMode_ == HM_ALWAYS || HasFocus();
  754. for (unsigned i = 0; i < numItems; ++i)
  755. {
  756. UIElement* item = GetItem(i);
  757. if (highlightMode_ != HM_NEVER && selections_.Contains(i))
  758. item->SetSelected(highlighted);
  759. else
  760. item->SetSelected(false);
  761. }
  762. }
  763. void ListView::EnsureItemVisibility(unsigned index)
  764. {
  765. EnsureItemVisibility(GetItem(index));
  766. }
  767. void ListView::EnsureItemVisibility(UIElement* item)
  768. {
  769. if (!item || !item->IsVisible())
  770. return;
  771. IntVector2 newView = GetViewPosition();
  772. IntVector2 currentOffset = item->GetPosition() - newView;
  773. const IntRect& clipBorder = scrollPanel_->GetClipBorder();
  774. IntVector2 windowSize(scrollPanel_->GetWidth() - clipBorder.left_ - clipBorder.right_, scrollPanel_->GetHeight() -
  775. clipBorder.top_ - clipBorder.bottom_);
  776. if (currentOffset.y_ < 0)
  777. newView.y_ += currentOffset.y_;
  778. if (currentOffset.y_ + item->GetHeight() > windowSize.y_)
  779. newView.y_ += currentOffset.y_ + item->GetHeight() - windowSize.y_;
  780. SetViewPosition(newView);
  781. }
  782. void ListView::HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
  783. {
  784. if (eventData[UIMouseClick::P_BUTTON].GetInt() != MOUSEB_LEFT)
  785. return;
  786. int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
  787. UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  788. unsigned numItems = GetNumItems();
  789. for (unsigned i = 0; i < numItems; ++i)
  790. {
  791. if (element == GetItem(i))
  792. {
  793. // Check doubleclick
  794. bool isDoubleClick = false;
  795. if (!multiselect_ || !qualifiers)
  796. {
  797. if (!(isDoubleClick = doubleClickTimer_.GetMSec(true) < doubleClickInterval_ && lastClickedItem_ == i))
  798. lastClickedItem_ = i;
  799. SetSelection(i);
  800. }
  801. // Check multiselect with shift & ctrl
  802. if (multiselect_)
  803. {
  804. if (qualifiers & QUAL_SHIFT)
  805. {
  806. if (selections_.Empty())
  807. SetSelection(i);
  808. else
  809. {
  810. unsigned first = selections_.Front();
  811. unsigned last = selections_.Back();
  812. PODVector<unsigned> newSelections = selections_;
  813. if (i == first || i == last)
  814. {
  815. for (unsigned j = first; j <= last; ++j)
  816. newSelections.Push(j);
  817. }
  818. else if (i < first)
  819. {
  820. for (unsigned j = i; j <= first; ++j)
  821. newSelections.Push(j);
  822. }
  823. else if (i < last)
  824. {
  825. if ((abs((int)i - (int)first)) <= (abs((int)i - (int)last)))
  826. {
  827. for (unsigned j = first; j <= i; ++j)
  828. newSelections.Push(j);
  829. }
  830. else
  831. {
  832. for (unsigned j = i; j <= last; ++j)
  833. newSelections.Push(j);
  834. }
  835. }
  836. else if (i > last)
  837. {
  838. for (unsigned j = last; j <= i; ++j)
  839. newSelections.Push(j);
  840. }
  841. SetSelections(newSelections);
  842. }
  843. }
  844. else if (qualifiers & QUAL_CTRL)
  845. ToggleSelection(i);
  846. }
  847. if (isDoubleClick)
  848. {
  849. VariantMap eventData;
  850. eventData[ItemDoubleClicked::P_ELEMENT] = (void*)this;
  851. eventData[ItemDoubleClicked::P_SELECTION] = i;
  852. SendEvent(E_ITEMDOUBLECLICKED, eventData);
  853. }
  854. return;
  855. }
  856. }
  857. }
  858. void ListView::HandleFocusChanged(StringHash eventType, VariantMap& eventData)
  859. {
  860. using namespace FocusChanged;
  861. UIElement* element = static_cast<UIElement*>(eventData[P_ELEMENT].GetPtr());
  862. while (element)
  863. {
  864. // If the focused element or its parent is in the list, scroll the list to make the item visible
  865. UIElement* parent = element->GetParent();
  866. if (parent == contentElement_)
  867. {
  868. EnsureItemVisibility(element);
  869. return;
  870. }
  871. element = parent;
  872. }
  873. }
  874. void ListView::HandleDefocused(StringHash eventType, VariantMap& eventData)
  875. {
  876. ClearSelection();
  877. }
  878. }