WidgetDropDown.cpp 19 KB

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