WidgetDropDown.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "WidgetDropDown.h"
  29. #include "../../../Include/RmlUi/Core/Context.h"
  30. #include "../../../Include/RmlUi/Core/ElementDocument.h"
  31. #include "../../../Include/RmlUi/Core/Math.h"
  32. #include "../../../Include/RmlUi/Core/Factory.h"
  33. #include "../../../Include/RmlUi/Core/ElementUtilities.h"
  34. #include "../../../Include/RmlUi/Core/Event.h"
  35. #include "../../../Include/RmlUi/Core/Input.h"
  36. #include "../../../Include/RmlUi/Core/Property.h"
  37. #include "../../../Include/RmlUi/Core/Profiling.h"
  38. #include "../../../Include/RmlUi/Core/Elements/ElementFormControl.h"
  39. namespace Rml {
  40. WidgetDropDown::WidgetDropDown(ElementFormControl* element)
  41. {
  42. parent_element = element;
  43. lock_selection = false;
  44. selection_dirty = false;
  45. box_layout_dirty = false;
  46. value_rml_dirty = false;
  47. value_layout_dirty = false;
  48. box_visible = false;
  49. // Create the button and selection elements.
  50. button_element = parent_element->AppendChild(Factory::InstanceElement(parent_element, "*", "selectarrow", XMLAttributes()), false);
  51. value_element = parent_element->AppendChild(Factory::InstanceElement(parent_element, "*", "selectvalue", XMLAttributes()), false);
  52. selection_element = parent_element->AppendChild(Factory::InstanceElement(parent_element, "*", "selectbox", XMLAttributes()), false);
  53. value_element->SetProperty(PropertyId::OverflowX, Property(Style::Overflow::Hidden));
  54. value_element->SetProperty(PropertyId::OverflowY, Property(Style::Overflow::Hidden));
  55. selection_element->SetProperty(PropertyId::Visibility, Property(Style::Visibility::Hidden));
  56. selection_element->SetProperty(PropertyId::ZIndex, Property(1.0f, Property::NUMBER));
  57. selection_element->SetProperty(PropertyId::Clip, Property(Style::Clip::Type::None));
  58. selection_element->SetProperty(PropertyId::OverflowY, Property(Style::Overflow::Auto));
  59. parent_element->AddEventListener(EventId::Click, this, true);
  60. parent_element->AddEventListener(EventId::Blur, this);
  61. parent_element->AddEventListener(EventId::Focus, this);
  62. parent_element->AddEventListener(EventId::Keydown, this, true);
  63. selection_element->AddEventListener(EventId::Mousescroll, this);
  64. }
  65. WidgetDropDown::~WidgetDropDown()
  66. {
  67. // We shouldn't clear the options ourselves, as removing the element will automatically clear children.
  68. // However, we do need to remove events of children.
  69. const int num_options = selection_element->GetNumChildren();
  70. for (int i = 0; i < num_options; i++)
  71. selection_element->GetChild(i)->RemoveEventListener(EventId::Click, this);
  72. parent_element->RemoveEventListener(EventId::Click, this, true);
  73. parent_element->RemoveEventListener(EventId::Blur, this);
  74. parent_element->RemoveEventListener(EventId::Focus, this);
  75. parent_element->RemoveEventListener(EventId::Keydown, this, true);
  76. selection_element->RemoveEventListener(EventId::Mousescroll, this);
  77. DetachScrollEvent();
  78. }
  79. void WidgetDropDown::OnUpdate()
  80. {
  81. if (selection_dirty)
  82. {
  83. // Find the best option element to select in the following priority:
  84. // 1. First option with 'selected' attribute.
  85. // 2. An option whose 'value' attribute matches the select 'value' attribute.
  86. // 3. The first option.
  87. // The select element's value may change as a result of this.
  88. const String select_value = parent_element->GetAttribute("value", String());
  89. Element* select_option = selection_element->GetFirstChild();
  90. const int num_options = selection_element->GetNumChildren();
  91. for (int i = 0; i < num_options; i++)
  92. {
  93. Element* option = selection_element->GetChild(i);
  94. if (option->HasAttribute("selected"))
  95. {
  96. select_option = option;
  97. break;
  98. }
  99. else if (!select_value.empty() && select_value == option->GetAttribute("value", String()))
  100. {
  101. select_option = option;
  102. }
  103. }
  104. if (select_option)
  105. SetSelection(select_option);
  106. selection_dirty = false;
  107. }
  108. if (value_rml_dirty)
  109. {
  110. String value_rml;
  111. const int selection = GetSelection();
  112. if (Element* option = selection_element->GetChild(selection))
  113. option->GetInnerRML(value_rml);
  114. else
  115. value_rml = parent_element->GetValue();
  116. value_element->SetInnerRML(value_rml);
  117. value_rml_dirty = false;
  118. value_layout_dirty = true;
  119. }
  120. }
  121. void WidgetDropDown::OnRender()
  122. {
  123. if (box_visible && box_layout_dirty)
  124. {
  125. // Layout the selection box.
  126. // The following procedure should ensure that the selection box is never (partly) outside of the context's window.
  127. // This is achieved by positioning the box either above or below the 'select' element, and possibly shrinking
  128. // the element's height.
  129. // We try to respect user values of 'height', 'min-height', and 'max-height'. However, when we need to shrink the box
  130. // we will override the 'height' property.
  131. // Previously set 'height' property from this procedure must be removed for the calculations below to work as intended.
  132. if(selection_element->GetLocalStyleProperties().count(PropertyId::Height) == 1)
  133. {
  134. selection_element->RemoveProperty(PropertyId::Height);
  135. selection_element->GetOwnerDocument()->UpdateDocument();
  136. }
  137. Box box;
  138. ElementUtilities::BuildBox(box, parent_element->GetBox().GetSize(), selection_element);
  139. // The user can use 'margin-left/top/bottom' to offset the box away from the 'select' element, respectively
  140. // horizontally, vertically when box below, and vertically when box above.
  141. const float offset_x = box.GetEdge(Box::MARGIN, Box::LEFT);
  142. const float offset_y_below = parent_element->GetBox().GetSize(Box::BORDER).y + box.GetEdge(Box::MARGIN, Box::TOP);
  143. const float offset_y_above = -box.GetEdge(Box::MARGIN, Box::BOTTOM);
  144. float window_height = 100'000.f;
  145. if (Context* context = parent_element->GetContext())
  146. window_height = float(context->GetDimensions().y);
  147. const float absolute_y = parent_element->GetAbsoluteOffset(Box::BORDER).y;
  148. const float height_below = window_height - absolute_y - offset_y_below;
  149. const float height_above = absolute_y + offset_y_above;
  150. // Format the selection box and retrieve the 'native' height occupied by all the options, while respecting
  151. // the 'min/max-height' properties.
  152. ElementUtilities::FormatElement(selection_element, parent_element->GetBox().GetSize(Box::BORDER));
  153. const float content_height = selection_element->GetOffsetHeight();
  154. if (content_height < height_below)
  155. {
  156. // Position box below
  157. selection_element->SetOffset(Vector2f(offset_x, offset_y_below), parent_element);
  158. }
  159. else if (content_height < height_above)
  160. {
  161. // Position box above
  162. selection_element->SetOffset(Vector2f(offset_x, -content_height + offset_y_above), parent_element);
  163. }
  164. else
  165. {
  166. // Shrink box and position either below or above
  167. const float padding_border_size =
  168. box.GetEdge(Box::BORDER, Box::TOP) + box.GetEdge(Box::BORDER, Box::BOTTOM) +
  169. box.GetEdge(Box::PADDING, Box::TOP) + box.GetEdge(Box::PADDING, Box::BOTTOM);
  170. float height = 0.f;
  171. float offset_y = 0.f;
  172. if (height_below > height_above)
  173. {
  174. // Position below
  175. height = height_below - padding_border_size;
  176. offset_y = offset_y_below;
  177. }
  178. else
  179. {
  180. // Position above
  181. height = height_above - padding_border_size;
  182. offset_y = offset_y_above - height_above;
  183. }
  184. // Set the height and re-format the selection box.
  185. selection_element->SetProperty(PropertyId::Height, Property(height, Property::PX));
  186. selection_element->GetOwnerDocument()->UpdateDocument();
  187. ElementUtilities::FormatElement(selection_element, parent_element->GetBox().GetSize(Box::BORDER));
  188. selection_element->SetOffset(Vector2f(offset_x, offset_y), parent_element);
  189. }
  190. box_layout_dirty = false;
  191. }
  192. if (value_layout_dirty)
  193. {
  194. ElementUtilities::FormatElement(value_element, parent_element->GetBox().GetSize(Box::BORDER));
  195. value_element->SetOffset(parent_element->GetBox().GetPosition(Box::CONTENT), parent_element);
  196. value_layout_dirty = false;
  197. }
  198. }
  199. void WidgetDropDown::OnLayout()
  200. {
  201. RMLUI_ZoneScopedNC("DropDownLayout", 0x7FFF00);
  202. if(parent_element->IsDisabled())
  203. {
  204. // Propagate disabled state to selectvalue and selectarrow
  205. value_element->SetPseudoClass("disabled", true);
  206. button_element->SetPseudoClass("disabled", true);
  207. }
  208. // Layout the button and selection boxes.
  209. Box parent_box = parent_element->GetBox();
  210. ElementUtilities::PositionElement(button_element, Vector2f(0, 0), ElementUtilities::TOP_RIGHT);
  211. ElementUtilities::PositionElement(selection_element, Vector2f(0, 0), ElementUtilities::TOP_LEFT);
  212. // Calculate the value element position and size.
  213. Vector2f size;
  214. size.x = parent_element->GetBox().GetSize(Box::CONTENT).x - button_element->GetBox().GetSize(Box::MARGIN).x;
  215. size.y = parent_element->GetBox().GetSize(Box::CONTENT).y;
  216. value_element->SetOffset(parent_element->GetBox().GetPosition(Box::CONTENT), parent_element);
  217. value_element->SetBox(Box(size));
  218. box_layout_dirty = true;
  219. value_layout_dirty = true;
  220. }
  221. // Sets the value of the widget.
  222. void WidgetDropDown::OnValueChange(const String& value)
  223. {
  224. if (!lock_selection)
  225. {
  226. Element* select_option = nullptr;
  227. const int num_options = selection_element->GetNumChildren();
  228. for (int i = 0; i < num_options; i++)
  229. {
  230. Element* option = selection_element->GetChild(i);
  231. Variant* variant = option->GetAttribute("value");
  232. if (variant && variant->Get<String>() == value)
  233. {
  234. select_option = option;
  235. break;
  236. }
  237. }
  238. if (select_option && !select_option->HasAttribute("selected"))
  239. SetSelection(select_option);
  240. }
  241. Dictionary parameters;
  242. parameters["value"] = value;
  243. parent_element->DispatchEvent(EventId::Change, parameters);
  244. value_rml_dirty = true;
  245. }
  246. void WidgetDropDown::SetSelection(Element* select_option, bool force)
  247. {
  248. const String old_value = parent_element->GetAttribute("value", String());
  249. const String new_value = select_option ? select_option->GetAttribute("value", String()) : String();
  250. bool newly_selected = false;
  251. const int num_options = selection_element->GetNumChildren();
  252. for (int i = 0; i < num_options; i++)
  253. {
  254. Element* option = selection_element->GetChild(i);
  255. if (select_option == option)
  256. {
  257. if (!option->IsPseudoClassSet("checked"))
  258. newly_selected = true;
  259. option->SetAttribute("selected", String());
  260. option->SetPseudoClass("checked", true);
  261. }
  262. else
  263. {
  264. option->RemoveAttribute("selected");
  265. option->SetPseudoClass("checked", false);
  266. }
  267. }
  268. if (force || newly_selected || (old_value != new_value))
  269. {
  270. lock_selection = true;
  271. parent_element->SetAttribute("value", new_value);
  272. lock_selection = false;
  273. }
  274. value_rml_dirty = true;
  275. }
  276. void WidgetDropDown::SeekSelection(bool seek_forward)
  277. {
  278. const int selected_option = GetSelection();
  279. const int num_options = selection_element->GetNumChildren();
  280. const int seek_direction = (seek_forward ? 1 : -1);
  281. for (int i = selected_option + seek_direction; i >= 0 && i < num_options; i += seek_direction)
  282. {
  283. Element* element = selection_element->GetChild(i);
  284. if (!element->HasAttribute("disabled") && element->IsVisible())
  285. {
  286. SetSelection(element);
  287. return;
  288. }
  289. }
  290. // No valid option found, leave selection unchanged.
  291. }
  292. // Returns the index of the currently selected item.
  293. int WidgetDropDown::GetSelection() const
  294. {
  295. const int num_options = selection_element->GetNumChildren();
  296. for (int i = 0; i < num_options; i++)
  297. {
  298. if (selection_element->GetChild(i)->HasAttribute("selected"))
  299. return i;
  300. }
  301. return -1;
  302. }
  303. // Adds a new option to the select control.
  304. int WidgetDropDown::AddOption(const String& rml, const String& option_value, int before, bool select, bool selectable)
  305. {
  306. ElementPtr element = Factory::InstanceElement(selection_element, "*", "option", XMLAttributes());
  307. element->SetInnerRML(rml);
  308. element->SetAttribute("value", option_value);
  309. if (select)
  310. element->SetAttribute("selected", String());
  311. if (!selectable)
  312. element->SetAttribute("disabled", String());
  313. int result = AddOption(std::move(element), before);
  314. return result;
  315. }
  316. int WidgetDropDown::AddOption(ElementPtr element, int before)
  317. {
  318. if (element->GetTagName() != "option")
  319. {
  320. Log::Message(Log::LT_WARNING, "A child of '%s' must be of type 'option' but '%s' was given. See element '%s'.", parent_element->GetTagName().c_str(), element->GetTagName().c_str(), parent_element->GetAddress().c_str());
  321. return -1;
  322. }
  323. const int num_children_before = selection_element->GetNumChildren();
  324. int option_index;
  325. if (before < 0 || before >= num_children_before)
  326. {
  327. selection_element->AppendChild(std::move(element));
  328. option_index = num_children_before;
  329. }
  330. else
  331. {
  332. selection_element->InsertBefore(std::move(element), selection_element->GetChild(before));
  333. option_index = before;
  334. }
  335. return option_index;
  336. }
  337. // Removes an option from the select control.
  338. void WidgetDropDown::RemoveOption(int index)
  339. {
  340. Element* element = selection_element->GetChild(index);
  341. if (!element)
  342. return;
  343. selection_element->RemoveChild(element);
  344. }
  345. // Removes all options from the list.
  346. void WidgetDropDown::ClearOptions()
  347. {
  348. while (Element* element = selection_element->GetLastChild())
  349. selection_element->RemoveChild(element);
  350. }
  351. // Returns on of the widget's options.
  352. Element* WidgetDropDown::GetOption(int index)
  353. {
  354. return selection_element->GetChild(index);
  355. }
  356. // Returns the number of options in the widget.
  357. int WidgetDropDown::GetNumOptions() const
  358. {
  359. return selection_element->GetNumChildren();
  360. }
  361. void WidgetDropDown::OnChildAdd(Element* element)
  362. {
  363. // We have a special case for 'data-for' here, since that element must remain hidden.
  364. if (element->GetParentNode() != selection_element || element->HasAttribute("data-for") || element->GetTagName() != "option")
  365. return;
  366. // Force to block display. Register a click handler so we can be notified of selection.
  367. element->SetProperty(PropertyId::Display, Property(Style::Display::Block));
  368. element->SetProperty(PropertyId::Clip, Property(Style::Clip::Type::Auto));
  369. element->AddEventListener(EventId::Click, this);
  370. // Select the option if appropriate.
  371. if (element->HasAttribute("selected"))
  372. SetSelection(element, true);
  373. selection_dirty = true;
  374. box_layout_dirty = true;
  375. }
  376. void WidgetDropDown::OnChildRemove(Element* element)
  377. {
  378. if (element->GetParentNode() != selection_element)
  379. return;
  380. element->RemoveEventListener(EventId::Click, this);
  381. if (element->HasAttribute("selected"))
  382. SetSelection(nullptr);
  383. selection_dirty = true;
  384. box_layout_dirty = true;
  385. }
  386. void WidgetDropDown::AttachScrollEvent()
  387. {
  388. if (ElementDocument* document = parent_element->GetOwnerDocument())
  389. document->AddEventListener(EventId::Scroll, this, true);
  390. }
  391. void WidgetDropDown::DetachScrollEvent()
  392. {
  393. if (ElementDocument* document = parent_element->GetOwnerDocument())
  394. document->RemoveEventListener(EventId::Scroll, this, true);
  395. }
  396. void WidgetDropDown::ProcessEvent(Event& event)
  397. {
  398. if (parent_element->IsDisabled())
  399. return;
  400. // Process the button onclick
  401. switch (event.GetId())
  402. {
  403. case EventId::Click:
  404. {
  405. if (event.GetCurrentElement()->GetParentNode() == selection_element)
  406. {
  407. const int num_options = selection_element->GetNumChildren();
  408. // Find the element in the options and fire the selection event
  409. for (int i = 0; i < num_options; i++)
  410. {
  411. Element* current_element = event.GetCurrentElement();
  412. if (selection_element->GetChild(i) == current_element)
  413. {
  414. if (!event.GetCurrentElement()->HasAttribute("disabled"))
  415. {
  416. SetSelection(current_element);
  417. event.StopPropagation();
  418. ShowSelectBox(false);
  419. parent_element->Focus();
  420. }
  421. }
  422. }
  423. }
  424. else
  425. {
  426. // We have to check that this event isn't targeted to an element
  427. // inside the selection box as we'll get all events coming from our
  428. // root level select element as well as the ones coming from options (which
  429. // get caught in the above if)
  430. Element* element = event.GetTargetElement();
  431. while (element && element != parent_element)
  432. {
  433. if (element == selection_element)
  434. return;
  435. element = element->GetParentNode();
  436. }
  437. if (selection_element->GetComputedValues().visibility == Style::Visibility::Hidden)
  438. ShowSelectBox(true);
  439. else
  440. ShowSelectBox(false);
  441. }
  442. }
  443. break;
  444. case EventId::Focus:
  445. {
  446. if (event.GetTargetElement() == parent_element)
  447. {
  448. value_element->SetPseudoClass("focus", true);
  449. button_element->SetPseudoClass("focus", true);
  450. }
  451. }
  452. break;
  453. case EventId::Blur:
  454. {
  455. if (event.GetTargetElement() == parent_element)
  456. {
  457. ShowSelectBox(false);
  458. value_element->SetPseudoClass("focus", false);
  459. button_element->SetPseudoClass("focus", false);
  460. }
  461. }
  462. break;
  463. case EventId::Keydown:
  464. {
  465. Input::KeyIdentifier key_identifier = (Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0);
  466. switch (key_identifier)
  467. {
  468. case Input::KI_UP:
  469. SeekSelection(false);
  470. event.StopPropagation();
  471. break;
  472. case Input::KI_DOWN:
  473. SeekSelection(true);
  474. event.StopPropagation();
  475. break;
  476. case Input::KI_RETURN:
  477. case Input::KI_NUMPADENTER:
  478. parent_element->Click();
  479. event.StopPropagation();
  480. break;
  481. default:
  482. break;
  483. }
  484. }
  485. break;
  486. case EventId::Mousescroll:
  487. {
  488. if (event.GetCurrentElement() == selection_element)
  489. {
  490. // Prevent scrolling in the parent window when mouse is inside the selection box.
  491. event.StopPropagation();
  492. // Stopping propagation also stops all default scrolling actions. However, we still want to be able
  493. // to scroll in the selection box, so call the default action manually.
  494. selection_element->ProcessDefaultAction(event);
  495. }
  496. }
  497. break;
  498. case EventId::Scroll:
  499. {
  500. if (box_visible)
  501. {
  502. // Close the select box if we scroll outside the select box.
  503. bool scrolls_selection_box = false;
  504. for (Element* element = event.GetTargetElement(); element; element = element->GetParentNode())
  505. {
  506. if (element == selection_element)
  507. {
  508. scrolls_selection_box = true;
  509. break;
  510. }
  511. }
  512. if (!scrolls_selection_box)
  513. ShowSelectBox(false);
  514. }
  515. }
  516. break;
  517. default:
  518. break;
  519. }
  520. }
  521. // Shows or hides the selection box.
  522. void WidgetDropDown::ShowSelectBox(bool show)
  523. {
  524. if (show)
  525. {
  526. selection_element->SetProperty(PropertyId::Visibility, Property(Style::Visibility::Visible));
  527. value_element->SetPseudoClass("checked", true);
  528. button_element->SetPseudoClass("checked", true);
  529. box_layout_dirty = true;
  530. AttachScrollEvent();
  531. }
  532. else
  533. {
  534. selection_element->SetProperty(PropertyId::Visibility, Property(Style::Visibility::Hidden));
  535. selection_element->RemoveProperty(PropertyId::Height);
  536. value_element->SetPseudoClass("checked", false);
  537. button_element->SetPseudoClass("checked", false);
  538. DetachScrollEvent();
  539. }
  540. box_visible = show;
  541. }
  542. } // namespace Rml