ElementHandle.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 "ElementHandle.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/Event.h"
  34. #include "../../Include/RmlUi/Core/Property.h"
  35. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  36. #include "../../Include/RmlUi/Core/PropertyDictionary.h"
  37. #include "../../Include/RmlUi/Core/PropertySpecification.h"
  38. namespace Rml {
  39. class ElementHandleTargetData {
  40. public:
  41. enum { TOP, RIGHT, BOTTOM, LEFT, NUM_EDGES };
  42. using MoveData = ElementHandle::MoveData;
  43. using SizeData = ElementHandle::SizeData;
  44. ElementHandleTargetData(Element* target, Context* context, const Array<NumericValue, NUM_EDGES>& edge_margin) :
  45. target(target), computed(target->GetComputedValues()), box(target->GetBox()), parent_box(GetParentBox(target, context)),
  46. containing_block(target->GetContainingBlock()), position(computed.position()),
  47. resolved_edge_margin(ResolveEdgeMargin(target, box, edge_margin))
  48. {
  49. SetDefiniteMargins();
  50. }
  51. // The following table lists the expected behavior for each combination of definite (non-auto) properties:
  52. //
  53. // Definite properties | Move | Size
  54. // ---------------------|-------------------------|--------------------------
  55. // (none) | left += dx | width += dx
  56. // left | left += dx | width += dx
  57. // right | right -= dx | right -= dx; width += dx
  58. // width | left += dx | width += dx
  59. // left & right | left += dx; right -= dx | right -= dx
  60. // left & width | left += dx; | width += dx
  61. // right & width | right -= dx | right -= dx; width += dx
  62. // right & width | right -= dx | right -= dx; width += dx
  63. // left & right & width | left += dx; | width += dx
  64. //
  65. // For simplicity, this table only specifies the horizontal direction. The same behavior applies for the
  66. // corresponding properties in the vertical direction. For now, we assume that the handle is anchored to the
  67. // bottom-right corner of the target element.
  68. MoveData GetMoveData(Vector2f& drag_delta_min, Vector2f& drag_delta_max) const
  69. {
  70. using namespace Style;
  71. MoveData data = {};
  72. data.original_position_top_left = {GetPositionLeft(), GetPositionTop()};
  73. data.original_position_bottom_right = {GetPositionRight(), GetPositionBottom()};
  74. data.bottom_right.x = (computed.right().type != Right::Auto);
  75. data.bottom_right.y = (computed.bottom().type != Bottom::Auto);
  76. data.top_left.x = (!data.bottom_right.x || computed.left().type != Left::Auto);
  77. data.top_left.y = (!data.bottom_right.y || computed.top().type != Top::Auto);
  78. const Vector2f distance_to_top_left = DistanceToTopLeft();
  79. const Vector2f distance_to_bottom_right = DistanceToBottomRight(distance_to_top_left);
  80. drag_delta_min = Math::Max(drag_delta_min, Vector2f{resolved_edge_margin[LEFT], resolved_edge_margin[TOP]} - distance_to_top_left);
  81. drag_delta_max = Math::Min(drag_delta_max, Vector2f{-resolved_edge_margin[RIGHT], -resolved_edge_margin[BOTTOM]} + distance_to_bottom_right);
  82. return data;
  83. }
  84. SizeData GetSizeData(Vector2f& drag_delta_min, Vector2f& drag_delta_max) const
  85. {
  86. using namespace Style;
  87. SizeData data = {};
  88. data.original_size = box.GetSize(computed.box_sizing() == BoxSizing::BorderBox ? BoxArea::Border : BoxArea::Content);
  89. data.original_position_bottom_right = {GetPositionRight(), GetPositionBottom()};
  90. data.bottom_right.x = (computed.right().type != Right::Auto);
  91. data.bottom_right.y = (computed.bottom().type != Bottom::Auto);
  92. data.width_height.x = (computed.left().type == Left::Auto || computed.right().type == Right::Auto || computed.width().type != Width::Auto);
  93. data.width_height.y = (computed.top().type == Top::Auto || computed.bottom().type == Bottom::Auto || computed.height().type != Height::Auto);
  94. const Vector2f min_size = {
  95. ResolveValue(computed.min_width(), containing_block.x),
  96. ResolveValue(computed.min_height(), containing_block.y),
  97. };
  98. const Vector2f max_size = {
  99. ResolveValueOr(computed.max_width(), containing_block.x, FLT_MAX),
  100. ResolveValueOr(computed.max_height(), containing_block.y, FLT_MAX),
  101. };
  102. const Vector2f distance_to_bottom_right = DistanceToBottomRight(DistanceToTopLeft());
  103. drag_delta_min = Math::Max(drag_delta_min, min_size - data.original_size);
  104. drag_delta_max = Math::Min(drag_delta_max, max_size - data.original_size);
  105. drag_delta_max = Math::Min(drag_delta_max, Vector2f{-resolved_edge_margin[RIGHT], -resolved_edge_margin[BOTTOM]} + distance_to_bottom_right);
  106. return data;
  107. }
  108. private:
  109. void SetDefiniteMargins()
  110. {
  111. // Set any auto margins to their current value, since auto-margins may affect the size and position of an element.
  112. auto SetDefiniteMargin = [](Element* element, PropertyId margin_id, BoxEdge edge) {
  113. element->SetProperty(margin_id, Property(Math::Round(element->GetBox().GetEdge(BoxArea::Margin, edge)), Unit::PX));
  114. };
  115. using Style::Margin;
  116. if (computed.margin_top().type == Margin::Auto)
  117. SetDefiniteMargin(target, PropertyId::MarginTop, BoxEdge::Top);
  118. if (computed.margin_right().type == Margin::Auto)
  119. SetDefiniteMargin(target, PropertyId::MarginRight, BoxEdge::Right);
  120. if (computed.margin_bottom().type == Margin::Auto)
  121. SetDefiniteMargin(target, PropertyId::MarginBottom, BoxEdge::Bottom);
  122. if (computed.margin_left().type == Margin::Auto)
  123. SetDefiniteMargin(target, PropertyId::MarginLeft, BoxEdge::Left);
  124. }
  125. static Array<float, NUM_EDGES> ResolveEdgeMargin(Element* target, const Box& box, const Array<NumericValue, NUM_EDGES>& edge_margin)
  126. {
  127. const Vector2f target_size = box.GetSize(BoxArea::Border);
  128. Array<float, NUM_EDGES> resolved_edge_margin = {};
  129. for (int i = 0; i < NUM_EDGES; i++)
  130. {
  131. resolved_edge_margin[i] = (edge_margin[i].unit == Unit::UNKNOWN
  132. ? -FLT_MAX
  133. : Math::Round(target->ResolveNumericValue(edge_margin[i], target_size[(i == LEFT || i == RIGHT) ? 0 : 1])));
  134. }
  135. return resolved_edge_margin;
  136. }
  137. static const Box& GetParentBox(Element* target, Context* context)
  138. {
  139. return target->GetOffsetParent() ? target->GetOffsetParent()->GetBox() : context->GetRootElement()->GetBox();
  140. }
  141. template <typename Func>
  142. static float ResolveValueOrInvoke(const Style::LengthPercentageAuto& value, float containing_block, Style::Position position,
  143. Func&& fallback_func)
  144. {
  145. if (value.type != Style::LengthPercentageAuto::Auto)
  146. return ResolveValue(value, containing_block);
  147. if (position == Style::Position::Relative)
  148. return 0.0f;
  149. return fallback_func();
  150. }
  151. // The following is derived at by solving the expressions in 'Element::UpdateOffset' for the computed top/left/bottom/right values.
  152. float GetPositionTop() const
  153. {
  154. return ResolveValueOrInvoke(computed.top(), containing_block.y, position, [&] {
  155. return target->GetOffsetTop() - (box.GetEdge(BoxArea::Margin, BoxEdge::Top) + parent_box.GetEdge(BoxArea::Border, BoxEdge::Top));
  156. });
  157. }
  158. float GetPositionLeft() const
  159. {
  160. return ResolveValueOrInvoke(computed.left(), containing_block.x, position, [&] {
  161. return target->GetOffsetLeft() - (box.GetEdge(BoxArea::Margin, BoxEdge::Left) + parent_box.GetEdge(BoxArea::Border, BoxEdge::Left));
  162. });
  163. }
  164. float GetPositionBottom() const
  165. {
  166. return ResolveValueOrInvoke(computed.bottom(), containing_block.y, position, [&] {
  167. return containing_block.y + parent_box.GetEdge(BoxArea::Border, BoxEdge::Top) -
  168. (target->GetOffsetTop() + box.GetSize(BoxArea::Border).y + box.GetEdge(BoxArea::Margin, BoxEdge::Bottom));
  169. });
  170. }
  171. float GetPositionRight() const
  172. {
  173. return ResolveValueOrInvoke(computed.right(), containing_block.x, position, [&] {
  174. return containing_block.x + parent_box.GetEdge(BoxArea::Border, BoxEdge::Left) -
  175. (target->GetOffsetLeft() + box.GetSize(BoxArea::Border).x + box.GetEdge(BoxArea::Margin, BoxEdge::Right));
  176. });
  177. }
  178. Vector2f DistanceToTopLeft() const
  179. {
  180. return {target->GetOffsetLeft() - parent_box.GetEdge(BoxArea::Border, BoxEdge::Left),
  181. target->GetOffsetTop() - parent_box.GetEdge(BoxArea::Border, BoxEdge::Top)};
  182. }
  183. Vector2f DistanceToBottomRight(Vector2f distance_to_top_left) const
  184. {
  185. const Vector2f scroll_size = {target->GetParentNode()->GetScrollWidth(), target->GetParentNode()->GetScrollHeight()};
  186. return scroll_size - box.GetSize(BoxArea::Border) - distance_to_top_left;
  187. }
  188. Element* target;
  189. const ComputedValues& computed;
  190. const Box& box;
  191. const Box& parent_box;
  192. const Vector2f containing_block;
  193. const Style::Position position;
  194. const Array<float, NUM_EDGES> resolved_edge_margin;
  195. };
  196. class HandleEdgeMarginParser {
  197. private:
  198. PropertySpecification specification;
  199. Array<PropertyId, 4> ids;
  200. ShorthandId id_constraint;
  201. public:
  202. HandleEdgeMarginParser() : specification(4, 1)
  203. {
  204. ids = {
  205. specification.RegisterProperty("edge-t", "", false, false).AddParser("length_percent").GetId(),
  206. specification.RegisterProperty("edge-r", "", false, false).AddParser("length_percent").GetId(),
  207. specification.RegisterProperty("edge-b", "", false, false).AddParser("length_percent").GetId(),
  208. specification.RegisterProperty("edge-l", "", false, false).AddParser("length_percent").GetId(),
  209. };
  210. id_constraint = specification.RegisterShorthand("edge-margin", "edge-t, edge-r, edge-b, edge-l", ShorthandType::Box);
  211. }
  212. bool Parse(const String& value, Array<NumericValue, 4>& out_constraints)
  213. {
  214. PropertyDictionary properties;
  215. if (!specification.ParseShorthandDeclaration(properties, id_constraint, value))
  216. return false;
  217. out_constraints = {};
  218. for (int i = 0; i < 4; i++)
  219. {
  220. if (const Property* p = properties.GetProperty(ids[i]))
  221. out_constraints[i] = p->GetNumericValue();
  222. }
  223. return true;
  224. }
  225. };
  226. ElementHandle::ElementHandle(const String& tag) : Element(tag), drag_start(0, 0)
  227. {
  228. // Make sure we can be dragged!
  229. SetProperty(PropertyId::Drag, Property(Style::Drag::Drag));
  230. move_target = nullptr;
  231. size_target = nullptr;
  232. initialised = false;
  233. }
  234. ElementHandle::~ElementHandle() {}
  235. void ElementHandle::OnAttributeChange(const ElementAttributes& changed_attributes)
  236. {
  237. Element::OnAttributeChange(changed_attributes);
  238. // Reset initialised state if the move or size targets have changed.
  239. if (changed_attributes.find("move_target") != changed_attributes.end() || changed_attributes.find("size_target") != changed_attributes.end() ||
  240. changed_attributes.find("edge_margin") != changed_attributes.end())
  241. {
  242. initialised = false;
  243. move_target = nullptr;
  244. size_target = nullptr;
  245. }
  246. }
  247. void ElementHandle::ProcessDefaultAction(Event& event)
  248. {
  249. Element::ProcessDefaultAction(event);
  250. if (event.GetTargetElement() == this)
  251. {
  252. if (!initialised && GetOwnerDocument())
  253. {
  254. const String move_target_name = GetAttribute<String>("move_target", "");
  255. if (!move_target_name.empty())
  256. move_target = GetElementById(move_target_name);
  257. const String size_target_name = GetAttribute<String>("size_target", "");
  258. if (!size_target_name.empty())
  259. size_target = GetElementById(size_target_name);
  260. const String edge_margin_str = GetAttribute<String>("edge_margin", "0px");
  261. edge_margin = {};
  262. if (edge_margin_str != "none")
  263. {
  264. HandleEdgeMarginParser parser;
  265. if (!parser.Parse(edge_margin_str, edge_margin))
  266. Log::Message(Log::LT_WARNING, "Failed to parse 'edge_margin' attribute for element '%s'.", GetAddress().c_str());
  267. }
  268. initialised = true;
  269. }
  270. if (event == EventId::Dragstart)
  271. {
  272. using namespace Style;
  273. Context* context = GetContext();
  274. drag_start = event.GetUnprojectedMouseScreenPos();
  275. drag_delta_min = {-FLT_MAX, -FLT_MAX};
  276. drag_delta_max = {FLT_MAX, FLT_MAX};
  277. if (move_target && context)
  278. {
  279. ElementHandleTargetData move_target_data(move_target, context, edge_margin);
  280. move_data = move_target_data.GetMoveData(drag_delta_min, drag_delta_max);
  281. }
  282. if (size_target && context)
  283. {
  284. ElementHandleTargetData size_target_data(size_target, context, edge_margin);
  285. size_data = size_target_data.GetSizeData(drag_delta_min, drag_delta_max);
  286. }
  287. drag_delta_min = Math::Min(drag_delta_min, Vector2f{0, 0});
  288. drag_delta_max = Math::Max(drag_delta_max, Vector2f{0, 0});
  289. }
  290. else if (event == EventId::Drag)
  291. {
  292. const Vector2f delta = Math::Clamp(event.GetUnprojectedMouseScreenPos() - drag_start, drag_delta_min, drag_delta_max);
  293. if (move_target)
  294. {
  295. const Vector2f new_position_top_left = (move_data.original_position_top_left + delta).Round();
  296. const Vector2f new_position_bottom_right = (move_data.original_position_bottom_right - delta).Round();
  297. if (move_data.top_left.x)
  298. move_target->SetProperty(PropertyId::Left, Property(new_position_top_left.x, Unit::PX));
  299. if (move_data.top_left.y)
  300. move_target->SetProperty(PropertyId::Top, Property(new_position_top_left.y, Unit::PX));
  301. if (move_data.bottom_right.x)
  302. move_target->SetProperty(PropertyId::Right, Property(new_position_bottom_right.x, Unit::PX));
  303. if (move_data.bottom_right.y)
  304. move_target->SetProperty(PropertyId::Bottom, Property(new_position_bottom_right.y, Unit::PX));
  305. }
  306. if (size_target)
  307. {
  308. const Vector2f new_size = Math::Max((size_data.original_size + delta).Round(), Vector2f(0.f));
  309. const Vector2f new_position_bottom_right = (size_data.original_position_bottom_right - delta).Round();
  310. if (size_data.width_height.x)
  311. size_target->SetProperty(PropertyId::Width, Property(new_size.x, Unit::PX));
  312. if (size_data.width_height.y)
  313. size_target->SetProperty(PropertyId::Height, Property(new_size.y, Unit::PX));
  314. if (size_data.bottom_right.x)
  315. size_target->SetProperty(PropertyId::Right, Property(new_position_bottom_right.x, Unit::PX));
  316. if (size_data.bottom_right.y)
  317. size_target->SetProperty(PropertyId::Bottom, Property(new_position_bottom_right.y, Unit::PX));
  318. }
  319. Dictionary parameters;
  320. parameters["handle_x"] = delta.x;
  321. parameters["handle_y"] = delta.y;
  322. DispatchEvent(EventId::Handledrag, parameters);
  323. }
  324. }
  325. }
  326. } // namespace Rml