WidgetDropDown.cpp 19 KB

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