ListView.cpp 33 KB

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