ElementHandle.cpp 15 KB

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