WidgetDropDown.cpp 17 KB

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