ListView.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "CheckBox.h"
  24. #include "Context.h"
  25. #include "InputEvents.h"
  26. #include "ListView.h"
  27. #include "Log.h"
  28. #include "Sort.h"
  29. #include "UIEvents.h"
  30. #include "DebugNew.h"
  31. namespace Urho3D
  32. {
  33. static const char* highlightModes[] =
  34. {
  35. "Never",
  36. "Focus",
  37. "Always",
  38. 0
  39. };
  40. template<> HighlightMode Variant::Get<HighlightMode>() const
  41. {
  42. return (HighlightMode)GetInt();
  43. }
  44. static const ShortStringHash expandedHash("Expanded");
  45. extern const char* UI_CATEGORY;
  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, ListView* listView, UIElement* overlayContainer) :
  70. UIElement(context),
  71. listView_(listView),
  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. listView_->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("HierarchyListViewOverlay");
  124. int baseIndent = listView_->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. // Parent list view.
  133. ListView* listView_;
  134. // Container for overlay checkboxes.
  135. UIElement* overlayContainer_;
  136. };
  137. ListView::ListView(Context* context) :
  138. ScrollView(context),
  139. highlightMode_(HM_FOCUS),
  140. multiselect_(false),
  141. hierarchyMode_(true), // Init to true here so that the setter below takes effect
  142. baseIndent_(0),
  143. clearSelectionOnDefocus_(false)
  144. {
  145. resizeContentWidth_ = true;
  146. // By default list view is set to non-hierarchy mode
  147. SetHierarchyMode(false);
  148. SubscribeToEvent(E_UIMOUSECLICK, HANDLER(ListView, HandleUIMouseClick));
  149. SubscribeToEvent(E_UIMOUSEDOUBLECLICK, HANDLER(ListView, HandleUIMouseDoubleClick));
  150. SubscribeToEvent(E_FOCUSCHANGED, HANDLER(ListView, HandleItemFocusChanged));
  151. SubscribeToEvent(this, E_DEFOCUSED, HANDLER(ListView, HandleFocusChanged));
  152. SubscribeToEvent(this, E_FOCUSED, HANDLER(ListView, HandleFocusChanged));
  153. }
  154. ListView::~ListView()
  155. {
  156. }
  157. void ListView::RegisterObject(Context* context)
  158. {
  159. context->RegisterFactory<ListView>(UI_CATEGORY);
  160. COPY_BASE_ATTRIBUTES(HierarchyContainer, UIElement);
  161. COPY_BASE_ATTRIBUTES(ListView, ScrollView);
  162. ENUM_ACCESSOR_ATTRIBUTE(ListView, "Highlight Mode", GetHighlightMode, SetHighlightMode, HighlightMode, highlightModes, HM_FOCUS, AM_FILE);
  163. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Multiselect", GetMultiselect, SetMultiselect, bool, false, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Hierarchy Mode", GetHierarchyMode, SetHierarchyMode, bool, false, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(ListView, VAR_INT, "Base Indent", GetBaseIndent, SetBaseIndent, int, 0, AM_FILE);
  166. ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Clear Sel. On Defocus", GetClearSelectionOnDefocus, SetClearSelectionOnDefocus, bool, false, AM_FILE);
  167. }
  168. void ListView::OnKey(int key, int buttons, int qualifiers)
  169. {
  170. // If no selection, can not move with keys
  171. unsigned numItems = GetNumItems();
  172. unsigned selection = GetSelection();
  173. // If either shift or ctrl held down, add to selection if multiselect enabled
  174. bool additive = multiselect_ && qualifiers & (QUAL_SHIFT | QUAL_CTRL);
  175. int delta = M_MAX_INT;
  176. int pageDirection = 1;
  177. if (numItems)
  178. {
  179. switch (key)
  180. {
  181. case KEY_LEFT:
  182. case KEY_RIGHT:
  183. if (selection != M_MAX_UNSIGNED && hierarchyMode_)
  184. {
  185. Expand(selection, key == KEY_RIGHT);
  186. return;
  187. }
  188. break;
  189. case KEY_RETURN:
  190. case KEY_RETURN2:
  191. case KEY_KP_ENTER:
  192. if (selection != M_MAX_UNSIGNED && hierarchyMode_)
  193. {
  194. ToggleExpand(selection);
  195. return;
  196. }
  197. break;
  198. case KEY_UP:
  199. delta = -1;
  200. break;
  201. case KEY_DOWN:
  202. delta = 1;
  203. break;
  204. case KEY_PAGEUP:
  205. pageDirection = -1;
  206. // Fallthru
  207. case KEY_PAGEDOWN:
  208. {
  209. // Convert page step to pixels and see how many items have to be skipped to reach that many pixels
  210. if (selection == M_MAX_UNSIGNED)
  211. selection = 0; // Assume as if first item is selected
  212. int stepPixels = ((int)(pageStep_ * scrollPanel_->GetHeight())) - contentElement_->GetChild(selection)->GetHeight();
  213. unsigned newSelection = selection;
  214. unsigned okSelection = selection;
  215. unsigned invisible = 0;
  216. while (newSelection < numItems)
  217. {
  218. UIElement* item = GetItem(newSelection);
  219. int height = 0;
  220. if (item->IsVisible())
  221. {
  222. height = item->GetHeight();
  223. okSelection = newSelection;
  224. }
  225. else
  226. ++invisible;
  227. if (stepPixels < height)
  228. break;
  229. stepPixels -= height;
  230. newSelection += pageDirection;
  231. }
  232. delta = okSelection - selection - pageDirection * invisible;
  233. }
  234. break;
  235. case KEY_HOME:
  236. delta = -(int)GetNumItems();
  237. break;
  238. case KEY_END:
  239. delta = GetNumItems();
  240. break;
  241. }
  242. }
  243. if (delta != M_MAX_INT)
  244. {
  245. ChangeSelection(delta, additive);
  246. return;
  247. }
  248. using namespace UnhandledKey;
  249. VariantMap& eventData = GetEventDataMap();
  250. eventData[P_ELEMENT] = this;
  251. eventData[P_KEY] = key;
  252. eventData[P_BUTTONS] = buttons;
  253. eventData[P_QUALIFIERS] = qualifiers;
  254. SendEvent(E_UNHANDLEDKEY, eventData);
  255. }
  256. void ListView::OnResize()
  257. {
  258. ScrollView::OnResize();
  259. // When in hierarchy mode also need to resize the overlay container
  260. if (hierarchyMode_)
  261. overlayContainer_->SetSize(scrollPanel_->GetSize());
  262. }
  263. void ListView::AddItem(UIElement* item)
  264. {
  265. InsertItem(M_MAX_UNSIGNED, item);
  266. }
  267. void ListView::InsertItem(unsigned index, UIElement* item, UIElement* parentItem)
  268. {
  269. if (!item || item->GetParent() == contentElement_)
  270. return;
  271. // Enable input so that clicking the item can be detected
  272. item->SetEnabled(true);
  273. item->SetSelected(false);
  274. unsigned numItems = contentElement_->GetNumChildren();
  275. if (hierarchyMode_)
  276. {
  277. int baseIndent = baseIndent_;
  278. if (parentItem)
  279. {
  280. baseIndent = parentItem->GetIndent();
  281. SetItemHierarchyParent(parentItem, true);
  282. // Adjust the index to ensure it is within the children index limit of the parent item
  283. unsigned indexLimit = FindItem(parentItem);
  284. if (index <= indexLimit)
  285. index = indexLimit + 1;
  286. else
  287. {
  288. while (++indexLimit < numItems)
  289. {
  290. if (contentElement_->GetChild(indexLimit)->GetIndent() <= baseIndent)
  291. break;
  292. }
  293. if (index > indexLimit)
  294. index = indexLimit;
  295. }
  296. }
  297. item->SetIndent(baseIndent + 1);
  298. SetItemExpanded(item, item->IsVisible());
  299. // Use the 'overrided' version to insert the child item
  300. static_cast<HierarchyContainer*>(contentElement_.Get())->InsertChild(index, item);
  301. }
  302. else
  303. {
  304. if (index > numItems)
  305. index = numItems;
  306. contentElement_->InsertChild(index, item);
  307. }
  308. // If necessary, shift the following selections
  309. if (!selections_.Empty())
  310. {
  311. for (unsigned i = 0; i < selections_.Size(); ++i)
  312. {
  313. if (selections_[i] >= index)
  314. ++selections_[i];
  315. }
  316. UpdateSelectionEffect();
  317. }
  318. }
  319. void ListView::RemoveItem(UIElement* item, unsigned index)
  320. {
  321. if (!item)
  322. return;
  323. unsigned numItems = GetNumItems();
  324. for (unsigned i = index; i < numItems; ++i)
  325. {
  326. if (GetItem(i) == item)
  327. {
  328. item->SetSelected(false);
  329. selections_.Remove(i);
  330. unsigned removed = 1;
  331. if (hierarchyMode_)
  332. {
  333. // Remove any child items in hierarchy mode
  334. if (GetItemHierarchyParent(item))
  335. {
  336. int baseIndent = item->GetIndent();
  337. for (unsigned j = i + 1; ; ++j)
  338. {
  339. UIElement* childItem = GetItem(i + 1);
  340. if (!childItem)
  341. break;
  342. if (childItem->GetIndent() > baseIndent)
  343. {
  344. childItem->SetSelected(false);
  345. selections_.Erase(j);
  346. contentElement_->RemoveChildAtIndex(i + 1);
  347. overlayContainer_->RemoveChildAtIndex(i + 1);
  348. ++removed;
  349. }
  350. else
  351. break;
  352. }
  353. }
  354. // Check if the parent of removed item still has other children
  355. if (i > 0)
  356. {
  357. int baseIndent = item->GetIndent();
  358. UIElement* prevKin = GetItem(i - 1); // Could be parent or sibling
  359. if (prevKin->GetIndent() < baseIndent)
  360. {
  361. UIElement* nextKin = GetItem(i + 1); // Could be sibling or parent-sibling or 0 if index out of bound
  362. if (!nextKin || nextKin->GetIndent() < baseIndent)
  363. {
  364. // If we reach here then the parent has no other children
  365. SetItemHierarchyParent(prevKin, false);
  366. }
  367. }
  368. }
  369. // Remove the overlay at the same index
  370. overlayContainer_->RemoveChildAtIndex(i);
  371. }
  372. // If necessary, shift the following selections
  373. if (!selections_.Empty())
  374. {
  375. for (unsigned j = 0; j < selections_.Size(); ++j)
  376. {
  377. if (selections_[j] > i)
  378. selections_[j] -= removed;
  379. }
  380. UpdateSelectionEffect();
  381. }
  382. contentElement_->RemoveChildAtIndex(i);
  383. break;
  384. }
  385. }
  386. }
  387. void ListView::RemoveItem(unsigned index)
  388. {
  389. RemoveItem(GetItem(index), index);
  390. }
  391. void ListView::RemoveAllItems()
  392. {
  393. contentElement_->DisableLayoutUpdate();
  394. ClearSelection();
  395. contentElement_->RemoveAllChildren();
  396. if (hierarchyMode_)
  397. overlayContainer_->RemoveAllChildren();
  398. contentElement_->EnableLayoutUpdate();
  399. contentElement_->UpdateLayout();
  400. }
  401. void ListView::SetSelection(unsigned index)
  402. {
  403. PODVector<unsigned> indices;
  404. indices.Push(index);
  405. SetSelections(indices);
  406. EnsureItemVisibility(index);
  407. }
  408. void ListView::SetSelections(const PODVector<unsigned>& indices)
  409. {
  410. // Make a weak pointer to self to check for destruction as a response to events
  411. WeakPtr<ListView> self(this);
  412. unsigned numItems = GetNumItems();
  413. // Remove first items that should no longer be selected
  414. for (PODVector<unsigned>::Iterator i = selections_.Begin(); i != selections_.End();)
  415. {
  416. unsigned index = *i;
  417. if (!indices.Contains(index))
  418. {
  419. i = selections_.Erase(i);
  420. using namespace ItemSelected;
  421. VariantMap& eventData = GetEventDataMap();
  422. eventData[P_ELEMENT] = this;
  423. eventData[P_SELECTION] = index;
  424. SendEvent(E_ITEMDESELECTED, eventData);
  425. if (self.Expired())
  426. return;
  427. }
  428. else
  429. ++i;
  430. }
  431. bool added = false;
  432. // Then add missing items
  433. for (PODVector<unsigned>::ConstIterator i = indices.Begin(); i != indices.End(); ++i)
  434. {
  435. unsigned index = *i;
  436. if (index < numItems)
  437. {
  438. // In singleselect mode, resend the event even for the same selection
  439. bool duplicate = selections_.Contains(index);
  440. if (!duplicate || !multiselect_)
  441. {
  442. if (!duplicate)
  443. {
  444. selections_.Push(index);
  445. added = true;
  446. }
  447. using namespace ItemSelected;
  448. VariantMap& eventData = GetEventDataMap();
  449. eventData[P_ELEMENT] = this;
  450. eventData[P_SELECTION] = *i;
  451. SendEvent(E_ITEMSELECTED, eventData);
  452. if (self.Expired())
  453. return;
  454. }
  455. }
  456. // If no multiselect enabled, allow setting only one item
  457. if (!multiselect_)
  458. break;
  459. }
  460. // Re-sort selections if necessary
  461. if (added)
  462. Sort(selections_.Begin(), selections_.End());
  463. UpdateSelectionEffect();
  464. SendEvent(E_SELECTIONCHANGED);
  465. }
  466. void ListView::AddSelection(unsigned index)
  467. {
  468. // Make a weak pointer to self to check for destruction as a response to events
  469. WeakPtr<ListView> self(this);
  470. if (!multiselect_)
  471. SetSelection(index);
  472. else
  473. {
  474. if (index >= GetNumItems())
  475. return;
  476. if (!selections_.Contains(index))
  477. {
  478. selections_.Push(index);
  479. using namespace ItemSelected;
  480. VariantMap& eventData = GetEventDataMap();
  481. eventData[P_ELEMENT] = this;
  482. eventData[P_SELECTION] = index;
  483. SendEvent(E_ITEMSELECTED, eventData);
  484. if (self.Expired())
  485. return;
  486. Sort(selections_.Begin(), selections_.End());
  487. }
  488. EnsureItemVisibility(index);
  489. UpdateSelectionEffect();
  490. SendEvent(E_SELECTIONCHANGED);
  491. }
  492. }
  493. void ListView::RemoveSelection(unsigned index)
  494. {
  495. if (index >= GetNumItems())
  496. return;
  497. if (selections_.Remove(index))
  498. {
  499. using namespace ItemSelected;
  500. VariantMap& eventData = GetEventDataMap();
  501. eventData[P_ELEMENT] = this;
  502. eventData[P_SELECTION] = index;
  503. SendEvent(E_ITEMDESELECTED, eventData);
  504. }
  505. EnsureItemVisibility(index);
  506. UpdateSelectionEffect();
  507. SendEvent(E_SELECTIONCHANGED);
  508. }
  509. void ListView::ToggleSelection(unsigned index)
  510. {
  511. unsigned numItems = GetNumItems();
  512. if (index >= numItems)
  513. return;
  514. if (selections_.Contains(index))
  515. RemoveSelection(index);
  516. else
  517. AddSelection(index);
  518. }
  519. void ListView::ChangeSelection(int delta, bool additive)
  520. {
  521. unsigned numItems = GetNumItems();
  522. if (selections_.Empty())
  523. {
  524. // Select first item if there is no selection yet
  525. if (numItems > 0)
  526. SetSelection(0);
  527. if (abs(delta) == 1)
  528. return;
  529. }
  530. if (!multiselect_)
  531. additive = false;
  532. // If going downwards, use the last selection as a base. Otherwise use first
  533. unsigned selection = delta > 0 ? selections_.Back() : selections_.Front();
  534. int direction = delta > 0 ? 1 : -1;
  535. unsigned newSelection = selection;
  536. unsigned okSelection = selection;
  537. PODVector<unsigned> indices = selections_;
  538. while (delta != 0)
  539. {
  540. newSelection += direction;
  541. if (newSelection >= numItems)
  542. break;
  543. UIElement* item = GetItem(newSelection);
  544. if (item->IsVisible())
  545. {
  546. indices.Push(okSelection = newSelection);
  547. delta -= direction;
  548. }
  549. }
  550. if (!additive)
  551. SetSelection(okSelection);
  552. else
  553. SetSelections(indices);
  554. }
  555. void ListView::ClearSelection()
  556. {
  557. SetSelections(PODVector<unsigned>());
  558. }
  559. void ListView::SetHighlightMode(HighlightMode mode)
  560. {
  561. highlightMode_ = mode;
  562. UpdateSelectionEffect();
  563. }
  564. void ListView::SetMultiselect(bool enable)
  565. {
  566. multiselect_ = enable;
  567. }
  568. void ListView::SetHierarchyMode(bool enable)
  569. {
  570. if (enable == hierarchyMode_)
  571. return;
  572. hierarchyMode_ = enable;
  573. UIElement* container;
  574. if (enable)
  575. {
  576. overlayContainer_ = new UIElement(context_);
  577. overlayContainer_->SetName("LV_OverlayContainer");
  578. overlayContainer_->SetInternal(true);
  579. AddChild(overlayContainer_);
  580. overlayContainer_->SetSortChildren(false);
  581. overlayContainer_->SetClipChildren(true);
  582. container = new HierarchyContainer(context_, this, overlayContainer_);
  583. }
  584. else
  585. {
  586. if (overlayContainer_)
  587. {
  588. RemoveChild(overlayContainer_);
  589. overlayContainer_.Reset();
  590. }
  591. container = new UIElement(context_);
  592. }
  593. container->SetName("LV_ItemContainer");
  594. container->SetInternal(true);
  595. SetContentElement(container);
  596. container->SetEnabled(true);
  597. container->SetSortChildren(false);
  598. }
  599. void ListView::SetBaseIndent(int baseIndent)
  600. {
  601. baseIndent_ = baseIndent;
  602. UpdateLayout();
  603. }
  604. void ListView::SetClearSelectionOnDefocus(bool enable)
  605. {
  606. if (enable != clearSelectionOnDefocus_)
  607. {
  608. clearSelectionOnDefocus_ = enable;
  609. if (clearSelectionOnDefocus_ && !HasFocus())
  610. ClearSelection();
  611. }
  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. if (!item)
  672. return M_MAX_UNSIGNED;
  673. // Early-out by checking if the item belongs to the listview hierarchy at all
  674. if (item->GetParent() != contentElement_)
  675. return M_MAX_UNSIGNED;
  676. const Vector<SharedPtr<UIElement> >& children = contentElement_->GetChildren();
  677. // Binary search for list item based on screen coordinate Y
  678. if (contentElement_->GetLayoutMode() == LM_VERTICAL && item->GetHeight())
  679. {
  680. int itemY = item->GetScreenPosition().y_;
  681. int left = 0;
  682. int right = children.Size() - 1;
  683. while (right >= left)
  684. {
  685. int mid = (left + right) / 2;
  686. if (children[mid] == item)
  687. return mid;
  688. if (itemY < children[mid]->GetScreenPosition().y_)
  689. right = mid - 1;
  690. else
  691. left = mid + 1;
  692. }
  693. }
  694. // Fallback to linear search in case the coordinates/sizes were not yet initialized
  695. for (unsigned i = 0; i < children.Size(); ++i)
  696. {
  697. if (children[i] == item)
  698. return i;
  699. }
  700. return M_MAX_UNSIGNED;
  701. }
  702. unsigned ListView::GetSelection() const
  703. {
  704. if (selections_.Empty())
  705. return M_MAX_UNSIGNED;
  706. else
  707. return GetSelections().Front();
  708. }
  709. UIElement* ListView::GetSelectedItem() const
  710. {
  711. return contentElement_->GetChild(GetSelection());
  712. }
  713. PODVector<UIElement*> ListView::GetSelectedItems() const
  714. {
  715. PODVector<UIElement*> ret;
  716. for (PODVector<unsigned>::ConstIterator i = selections_.Begin(); i != selections_.End(); ++i)
  717. {
  718. UIElement* item = GetItem(*i);
  719. if (item)
  720. ret.Push(item);
  721. }
  722. return ret;
  723. }
  724. bool ListView::IsSelected(unsigned index) const
  725. {
  726. return selections_.Contains(index);
  727. }
  728. bool ListView::IsExpanded(unsigned index) const
  729. {
  730. return GetItemExpanded(contentElement_->GetChild(index));
  731. }
  732. bool ListView::FilterImplicitAttributes(XMLElement& dest) const
  733. {
  734. if (!ScrollView::FilterImplicitAttributes(dest))
  735. return false;
  736. XMLElement childElem = dest.GetChild("element"); // Horizontal scroll bar
  737. if (!childElem)
  738. return false;
  739. childElem = childElem.GetNext("element"); // Vertical scroll bar
  740. if (!childElem)
  741. return false;
  742. childElem = childElem.GetNext("element"); // Scroll panel
  743. if (!childElem)
  744. return false;
  745. XMLElement containerElem = childElem.GetChild("element"); // Item container
  746. if (!containerElem)
  747. return false;
  748. if (!RemoveChildXML(containerElem, "Name", "LV_ItemContainer"))
  749. return false;
  750. if (!RemoveChildXML(containerElem, "Is Enabled", "true"))
  751. return false;
  752. if (!RemoveChildXML(containerElem, "Layout Mode", "Vertical"))
  753. return false;
  754. if (!RemoveChildXML(containerElem, "Size"))
  755. return false;
  756. if (hierarchyMode_)
  757. {
  758. containerElem = childElem.GetNext("element"); // Overlay container
  759. if (!containerElem)
  760. return false;
  761. if (!RemoveChildXML(containerElem, "Name", "LV_OverlayContainer"))
  762. return false;
  763. if (!RemoveChildXML(containerElem, "Clip Children", "true"))
  764. return false;
  765. if (!RemoveChildXML(containerElem, "Size"))
  766. return false;
  767. }
  768. return true;
  769. }
  770. void ListView::UpdateSelectionEffect()
  771. {
  772. unsigned numItems = GetNumItems();
  773. bool highlighted = highlightMode_ == HM_ALWAYS || HasFocus();
  774. for (unsigned i = 0; i < numItems; ++i)
  775. {
  776. UIElement* item = GetItem(i);
  777. if (highlightMode_ != HM_NEVER && selections_.Contains(i))
  778. item->SetSelected(highlighted);
  779. else
  780. item->SetSelected(false);
  781. }
  782. }
  783. void ListView::EnsureItemVisibility(unsigned index)
  784. {
  785. EnsureItemVisibility(GetItem(index));
  786. }
  787. void ListView::EnsureItemVisibility(UIElement* item)
  788. {
  789. if (!item || !item->IsVisible())
  790. return;
  791. IntVector2 newView = GetViewPosition();
  792. IntVector2 currentOffset = item->GetPosition() - newView;
  793. const IntRect& clipBorder = scrollPanel_->GetClipBorder();
  794. IntVector2 windowSize(scrollPanel_->GetWidth() - clipBorder.left_ - clipBorder.right_, scrollPanel_->GetHeight() -
  795. clipBorder.top_ - clipBorder.bottom_);
  796. if (currentOffset.y_ < 0)
  797. newView.y_ += currentOffset.y_;
  798. if (currentOffset.y_ + item->GetHeight() > windowSize.y_)
  799. newView.y_ += currentOffset.y_ + item->GetHeight() - windowSize.y_;
  800. SetViewPosition(newView);
  801. }
  802. void ListView::HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
  803. {
  804. int button = eventData[UIMouseClick::P_BUTTON].GetInt();
  805. int buttons = eventData[UIMouseClick::P_BUTTONS].GetInt();
  806. int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
  807. UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  808. // Check if the clicked element belongs to the list
  809. unsigned i = FindItem(element);
  810. if (i >= GetNumItems())
  811. return;
  812. // If not editable, repeat the previous selection. This will send an event and allow eg. a dropdownlist to close
  813. if (!editable_)
  814. {
  815. SetSelections(selections_);
  816. return;
  817. }
  818. if (button == MOUSEB_LEFT)
  819. {
  820. // Single selection
  821. if (!multiselect_ || !qualifiers)
  822. SetSelection(i);
  823. // Check multiselect with shift & ctrl
  824. if (multiselect_)
  825. {
  826. if (qualifiers & QUAL_SHIFT)
  827. {
  828. if (selections_.Empty())
  829. SetSelection(i);
  830. else
  831. {
  832. unsigned first = selections_.Front();
  833. unsigned last = selections_.Back();
  834. PODVector<unsigned> newSelections = selections_;
  835. if (i == first || i == last)
  836. {
  837. for (unsigned j = first; j <= last; ++j)
  838. newSelections.Push(j);
  839. }
  840. else if (i < first)
  841. {
  842. for (unsigned j = i; j <= first; ++j)
  843. newSelections.Push(j);
  844. }
  845. else if (i < last)
  846. {
  847. if ((abs((int)i - (int)first)) <= (abs((int)i - (int)last)))
  848. {
  849. for (unsigned j = first; j <= i; ++j)
  850. newSelections.Push(j);
  851. }
  852. else
  853. {
  854. for (unsigned j = i; j <= last; ++j)
  855. newSelections.Push(j);
  856. }
  857. }
  858. else if (i > last)
  859. {
  860. for (unsigned j = last; j <= i; ++j)
  861. newSelections.Push(j);
  862. }
  863. SetSelections(newSelections);
  864. }
  865. }
  866. else if (qualifiers & QUAL_CTRL)
  867. ToggleSelection(i);
  868. }
  869. }
  870. // Propagate the click as an event. Also include right-clicks
  871. VariantMap& clickEventData = GetEventDataMap();
  872. clickEventData[ItemClicked::P_ELEMENT] = this;
  873. clickEventData[ItemClicked::P_ITEM] = element;
  874. clickEventData[ItemClicked::P_SELECTION] = i;
  875. clickEventData[ItemClicked::P_BUTTON] = button;
  876. clickEventData[ItemClicked::P_BUTTONS] = buttons;
  877. clickEventData[ItemClicked::P_QUALIFIERS] = qualifiers;
  878. SendEvent(E_ITEMCLICKED, clickEventData);
  879. }
  880. void ListView::HandleUIMouseDoubleClick(StringHash eventType, VariantMap& eventData)
  881. {
  882. int button = eventData[UIMouseClick::P_BUTTON].GetInt();
  883. int buttons = eventData[UIMouseClick::P_BUTTONS].GetInt();
  884. int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
  885. UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  886. // Check if the clicked element belongs to the list
  887. unsigned i = FindItem(element);
  888. if (i >= GetNumItems())
  889. return;
  890. VariantMap& clickEventData = GetEventDataMap();
  891. clickEventData[ItemDoubleClicked::P_ELEMENT] = this;
  892. clickEventData[ItemDoubleClicked::P_ITEM] = element;
  893. clickEventData[ItemDoubleClicked::P_SELECTION] = i;
  894. clickEventData[ItemDoubleClicked::P_BUTTON] = button;
  895. clickEventData[ItemDoubleClicked::P_BUTTONS] = buttons;
  896. clickEventData[ItemDoubleClicked::P_QUALIFIERS] = qualifiers;
  897. SendEvent(E_ITEMDOUBLECLICKED, clickEventData);
  898. }
  899. void ListView::HandleItemFocusChanged(StringHash eventType, VariantMap& eventData)
  900. {
  901. using namespace FocusChanged;
  902. UIElement* element = static_cast<UIElement*>(eventData[P_ELEMENT].GetPtr());
  903. while (element)
  904. {
  905. // If the focused element or its parent is in the list, scroll the list to make the item visible
  906. UIElement* parent = element->GetParent();
  907. if (parent == contentElement_)
  908. {
  909. EnsureItemVisibility(element);
  910. return;
  911. }
  912. element = parent;
  913. }
  914. }
  915. void ListView::HandleFocusChanged(StringHash eventType, VariantMap& eventData)
  916. {
  917. scrollPanel_->SetSelected(eventType == E_FOCUSED);
  918. if (clearSelectionOnDefocus_ && eventType == E_DEFOCUSED)
  919. ClearSelection();
  920. else if (highlightMode_ == HM_FOCUS)
  921. UpdateSelectionEffect();
  922. }
  923. }