WidgetDropDown.cpp 20 KB

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