ElementHandle.cpp 14 KB

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