Element.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562
  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 "precompiled.h"
  29. #include "../../Include/RmlUi/Core/Element.h"
  30. #include "../../Include/RmlUi/Core/Dictionary.h"
  31. #include "../../Include/RmlUi/Core/PropertyIdSet.h"
  32. #include "../../Include/RmlUi/Core/TransformPrimitive.h"
  33. #include "../../Include/RmlUi/Core/TransformState.h"
  34. #include <algorithm>
  35. #include <limits>
  36. #include "Clock.h"
  37. #include "ComputeProperty.h"
  38. #include "ElementAnimation.h"
  39. #include "ElementBackground.h"
  40. #include "ElementBorder.h"
  41. #include "ElementDefinition.h"
  42. #include "ElementStyle.h"
  43. #include "EventDispatcher.h"
  44. #include "EventSpecification.h"
  45. #include "ElementDecoration.h"
  46. #include "LayoutEngine.h"
  47. #include "PluginRegistry.h"
  48. #include "PropertiesIterator.h"
  49. #include "Pool.h"
  50. #include "StyleSheetParser.h"
  51. #include "XMLParseTools.h"
  52. #include "../../Include/RmlUi/Core/Core.h"
  53. namespace Rml {
  54. namespace Core {
  55. /**
  56. STL function object for sorting elements by z-type (ie, float-types before general types, etc).
  57. @author Peter Curry
  58. */
  59. class ElementSortZOrder
  60. {
  61. public:
  62. bool operator()(const std::pair< Element*, float >& lhs, const std::pair< Element*, float >& rhs) const
  63. {
  64. return lhs.second < rhs.second;
  65. }
  66. };
  67. /**
  68. STL function object for sorting elements by z-index property.
  69. @author Peter Curry
  70. */
  71. class ElementSortZIndex
  72. {
  73. public:
  74. bool operator()(const Element* lhs, const Element* rhs) const
  75. {
  76. // Check the z-index.
  77. return lhs->GetZIndex() < rhs->GetZIndex();
  78. }
  79. };
  80. // Determines how many levels up in the hierarchy the OnChildAdd and OnChildRemove are called (starting at the child itself)
  81. static constexpr int ChildNotifyLevels = 2;
  82. // Meta objects for element collected in a single struct to reduce memory allocations
  83. struct ElementMeta
  84. {
  85. ElementMeta(Element* el) : event_dispatcher(el), style(el), background(el), border(el), decoration(el), scroll(el) {}
  86. EventDispatcher event_dispatcher;
  87. ElementStyle style;
  88. ElementBackground background;
  89. ElementBorder border;
  90. ElementDecoration decoration;
  91. ElementScroll scroll;
  92. Style::ComputedValues computed_values;
  93. };
  94. static Pool< ElementMeta > element_meta_chunk_pool(200, true);
  95. /// Constructs a new RmlUi element.
  96. Element::Element(const String& tag) : tag(tag), relative_offset_base(0, 0), relative_offset_position(0, 0), absolute_offset(0, 0), scroll_offset(0, 0), content_offset(0, 0), content_box(0, 0),
  97. transform_state(), dirty_transform(false), dirty_perspective(false), dirty_animation(false), dirty_transition(false),
  98. EnableObserverPtr<Element>()
  99. {
  100. RMLUI_ASSERT(tag == StringUtilities::ToLower(tag));
  101. parent = nullptr;
  102. focus = nullptr;
  103. instancer = nullptr;
  104. owner_document = nullptr;
  105. offset_fixed = false;
  106. offset_parent = nullptr;
  107. offset_dirty = true;
  108. client_area = Box::PADDING;
  109. num_non_dom_children = 0;
  110. visible = true;
  111. z_index = 0;
  112. local_stacking_context = false;
  113. local_stacking_context_forced = false;
  114. stacking_context_dirty = false;
  115. structure_dirty = false;
  116. computed_values_are_default_initialized = true;
  117. clipping_ignore_depth = 0;
  118. clipping_enabled = false;
  119. clipping_state_dirty = true;
  120. element_meta = element_meta_chunk_pool.AllocateAndConstruct(this);
  121. event_dispatcher = &element_meta->event_dispatcher;
  122. style = &element_meta->style;
  123. background = &element_meta->background;
  124. border = &element_meta->border;
  125. decoration = &element_meta->decoration;
  126. scroll = &element_meta->scroll;
  127. }
  128. Element::~Element()
  129. {
  130. RMLUI_ASSERT(parent == nullptr);
  131. PluginRegistry::NotifyElementDestroy(this);
  132. // Remove scrollbar elements before we delete the children!
  133. scroll->ClearScrollbars();
  134. // A simplified version of RemoveChild() for destruction.
  135. for (ElementPtr& child : children)
  136. {
  137. Element* child_ancestor = child.get();
  138. for (int i = 0; i <= ChildNotifyLevels && child_ancestor; i++, child_ancestor = child_ancestor->GetParentNode())
  139. child_ancestor->OnChildRemove(child.get());
  140. child->SetParent(nullptr);
  141. }
  142. children.clear();
  143. num_non_dom_children = 0;
  144. element_meta_chunk_pool.DestroyAndDeallocate(element_meta);
  145. }
  146. void Element::Update(float dp_ratio)
  147. {
  148. RMLUI_ZoneScoped;
  149. OnUpdate();
  150. UpdateStructure();
  151. UpdateTransition();
  152. UpdateAnimation();
  153. AdvanceAnimations();
  154. scroll->Update();
  155. UpdateProperties();
  156. for (size_t i = 0; i < children.size(); i++)
  157. children[i]->Update(dp_ratio);
  158. }
  159. void Element::UpdateProperties()
  160. {
  161. style->UpdateDefinition();
  162. if (style->AnyPropertiesDirty())
  163. {
  164. const ComputedValues* parent_values = nullptr;
  165. if (parent)
  166. parent_values = &parent->GetComputedValues();
  167. const ComputedValues* document_values = nullptr;
  168. float dp_ratio = 1.0f;
  169. if (auto doc = GetOwnerDocument())
  170. {
  171. document_values = &doc->GetComputedValues();
  172. if (Context * context = doc->GetContext())
  173. dp_ratio = context->GetDensityIndependentPixelRatio();
  174. }
  175. // Compute values and clear dirty properties
  176. PropertyIdSet dirty_properties = style->ComputeValues(element_meta->computed_values, parent_values, document_values, computed_values_are_default_initialized, dp_ratio);
  177. computed_values_are_default_initialized = false;
  178. // Computed values are just calculated and can safely be used in OnPropertyChange.
  179. // However, new properties set during this call will not be available until the next update loop.
  180. if (!dirty_properties.Empty())
  181. OnPropertyChange(dirty_properties);
  182. }
  183. }
  184. void Element::Render()
  185. {
  186. #ifdef RMLUI_ENABLE_PROFILING
  187. auto name = GetAddress(false, false);
  188. RMLUI_ZoneScoped;
  189. RMLUI_ZoneText(name.c_str(), name.size());
  190. #endif
  191. // Rebuild our stacking context if necessary.
  192. if (stacking_context_dirty)
  193. BuildLocalStackingContext();
  194. UpdateTransformState();
  195. // Apply our transform
  196. ElementUtilities::ApplyTransform(*this);
  197. // Render all elements in our local stacking context that have a z-index beneath our local index of 0.
  198. size_t i = 0;
  199. for (; i < stacking_context.size() && stacking_context[i]->z_index < 0; ++i)
  200. stacking_context[i]->Render();
  201. // Set up the clipping region for this element.
  202. if (ElementUtilities::SetClippingRegion(this))
  203. {
  204. background->RenderBackground();
  205. border->RenderBorder();
  206. decoration->RenderDecorators();
  207. {
  208. RMLUI_ZoneScopedNC("OnRender", 0x228B22);
  209. OnRender();
  210. }
  211. }
  212. // Render the rest of the elements in the stacking context.
  213. for (; i < stacking_context.size(); ++i)
  214. stacking_context[i]->Render();
  215. }
  216. // Clones this element, returning a new, unparented element.
  217. ElementPtr Element::Clone() const
  218. {
  219. ElementPtr clone;
  220. if (instancer)
  221. {
  222. clone = instancer->InstanceElement(nullptr, GetTagName(), attributes);
  223. if (clone)
  224. clone->SetInstancer(instancer);
  225. }
  226. else
  227. clone = Factory::InstanceElement(nullptr, GetTagName(), GetTagName(), attributes);
  228. if (clone != nullptr)
  229. {
  230. String inner_rml;
  231. GetInnerRML(inner_rml);
  232. clone->SetInnerRML(inner_rml);
  233. }
  234. return clone;
  235. }
  236. // Sets or removes a class on the element.
  237. void Element::SetClass(const String& class_name, bool activate)
  238. {
  239. style->SetClass(class_name, activate);
  240. }
  241. // Checks if a class is set on the element.
  242. bool Element::IsClassSet(const String& class_name) const
  243. {
  244. return style->IsClassSet(class_name);
  245. }
  246. // Specifies the entire list of classes for this element. This will replace any others specified.
  247. void Element::SetClassNames(const String& class_names)
  248. {
  249. SetAttribute("class", class_names);
  250. }
  251. /// Return the active class list
  252. String Element::GetClassNames() const
  253. {
  254. return style->GetClassNames();
  255. }
  256. // Returns the active style sheet for this element. This may be nullptr.
  257. const SharedPtr<StyleSheet>& Element::GetStyleSheet() const
  258. {
  259. if (ElementDocument * document = GetOwnerDocument())
  260. return document->GetStyleSheet();
  261. static SharedPtr<StyleSheet> null_style_sheet;
  262. return null_style_sheet;
  263. }
  264. // Returns the element's definition.
  265. const ElementDefinition* Element::GetDefinition()
  266. {
  267. return style->GetDefinition();
  268. }
  269. // Fills an String with the full address of this element.
  270. String Element::GetAddress(bool include_pseudo_classes, bool include_parents) const
  271. {
  272. // Add the tag name onto the address.
  273. String address(tag);
  274. // Add the ID if we have one.
  275. if (!id.empty())
  276. {
  277. address += "#";
  278. address += id;
  279. }
  280. String classes = style->GetClassNames();
  281. if (!classes.empty())
  282. {
  283. classes = StringUtilities::Replace(classes, ' ', '.');
  284. address += ".";
  285. address += classes;
  286. }
  287. if (include_pseudo_classes)
  288. {
  289. const PseudoClassList& pseudo_classes = style->GetActivePseudoClasses();
  290. for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
  291. {
  292. address += ":";
  293. address += (*i);
  294. }
  295. }
  296. if (include_parents && parent)
  297. {
  298. address += " < ";
  299. return address + parent->GetAddress(include_pseudo_classes, true);
  300. }
  301. else
  302. return address;
  303. }
  304. // Sets the position of this element, as a two-dimensional offset from another element.
  305. void Element::SetOffset(const Vector2f& offset, Element* _offset_parent, bool _offset_fixed)
  306. {
  307. _offset_fixed |= GetPosition() == Style::Position::Fixed;
  308. // If our offset has definitely changed, or any of our parenting has, then these are set and
  309. // updated based on our left / right / top / bottom properties.
  310. if (relative_offset_base != offset ||
  311. offset_parent != _offset_parent ||
  312. offset_fixed != _offset_fixed)
  313. {
  314. relative_offset_base = offset;
  315. offset_fixed = _offset_fixed;
  316. offset_parent = _offset_parent;
  317. UpdateOffset();
  318. DirtyOffset();
  319. }
  320. // Otherwise, our offset is updated in case left / right / top / bottom will have an impact on
  321. // our final position, and our children are dirtied if they do.
  322. else
  323. {
  324. Vector2f& old_base = relative_offset_base;
  325. Vector2f& old_position = relative_offset_position;
  326. UpdateOffset();
  327. if (old_base != relative_offset_base ||
  328. old_position != relative_offset_position)
  329. DirtyOffset();
  330. }
  331. }
  332. // Returns the position of the top-left corner of one of the areas of this element's primary box.
  333. Vector2f Element::GetRelativeOffset(Box::Area area)
  334. {
  335. return relative_offset_base + relative_offset_position + GetBox().GetPosition(area);
  336. }
  337. // Returns the position of the top-left corner of one of the areas of this element's primary box.
  338. Vector2f Element::GetAbsoluteOffset(Box::Area area)
  339. {
  340. if (offset_dirty)
  341. {
  342. offset_dirty = false;
  343. if (offset_parent != nullptr)
  344. absolute_offset = offset_parent->GetAbsoluteOffset(Box::BORDER) + relative_offset_base + relative_offset_position;
  345. else
  346. absolute_offset = relative_offset_base + relative_offset_position;
  347. // Add any parent scrolling onto our position as well. Could cache this if required.
  348. if (!offset_fixed)
  349. {
  350. Element* scroll_parent = parent;
  351. while (scroll_parent != nullptr)
  352. {
  353. absolute_offset -= (scroll_parent->scroll_offset + scroll_parent->content_offset);
  354. if (scroll_parent == offset_parent)
  355. break;
  356. else
  357. scroll_parent = scroll_parent->parent;
  358. }
  359. }
  360. }
  361. return absolute_offset + GetBox().GetPosition(area);
  362. }
  363. // Sets an alternate area to use as the client area.
  364. void Element::SetClientArea(Box::Area _client_area)
  365. {
  366. client_area = _client_area;
  367. }
  368. // Returns the area the element uses as its client area.
  369. Box::Area Element::GetClientArea() const
  370. {
  371. return client_area;
  372. }
  373. // Sets the dimensions of the element's internal content.
  374. void Element::SetContentBox(const Vector2f& _content_offset, const Vector2f& _content_box)
  375. {
  376. if (content_offset != _content_offset ||
  377. content_box != _content_box)
  378. {
  379. // Seems to be jittering a wee bit; might need to be looked at.
  380. scroll_offset.x += (content_offset.x - _content_offset.x);
  381. scroll_offset.y += (content_offset.y - _content_offset.y);
  382. content_offset = _content_offset;
  383. content_box = _content_box;
  384. scroll_offset.x = Math::Min(scroll_offset.x, GetScrollWidth() - GetClientWidth());
  385. scroll_offset.y = Math::Min(scroll_offset.y, GetScrollHeight() - GetClientHeight());
  386. DirtyOffset();
  387. }
  388. }
  389. // Sets the box describing the size of the element.
  390. void Element::SetBox(const Box& box)
  391. {
  392. if (box != main_box || additional_boxes.size() > 0)
  393. {
  394. main_box = box;
  395. additional_boxes.clear();
  396. OnResize();
  397. background->DirtyBackground();
  398. border->DirtyBorder();
  399. decoration->DirtyDecorators();
  400. }
  401. }
  402. // Adds a box to the end of the list describing this element's geometry.
  403. void Element::AddBox(const Box& box)
  404. {
  405. additional_boxes.push_back(box);
  406. OnResize();
  407. background->DirtyBackground();
  408. border->DirtyBorder();
  409. decoration->DirtyDecorators();
  410. }
  411. // Returns one of the boxes describing the size of the element.
  412. const Box& Element::GetBox()
  413. {
  414. return main_box;
  415. }
  416. // Returns one of the boxes describing the size of the element.
  417. const Box& Element::GetBox(int index)
  418. {
  419. if (index < 1)
  420. return main_box;
  421. int additional_box_index = index - 1;
  422. if (additional_box_index >= (int)additional_boxes.size())
  423. return main_box;
  424. return additional_boxes[additional_box_index];
  425. }
  426. // Returns the number of boxes making up this element's geometry.
  427. int Element::GetNumBoxes()
  428. {
  429. return 1 + (int)additional_boxes.size();
  430. }
  431. // Returns the baseline of the element, in pixels offset from the bottom of the element's content area.
  432. float Element::GetBaseline() const
  433. {
  434. return 0;
  435. }
  436. // Gets the intrinsic dimensions of this element, if it is of a type that has an inherent size.
  437. bool Element::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions))
  438. {
  439. RMLUI_UNUSED(dimensions);
  440. return false;
  441. }
  442. // Checks if a given point in screen coordinates lies within the bordered area of this element.
  443. bool Element::IsPointWithinElement(const Vector2f& point)
  444. {
  445. Vector2f position = GetAbsoluteOffset(Box::BORDER);
  446. for (int i = 0; i < GetNumBoxes(); ++i)
  447. {
  448. const Box& box = GetBox(i);
  449. Vector2f box_position = position + box.GetOffset();
  450. Vector2f box_dimensions = box.GetSize(Box::BORDER);
  451. if (point.x >= box_position.x &&
  452. point.x <= (box_position.x + box_dimensions.x) &&
  453. point.y >= box_position.y &&
  454. point.y <= (box_position.y + box_dimensions.y))
  455. {
  456. return true;
  457. }
  458. }
  459. return false;
  460. }
  461. // Returns the visibility of the element.
  462. bool Element::IsVisible() const
  463. {
  464. return visible;
  465. }
  466. // Returns the z-index of the element.
  467. float Element::GetZIndex() const
  468. {
  469. return z_index;
  470. }
  471. // Returns the element's font face handle.
  472. FontFaceHandle Element::GetFontFaceHandle() const
  473. {
  474. return element_meta->computed_values.font_face_handle;
  475. }
  476. // Sets a local property override on the element.
  477. bool Element::SetProperty(const String& name, const String& value)
  478. {
  479. // The name may be a shorthand giving us multiple underlying properties
  480. PropertyDictionary properties;
  481. if (!StyleSheetSpecification::ParsePropertyDeclaration(properties, name, value))
  482. {
  483. Log::Message(Log::LT_WARNING, "Syntax error parsing inline property declaration '%s: %s;'.", name.c_str(), value.c_str());
  484. return false;
  485. }
  486. for (auto& property : properties.GetProperties())
  487. {
  488. if (!style->SetProperty(property.first, property.second))
  489. return false;
  490. }
  491. return true;
  492. }
  493. // Sets a local property override on the element to a pre-parsed value.
  494. bool Element::SetProperty(PropertyId id, const Property& property)
  495. {
  496. return style->SetProperty(id, property);
  497. }
  498. // Removes a local property override on the element.
  499. void Element::RemoveProperty(const String& name)
  500. {
  501. style->RemoveProperty(StyleSheetSpecification::GetPropertyId(name));
  502. }
  503. // Removes a local property override on the element.
  504. void Element::RemoveProperty(PropertyId id)
  505. {
  506. style->RemoveProperty(id);
  507. }
  508. // Returns one of this element's properties.
  509. const Property* Element::GetProperty(const String& name)
  510. {
  511. return style->GetProperty(StyleSheetSpecification::GetPropertyId(name));
  512. }
  513. // Returns one of this element's properties.
  514. const Property* Element::GetProperty(PropertyId id)
  515. {
  516. return style->GetProperty(id);
  517. }
  518. // Returns one of this element's properties.
  519. const Property* Element::GetLocalProperty(const String& name)
  520. {
  521. return style->GetLocalProperty(StyleSheetSpecification::GetPropertyId(name));
  522. }
  523. const Property* Element::GetLocalProperty(PropertyId id)
  524. {
  525. return style->GetLocalProperty(id);
  526. }
  527. const PropertyMap& Element::GetLocalStyleProperties()
  528. {
  529. return style->GetLocalStyleProperties();
  530. }
  531. float Element::ResolveNumericProperty(const Property *property, float base_value)
  532. {
  533. return style->ResolveNumericProperty(property, base_value);
  534. }
  535. float Element::ResolveNumericProperty(const String& property_name)
  536. {
  537. auto property = style->GetProperty(StyleSheetSpecification::GetPropertyId(property_name));
  538. if (!property)
  539. return 0.0f;
  540. if (property->unit & Property::ANGLE)
  541. return ComputeAngle(*property);
  542. RelativeTarget relative_target = RelativeTarget::None;
  543. if (property->definition)
  544. relative_target = property->definition->GetRelativeTarget();
  545. float result = style->ResolveLength(property, relative_target);
  546. return result;
  547. }
  548. Vector2f Element::GetContainingBlock()
  549. {
  550. Vector2f containing_block(0, 0);
  551. if (offset_parent != nullptr)
  552. {
  553. using namespace Style;
  554. Position position_property = GetPosition();
  555. const Box& parent_box = offset_parent->GetBox();
  556. if (position_property == Position::Static || position_property == Position::Relative)
  557. {
  558. containing_block = parent_box.GetSize();
  559. }
  560. else if(position_property == Position::Absolute || position_property == Position::Fixed)
  561. {
  562. containing_block = parent_box.GetSize(Box::PADDING);
  563. }
  564. }
  565. return containing_block;
  566. }
  567. Style::Position Element::GetPosition()
  568. {
  569. return element_meta->computed_values.position;
  570. }
  571. Style::Float Element::GetFloat()
  572. {
  573. return element_meta->computed_values.float_;
  574. }
  575. Style::Display Element::GetDisplay()
  576. {
  577. return element_meta->computed_values.display;
  578. }
  579. float Element::GetLineHeight()
  580. {
  581. return element_meta->computed_values.line_height.value;
  582. }
  583. // Returns this element's TransformState
  584. const TransformState *Element::GetTransformState() const noexcept
  585. {
  586. return transform_state.get();
  587. }
  588. // Project a 2D point in pixel coordinates onto the element's plane.
  589. bool Element::Project(Vector2f& point) const noexcept
  590. {
  591. if(!transform_state || !transform_state->GetTransform())
  592. return true;
  593. // The input point is in window coordinates. Need to find the projection of the point onto the current element plane,
  594. // taking into account the full transform applied to the element.
  595. if (const Matrix4f* inv_transform = transform_state->GetInverseTransform())
  596. {
  597. // Pick two points forming a line segment perpendicular to the window.
  598. Vector4f window_points[2] = {{ point.x, point.y, -10, 1}, { point.x, point.y, 10, 1 }};
  599. // Project them into the local element space.
  600. window_points[0] = *inv_transform * window_points[0];
  601. window_points[1] = *inv_transform * window_points[1];
  602. Vector3f local_points[2] = {
  603. window_points[0].PerspectiveDivide(),
  604. window_points[1].PerspectiveDivide()
  605. };
  606. // Construct a ray from the two projected points in the local space of the current element.
  607. // Find the intersection with the z=0 plane to produce our destination point.
  608. Vector3f ray = local_points[1] - local_points[0];
  609. // Only continue if we are not close to parallel with the plane.
  610. if(std::abs(ray.z) > 1.0f)
  611. {
  612. // Solving the line equation p = p0 + t*ray for t, knowing that p.z = 0, produces the following.
  613. float t = -local_points[0].z / ray.z;
  614. Vector3f p = local_points[0] + ray * t;
  615. point = Vector2f(p.x, p.y);
  616. return true;
  617. }
  618. }
  619. // The transformation matrix is either singular, or the ray is parallel to the element's plane.
  620. return false;
  621. }
  622. PropertiesIteratorView Element::IterateLocalProperties() const
  623. {
  624. return PropertiesIteratorView(std::make_unique<PropertiesIterator>(style->Iterate()));
  625. }
  626. // Sets or removes a pseudo-class on the element.
  627. void Element::SetPseudoClass(const String& pseudo_class, bool activate)
  628. {
  629. style->SetPseudoClass(pseudo_class, activate);
  630. }
  631. // Checks if a specific pseudo-class has been set on the element.
  632. bool Element::IsPseudoClassSet(const String& pseudo_class) const
  633. {
  634. return style->IsPseudoClassSet(pseudo_class);
  635. }
  636. // Checks if a complete set of pseudo-classes are set on the element.
  637. bool Element::ArePseudoClassesSet(const PseudoClassList& pseudo_classes) const
  638. {
  639. for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
  640. {
  641. if (!IsPseudoClassSet(*i))
  642. return false;
  643. }
  644. return true;
  645. }
  646. // Gets a list of the current active pseudo classes
  647. const PseudoClassList& Element::GetActivePseudoClasses() const
  648. {
  649. return style->GetActivePseudoClasses();
  650. }
  651. /// Get the named attribute
  652. Variant* Element::GetAttribute(const String& name)
  653. {
  654. return GetIf(attributes, name);
  655. }
  656. // Checks if the element has a certain attribute.
  657. bool Element::HasAttribute(const String& name) const
  658. {
  659. return attributes.find(name) != attributes.end();
  660. }
  661. // Removes an attribute from the element
  662. void Element::RemoveAttribute(const String& name)
  663. {
  664. auto it = attributes.find(name);
  665. if (it != attributes.end())
  666. {
  667. attributes.erase(it);
  668. ElementAttributes changed_attributes;
  669. changed_attributes.emplace(name, Variant());
  670. OnAttributeChange(changed_attributes);
  671. }
  672. }
  673. // Gets the outer most focus element down the tree from this node
  674. Element* Element::GetFocusLeafNode()
  675. {
  676. // If there isn't a focus, then we are the leaf.
  677. if (!focus)
  678. {
  679. return this;
  680. }
  681. // Recurse down the tree until we found the leaf focus element
  682. Element* focus_element = focus;
  683. while (focus_element->focus)
  684. focus_element = focus_element->focus;
  685. return focus_element;
  686. }
  687. // Returns the element's context.
  688. Context* Element::GetContext() const
  689. {
  690. ElementDocument* document = GetOwnerDocument();
  691. if (document != nullptr)
  692. return document->GetContext();
  693. return nullptr;
  694. }
  695. // Set a group of attributes
  696. void Element::SetAttributes(const ElementAttributes& _attributes)
  697. {
  698. attributes.reserve(attributes.size() + _attributes.size());
  699. for (auto& pair : _attributes)
  700. attributes[pair.first] = pair.second;
  701. OnAttributeChange(_attributes);
  702. }
  703. // Returns the number of attributes on the element.
  704. int Element::GetNumAttributes() const
  705. {
  706. return (int)attributes.size();
  707. }
  708. // Gets the name of the element.
  709. const String& Element::GetTagName() const
  710. {
  711. return tag;
  712. }
  713. // Gets the ID of the element.
  714. const String& Element::GetId() const
  715. {
  716. return id;
  717. }
  718. // Sets the ID of the element.
  719. void Element::SetId(const String& _id)
  720. {
  721. SetAttribute("id", _id);
  722. }
  723. // Gets the horizontal offset from the context's left edge to element's left border edge.
  724. float Element::GetAbsoluteLeft()
  725. {
  726. return GetAbsoluteOffset(Box::BORDER).x;
  727. }
  728. // Gets the vertical offset from the context's top edge to element's top border edge.
  729. float Element::GetAbsoluteTop()
  730. {
  731. return GetAbsoluteOffset(Box::BORDER).y;
  732. }
  733. // Gets the width of the left border of an element.
  734. float Element::GetClientLeft()
  735. {
  736. return GetBox().GetPosition(client_area).x;
  737. }
  738. // Gets the height of the top border of an element.
  739. float Element::GetClientTop()
  740. {
  741. return GetBox().GetPosition(client_area).y;
  742. }
  743. // Gets the inner width of the element.
  744. float Element::GetClientWidth()
  745. {
  746. return GetBox().GetSize(client_area).x - scroll->GetScrollbarSize(ElementScroll::VERTICAL);
  747. }
  748. // Gets the inner height of the element.
  749. float Element::GetClientHeight()
  750. {
  751. return GetBox().GetSize(client_area).y - scroll->GetScrollbarSize(ElementScroll::HORIZONTAL);
  752. }
  753. // Returns the element from which all offset calculations are currently computed.
  754. Element* Element::GetOffsetParent()
  755. {
  756. return offset_parent;
  757. }
  758. // Gets the distance from this element's left border to its offset parent's left border.
  759. float Element::GetOffsetLeft()
  760. {
  761. return relative_offset_base.x + relative_offset_position.x;
  762. }
  763. // Gets the distance from this element's top border to its offset parent's top border.
  764. float Element::GetOffsetTop()
  765. {
  766. return relative_offset_base.y + relative_offset_position.y;
  767. }
  768. // Gets the width of the element, including the client area, padding, borders and scrollbars, but not margins.
  769. float Element::GetOffsetWidth()
  770. {
  771. return GetBox().GetSize(Box::BORDER).x;
  772. }
  773. // Gets the height of the element, including the client area, padding, borders and scrollbars, but not margins.
  774. float Element::GetOffsetHeight()
  775. {
  776. return GetBox().GetSize(Box::BORDER).y;
  777. }
  778. // Gets the left scroll offset of the element.
  779. float Element::GetScrollLeft()
  780. {
  781. return scroll_offset.x;
  782. }
  783. // Sets the left scroll offset of the element.
  784. void Element::SetScrollLeft(float scroll_left)
  785. {
  786. const float new_offset = Math::Clamp(scroll_left, 0.0f, GetScrollWidth() - GetClientWidth());
  787. if (new_offset != scroll_offset.x)
  788. {
  789. scroll_offset.x = new_offset;
  790. scroll->UpdateScrollbar(ElementScroll::HORIZONTAL);
  791. DirtyOffset();
  792. DispatchEvent(EventId::Scroll, Dictionary());
  793. }
  794. }
  795. // Gets the top scroll offset of the element.
  796. float Element::GetScrollTop()
  797. {
  798. return scroll_offset.y;
  799. }
  800. // Sets the top scroll offset of the element.
  801. void Element::SetScrollTop(float scroll_top)
  802. {
  803. const float new_offset = Math::Clamp(scroll_top, 0.0f, GetScrollHeight() - GetClientHeight());
  804. if(new_offset != scroll_offset.y)
  805. {
  806. scroll_offset.y = new_offset;
  807. scroll->UpdateScrollbar(ElementScroll::VERTICAL);
  808. DirtyOffset();
  809. DispatchEvent(EventId::Scroll, Dictionary());
  810. }
  811. }
  812. // Gets the width of the scrollable content of the element; it includes the element padding but not its margin.
  813. float Element::GetScrollWidth()
  814. {
  815. return Math::Max(content_box.x, GetClientWidth());
  816. }
  817. // Gets the height of the scrollable content of the element; it includes the element padding but not its margin.
  818. float Element::GetScrollHeight()
  819. {
  820. return Math::Max(content_box.y, GetClientHeight());
  821. }
  822. // Gets the object representing the declarations of an element's style attributes.
  823. ElementStyle* Element::GetStyle() const
  824. {
  825. return style;
  826. }
  827. // Gets the document this element belongs to.
  828. ElementDocument* Element::GetOwnerDocument() const
  829. {
  830. #ifdef RMLUI_DEBUG
  831. if (parent && !owner_document)
  832. {
  833. // Since we have a parent but no owner_document, then we must be a 'loose' element -- that is, constructed
  834. // outside of a document and not attached to a child of any element in the hierarchy of a document.
  835. // This check ensures that we didn't just forget to set the owner document.
  836. RMLUI_ASSERT(!parent->GetOwnerDocument());
  837. }
  838. #endif
  839. return owner_document;
  840. }
  841. // Gets this element's parent node.
  842. Element* Element::GetParentNode() const
  843. {
  844. return parent;
  845. }
  846. // Gets the element immediately following this one in the tree.
  847. Element* Element::GetNextSibling() const
  848. {
  849. if (parent == nullptr)
  850. return nullptr;
  851. for (size_t i = 0; i < parent->children.size() - (parent->num_non_dom_children + 1); i++)
  852. {
  853. if (parent->children[i].get() == this)
  854. return parent->children[i + 1].get();
  855. }
  856. return nullptr;
  857. }
  858. // Gets the element immediately preceding this one in the tree.
  859. Element* Element::GetPreviousSibling() const
  860. {
  861. if (parent == nullptr)
  862. return nullptr;
  863. for (size_t i = 1; i < parent->children.size() - parent->num_non_dom_children; i++)
  864. {
  865. if (parent->children[i].get() == this)
  866. return parent->children[i - 1].get();
  867. }
  868. return nullptr;
  869. }
  870. // Returns the first child of this element.
  871. Element* Element::GetFirstChild() const
  872. {
  873. if (GetNumChildren() > 0)
  874. return children[0].get();
  875. return nullptr;
  876. }
  877. // Gets the last child of this element.
  878. Element* Element::GetLastChild() const
  879. {
  880. if (GetNumChildren() > 0)
  881. return (children.end() - (num_non_dom_children + 1))->get();
  882. return nullptr;
  883. }
  884. Element* Element::GetChild(int index) const
  885. {
  886. if (index < 0 || index >= (int) children.size())
  887. return nullptr;
  888. return children[index].get();
  889. }
  890. int Element::GetNumChildren(bool include_non_dom_elements) const
  891. {
  892. return (int) children.size() - (include_non_dom_elements ? 0 : num_non_dom_children);
  893. }
  894. // Gets the markup and content of the element.
  895. void Element::GetInnerRML(String& content) const
  896. {
  897. for (int i = 0; i < GetNumChildren(); i++)
  898. {
  899. children[i]->GetRML(content);
  900. }
  901. }
  902. // Gets the markup and content of the element.
  903. String Element::GetInnerRML() const {
  904. String result;
  905. GetInnerRML(result);
  906. return result;
  907. }
  908. // Sets the markup and content of the element. All existing children will be replaced.
  909. void Element::SetInnerRML(const String& rml)
  910. {
  911. RMLUI_ZoneScopedC(0x6495ED);
  912. // Remove all DOM children.
  913. while ((int) children.size() > num_non_dom_children)
  914. RemoveChild(children.front().get());
  915. if(!rml.empty())
  916. Factory::InstanceElementText(this, rml);
  917. }
  918. // Sets the current element as the focus object.
  919. bool Element::Focus()
  920. {
  921. // Are we allowed focus?
  922. Style::Focus focus_property = element_meta->computed_values.focus;
  923. if (focus_property == Style::Focus::None)
  924. return false;
  925. // Ask our context if we can switch focus.
  926. Context* context = GetContext();
  927. if (context == nullptr)
  928. return false;
  929. if (!context->OnFocusChange(this))
  930. return false;
  931. // Set this as the end of the focus chain.
  932. focus = nullptr;
  933. // Update the focus chain up the hierarchy.
  934. Element* element = this;
  935. while (Element* parent = element->GetParentNode())
  936. {
  937. parent->focus = element;
  938. element = parent;
  939. }
  940. return true;
  941. }
  942. // Removes focus from from this element.
  943. void Element::Blur()
  944. {
  945. if (parent)
  946. {
  947. Context* context = GetContext();
  948. if (context == nullptr)
  949. return;
  950. if (context->GetFocusElement() == this)
  951. {
  952. parent->Focus();
  953. }
  954. else if (parent->focus == this)
  955. {
  956. parent->focus = nullptr;
  957. }
  958. }
  959. }
  960. // Fakes a mouse click on this element.
  961. void Element::Click()
  962. {
  963. Context* context = GetContext();
  964. if (context == nullptr)
  965. return;
  966. context->GenerateClickEvent(this);
  967. }
  968. // Adds an event listener
  969. void Element::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  970. {
  971. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  972. event_dispatcher->AttachEvent(id, listener, in_capture_phase);
  973. }
  974. // Adds an event listener
  975. void Element::AddEventListener(EventId id, EventListener* listener, bool in_capture_phase)
  976. {
  977. event_dispatcher->AttachEvent(id, listener, in_capture_phase);
  978. }
  979. // Removes an event listener from this element.
  980. void Element::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  981. {
  982. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  983. event_dispatcher->DetachEvent(id, listener, in_capture_phase);
  984. }
  985. // Removes an event listener from this element.
  986. void Element::RemoveEventListener(EventId id, EventListener* listener, bool in_capture_phase)
  987. {
  988. event_dispatcher->DetachEvent(id, listener, in_capture_phase);
  989. }
  990. // Dispatches the specified event
  991. bool Element::DispatchEvent(const String& type, const Dictionary& parameters)
  992. {
  993. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  994. return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
  995. }
  996. // Dispatches the specified event
  997. bool Element::DispatchEvent(const String& type, const Dictionary& parameters, bool interruptible, bool bubbles)
  998. {
  999. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  1000. return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, interruptible, bubbles, specification.default_action_phase);
  1001. }
  1002. // Dispatches the specified event
  1003. bool Element::DispatchEvent(EventId id, const Dictionary& parameters)
  1004. {
  1005. const EventSpecification& specification = EventSpecificationInterface::Get(id);
  1006. return EventDispatcher::DispatchEvent(this, specification.id, specification.type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
  1007. }
  1008. // Scrolls the parent element's contents so that this element is visible.
  1009. void Element::ScrollIntoView(bool align_with_top)
  1010. {
  1011. Vector2f size(0, 0);
  1012. if (!align_with_top)
  1013. {
  1014. size.y = main_box.GetOffset().y +
  1015. main_box.GetSize(Box::BORDER).y;
  1016. }
  1017. Element* scroll_parent = parent;
  1018. while (scroll_parent != nullptr)
  1019. {
  1020. Style::Overflow overflow_x_property = scroll_parent->GetComputedValues().overflow_x;
  1021. Style::Overflow overflow_y_property = scroll_parent->GetComputedValues().overflow_y;
  1022. if ((overflow_x_property != Style::Overflow::Visible &&
  1023. scroll_parent->GetScrollWidth() > scroll_parent->GetClientWidth()) ||
  1024. (overflow_y_property != Style::Overflow::Visible &&
  1025. scroll_parent->GetScrollHeight() > scroll_parent->GetClientHeight()))
  1026. {
  1027. Vector2f offset = scroll_parent->GetAbsoluteOffset(Box::BORDER) - GetAbsoluteOffset(Box::BORDER);
  1028. Vector2f scroll_offset(scroll_parent->GetScrollLeft(), scroll_parent->GetScrollTop());
  1029. scroll_offset -= offset;
  1030. scroll_offset.x += scroll_parent->GetClientLeft();
  1031. scroll_offset.y += scroll_parent->GetClientTop();
  1032. if (!align_with_top)
  1033. scroll_offset.y -= (scroll_parent->GetClientHeight() - size.y);
  1034. if (overflow_x_property != Style::Overflow::Visible)
  1035. scroll_parent->SetScrollLeft(scroll_offset.x);
  1036. if (overflow_y_property != Style::Overflow::Visible)
  1037. scroll_parent->SetScrollTop(scroll_offset.y);
  1038. }
  1039. scroll_parent = scroll_parent->GetParentNode();
  1040. }
  1041. }
  1042. // Appends a child to this element
  1043. Element* Element::AppendChild(ElementPtr child, bool dom_element)
  1044. {
  1045. RMLUI_ASSERT(child);
  1046. Element* child_ptr = child.get();
  1047. child_ptr->SetParent(this);
  1048. if (dom_element)
  1049. children.insert(children.end() - num_non_dom_children, std::move(child));
  1050. else
  1051. {
  1052. children.push_back(std::move(child));
  1053. num_non_dom_children++;
  1054. }
  1055. Element* ancestor = child_ptr;
  1056. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1057. ancestor->OnChildAdd(child_ptr);
  1058. DirtyStackingContext();
  1059. DirtyStructure();
  1060. if (dom_element)
  1061. DirtyLayout();
  1062. return child_ptr;
  1063. }
  1064. // Adds a child to this element, directly after the adjacent element. Inherits
  1065. // the dom/non-dom status from the adjacent element.
  1066. Element* Element::InsertBefore(ElementPtr child, Element* adjacent_element)
  1067. {
  1068. RMLUI_ASSERT(child);
  1069. // Find the position in the list of children of the adjacent element. If
  1070. // it's nullptr or we can't find it, then we insert it at the end of the dom
  1071. // children, as a dom element.
  1072. size_t child_index = 0;
  1073. bool found_child = false;
  1074. if (adjacent_element)
  1075. {
  1076. for (child_index = 0; child_index < children.size(); child_index++)
  1077. {
  1078. if (children[child_index].get() == adjacent_element)
  1079. {
  1080. found_child = true;
  1081. break;
  1082. }
  1083. }
  1084. }
  1085. Element* child_ptr = nullptr;
  1086. if (found_child)
  1087. {
  1088. child_ptr = child.get();
  1089. child_ptr->SetParent(this);
  1090. if ((int) child_index >= GetNumChildren())
  1091. num_non_dom_children++;
  1092. else
  1093. DirtyLayout();
  1094. children.insert(children.begin() + child_index, std::move(child));
  1095. Element* ancestor = child_ptr;
  1096. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1097. ancestor->OnChildAdd(child_ptr);
  1098. DirtyStackingContext();
  1099. DirtyStructure();
  1100. }
  1101. else
  1102. {
  1103. child_ptr = AppendChild(std::move(child));
  1104. }
  1105. return child_ptr;
  1106. }
  1107. // Replaces the second node with the first node.
  1108. ElementPtr Element::ReplaceChild(ElementPtr inserted_element, Element* replaced_element)
  1109. {
  1110. RMLUI_ASSERT(inserted_element);
  1111. auto insertion_point = children.begin();
  1112. while (insertion_point != children.end() && insertion_point->get() != replaced_element)
  1113. {
  1114. ++insertion_point;
  1115. }
  1116. Element* inserted_element_ptr = inserted_element.get();
  1117. if (insertion_point == children.end())
  1118. {
  1119. AppendChild(std::move(inserted_element));
  1120. return nullptr;
  1121. }
  1122. inserted_element_ptr->SetParent(this);
  1123. children.insert(insertion_point, std::move(inserted_element));
  1124. ElementPtr result = RemoveChild(replaced_element);
  1125. Element* ancestor = inserted_element_ptr;
  1126. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1127. ancestor->OnChildAdd(inserted_element_ptr);
  1128. return result;
  1129. }
  1130. // Removes the specified child
  1131. ElementPtr Element::RemoveChild(Element* child)
  1132. {
  1133. size_t child_index = 0;
  1134. for (auto itr = children.begin(); itr != children.end(); ++itr)
  1135. {
  1136. // Add the element to the delete list
  1137. if (itr->get() == child)
  1138. {
  1139. Element* ancestor = child;
  1140. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1141. ancestor->OnChildRemove(child);
  1142. if (child_index >= children.size() - num_non_dom_children)
  1143. num_non_dom_children--;
  1144. ElementPtr detached_child = std::move(*itr);
  1145. children.erase(itr);
  1146. // Remove the child element as the focused child of this element.
  1147. if (child == focus)
  1148. {
  1149. focus = nullptr;
  1150. // If this child (or a descendant of this child) is the context's currently
  1151. // focused element, set the focus to us instead.
  1152. if (Context * context = GetContext())
  1153. {
  1154. Element* focus_element = context->GetFocusElement();
  1155. while (focus_element)
  1156. {
  1157. if (focus_element == child)
  1158. {
  1159. Focus();
  1160. break;
  1161. }
  1162. focus_element = focus_element->GetParentNode();
  1163. }
  1164. }
  1165. }
  1166. detached_child->SetParent(nullptr);
  1167. DirtyLayout();
  1168. DirtyStackingContext();
  1169. DirtyStructure();
  1170. return detached_child;
  1171. }
  1172. child_index++;
  1173. }
  1174. return nullptr;
  1175. }
  1176. bool Element::HasChildNodes() const
  1177. {
  1178. return (int) children.size() > num_non_dom_children;
  1179. }
  1180. Element* Element::GetElementById(const String& id)
  1181. {
  1182. // Check for special-case tokens.
  1183. if (id == "#self")
  1184. return this;
  1185. else if (id == "#document")
  1186. return GetOwnerDocument();
  1187. else if (id == "#parent")
  1188. return this->parent;
  1189. else
  1190. {
  1191. Element* search_root = GetOwnerDocument();
  1192. if (search_root == nullptr)
  1193. search_root = this;
  1194. return ElementUtilities::GetElementById(search_root, id);
  1195. }
  1196. }
  1197. // Get all elements with the given tag.
  1198. void Element::GetElementsByTagName(ElementList& elements, const String& tag)
  1199. {
  1200. return ElementUtilities::GetElementsByTagName(elements, this, tag);
  1201. }
  1202. // Get all elements with the given class set on them.
  1203. void Element::GetElementsByClassName(ElementList& elements, const String& class_name)
  1204. {
  1205. return ElementUtilities::GetElementsByClassName(elements, this, class_name);
  1206. }
  1207. // Access the event dispatcher
  1208. EventDispatcher* Element::GetEventDispatcher() const
  1209. {
  1210. return event_dispatcher;
  1211. }
  1212. String Element::GetEventDispatcherSummary() const
  1213. {
  1214. return event_dispatcher->ToString();
  1215. }
  1216. // Access the element background.
  1217. ElementBackground* Element::GetElementBackground() const
  1218. {
  1219. return background;
  1220. }
  1221. // Access the element border.
  1222. ElementBorder* Element::GetElementBorder() const
  1223. {
  1224. return border;
  1225. }
  1226. // Access the element decorators
  1227. ElementDecoration* Element::GetElementDecoration() const
  1228. {
  1229. return decoration;
  1230. }
  1231. // Returns the element's scrollbar functionality.
  1232. ElementScroll* Element::GetElementScroll() const
  1233. {
  1234. return scroll;
  1235. }
  1236. int Element::GetClippingIgnoreDepth()
  1237. {
  1238. if (clipping_state_dirty)
  1239. {
  1240. IsClippingEnabled();
  1241. }
  1242. return clipping_ignore_depth;
  1243. }
  1244. bool Element::IsClippingEnabled()
  1245. {
  1246. if (clipping_state_dirty)
  1247. {
  1248. const auto& computed = GetComputedValues();
  1249. // Is clipping enabled for this element, yes unless both overlow properties are set to visible
  1250. clipping_enabled = computed.overflow_x != Style::Overflow::Visible
  1251. || computed.overflow_y != Style::Overflow::Visible;
  1252. // Get the clipping ignore depth from the clip property
  1253. clipping_ignore_depth = computed.clip.number;
  1254. clipping_state_dirty = false;
  1255. }
  1256. return clipping_enabled;
  1257. }
  1258. // Gets the render interface owned by this element's context.
  1259. RenderInterface* Element::GetRenderInterface()
  1260. {
  1261. if (Context* context = GetContext())
  1262. return context->GetRenderInterface();
  1263. return Rml::Core::GetRenderInterface();
  1264. }
  1265. void Element::SetInstancer(ElementInstancer* _instancer)
  1266. {
  1267. // Only record the first instancer being set as some instancers call other instancers to do their dirty work, in
  1268. // which case we don't want to update the lowest level instancer.
  1269. if (!instancer)
  1270. {
  1271. instancer = _instancer;
  1272. }
  1273. }
  1274. // Forces the element to generate a local stacking context, regardless of the value of its z-index property.
  1275. void Element::ForceLocalStackingContext()
  1276. {
  1277. local_stacking_context_forced = true;
  1278. local_stacking_context = true;
  1279. DirtyStackingContext();
  1280. }
  1281. // Called during the update loop after children are rendered.
  1282. void Element::OnUpdate()
  1283. {
  1284. }
  1285. // Called during render after backgrounds, borders, decorators, but before children, are rendered.
  1286. void Element::OnRender()
  1287. {
  1288. }
  1289. void Element::OnResize()
  1290. {
  1291. }
  1292. // Called during a layout operation, when the element is being positioned and sized.
  1293. void Element::OnLayout()
  1294. {
  1295. }
  1296. // Called when attributes on the element are changed.
  1297. void Element::OnAttributeChange(const ElementAttributes& changed_attributes)
  1298. {
  1299. auto it = changed_attributes.find("id");
  1300. if (it != changed_attributes.end())
  1301. {
  1302. id = it->second.Get<String>();
  1303. style->DirtyDefinition();
  1304. }
  1305. it = changed_attributes.find("class");
  1306. if (it != changed_attributes.end())
  1307. {
  1308. style->SetClassNames(it->second.Get<String>());
  1309. }
  1310. // Add any inline style declarations.
  1311. it = changed_attributes.find("style");
  1312. if (it != changed_attributes.end())
  1313. {
  1314. PropertyDictionary properties;
  1315. StyleSheetParser parser;
  1316. parser.ParseProperties(properties, it->second.Get<String>());
  1317. Rml::Core::PropertyMap property_map = properties.GetProperties();
  1318. for (Rml::Core::PropertyMap::iterator i = property_map.begin(); i != property_map.end(); ++i)
  1319. {
  1320. style->SetProperty((*i).first, (*i).second);
  1321. }
  1322. }
  1323. }
  1324. // Called when properties on the element are changed.
  1325. void Element::OnPropertyChange(const PropertyIdSet& changed_properties)
  1326. {
  1327. RMLUI_ZoneScoped;
  1328. if (!IsLayoutDirty())
  1329. {
  1330. // Force a relayout if any of the changed properties require it.
  1331. const PropertyIdSet changed_properties_forcing_layout = (changed_properties & StyleSheetSpecification::GetRegisteredPropertiesForcingLayout());
  1332. if(!changed_properties_forcing_layout.Empty())
  1333. DirtyLayout();
  1334. }
  1335. // Update the visibility.
  1336. if (changed_properties.Contains(PropertyId::Visibility) ||
  1337. changed_properties.Contains(PropertyId::Display))
  1338. {
  1339. bool new_visibility = (element_meta->computed_values.display != Style::Display::None && element_meta->computed_values.visibility == Style::Visibility::Visible);
  1340. if (visible != new_visibility)
  1341. {
  1342. visible = new_visibility;
  1343. if (parent != nullptr)
  1344. parent->DirtyStackingContext();
  1345. if (!visible)
  1346. Blur();
  1347. }
  1348. if (changed_properties.Contains(PropertyId::Display))
  1349. {
  1350. // Due to structural pseudo-classes, this may change the element definition in siblings and parent.
  1351. // However, the definitions will only be changed on the next update loop which may result in jarring behavior for one @frame.
  1352. // A possible workaround is to add the parent to a list of elements that need to be updated again.
  1353. if (parent != nullptr)
  1354. parent->DirtyStructure();
  1355. }
  1356. }
  1357. // Update the position.
  1358. if (changed_properties.Contains(PropertyId::Left) ||
  1359. changed_properties.Contains(PropertyId::Right) ||
  1360. changed_properties.Contains(PropertyId::Top) ||
  1361. changed_properties.Contains(PropertyId::Bottom))
  1362. {
  1363. // TODO: This should happen during/after layout, as the containing box is not properly defined yet. Off-by-one @frame issue.
  1364. UpdateOffset();
  1365. DirtyOffset();
  1366. }
  1367. // Update the z-index.
  1368. if (changed_properties.Contains(PropertyId::ZIndex))
  1369. {
  1370. Style::ZIndex z_index_property = element_meta->computed_values.z_index;
  1371. if (z_index_property.type == Style::ZIndex::Auto)
  1372. {
  1373. if (local_stacking_context &&
  1374. !local_stacking_context_forced)
  1375. {
  1376. // We're no longer acting as a stacking context.
  1377. local_stacking_context = false;
  1378. stacking_context_dirty = false;
  1379. stacking_context.clear();
  1380. }
  1381. // If our old z-index was not zero, then we must dirty our stacking context so we'll be re-indexed.
  1382. if (z_index != 0)
  1383. {
  1384. z_index = 0;
  1385. DirtyStackingContext();
  1386. }
  1387. }
  1388. else
  1389. {
  1390. float new_z_index = z_index_property.value;
  1391. if (new_z_index != z_index)
  1392. {
  1393. z_index = new_z_index;
  1394. if (parent != nullptr)
  1395. parent->DirtyStackingContext();
  1396. }
  1397. if (!local_stacking_context)
  1398. {
  1399. local_stacking_context = true;
  1400. stacking_context_dirty = true;
  1401. }
  1402. }
  1403. }
  1404. // Dirty the background if it's changed.
  1405. if (changed_properties.Contains(PropertyId::BackgroundColor) ||
  1406. changed_properties.Contains(PropertyId::Opacity) ||
  1407. changed_properties.Contains(PropertyId::ImageColor)) {
  1408. background->DirtyBackground();
  1409. }
  1410. // Dirty the decoration if it's changed.
  1411. if (changed_properties.Contains(PropertyId::Decorator) ||
  1412. changed_properties.Contains(PropertyId::Opacity) ||
  1413. changed_properties.Contains(PropertyId::ImageColor)) {
  1414. decoration->DirtyDecorators();
  1415. }
  1416. // Dirty the border if it's changed.
  1417. if (changed_properties.Contains(PropertyId::BorderTopWidth) ||
  1418. changed_properties.Contains(PropertyId::BorderRightWidth) ||
  1419. changed_properties.Contains(PropertyId::BorderBottomWidth) ||
  1420. changed_properties.Contains(PropertyId::BorderLeftWidth) ||
  1421. changed_properties.Contains(PropertyId::BorderTopColor) ||
  1422. changed_properties.Contains(PropertyId::BorderRightColor) ||
  1423. changed_properties.Contains(PropertyId::BorderBottomColor) ||
  1424. changed_properties.Contains(PropertyId::BorderLeftColor) ||
  1425. changed_properties.Contains(PropertyId::Opacity))
  1426. border->DirtyBorder();
  1427. // Check for clipping state changes
  1428. if (changed_properties.Contains(PropertyId::Clip) ||
  1429. changed_properties.Contains(PropertyId::OverflowX) ||
  1430. changed_properties.Contains(PropertyId::OverflowY))
  1431. {
  1432. clipping_state_dirty = true;
  1433. }
  1434. // Check for `perspective' and `perspective-origin' changes
  1435. if (changed_properties.Contains(PropertyId::Perspective) ||
  1436. changed_properties.Contains(PropertyId::PerspectiveOriginX) ||
  1437. changed_properties.Contains(PropertyId::PerspectiveOriginY))
  1438. {
  1439. DirtyTransformState(true, false);
  1440. }
  1441. // Check for `transform' and `transform-origin' changes
  1442. if (changed_properties.Contains(PropertyId::Transform) ||
  1443. changed_properties.Contains(PropertyId::TransformOriginX) ||
  1444. changed_properties.Contains(PropertyId::TransformOriginY) ||
  1445. changed_properties.Contains(PropertyId::TransformOriginZ))
  1446. {
  1447. DirtyTransformState(false, true);
  1448. }
  1449. // Check for `animation' changes
  1450. if (changed_properties.Contains(PropertyId::Animation))
  1451. {
  1452. dirty_animation = true;
  1453. }
  1454. // Check for `transition' changes
  1455. if (changed_properties.Contains(PropertyId::Transition))
  1456. {
  1457. dirty_transition = true;
  1458. }
  1459. }
  1460. // Called when a child node has been added somewhere in the hierarchy
  1461. void Element::OnChildAdd(Element* child)
  1462. {
  1463. }
  1464. // Called when a child node has been removed somewhere in the hierarchy
  1465. void Element::OnChildRemove(Element* child)
  1466. {
  1467. }
  1468. // Forces a re-layout of this element, and any other children required.
  1469. void Element::DirtyLayout()
  1470. {
  1471. Element* document = GetOwnerDocument();
  1472. if (document != nullptr)
  1473. document->DirtyLayout();
  1474. }
  1475. // Forces a re-layout of this element, and any other children required.
  1476. bool Element::IsLayoutDirty()
  1477. {
  1478. Element* document = GetOwnerDocument();
  1479. if (document != nullptr)
  1480. return document->IsLayoutDirty();
  1481. return false;
  1482. }
  1483. void Element::ProcessDefaultAction(Event& event)
  1484. {
  1485. if (event == EventId::Mousedown && IsPointWithinElement(Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0))) &&
  1486. event.GetParameter< int >("button", 0) == 0)
  1487. SetPseudoClass("active", true);
  1488. if (event == EventId::Mousescroll)
  1489. {
  1490. if (GetScrollHeight() > GetClientHeight())
  1491. {
  1492. Style::Overflow overflow_property = element_meta->computed_values.overflow_y;
  1493. if (overflow_property == Style::Overflow::Auto ||
  1494. overflow_property == Style::Overflow::Scroll)
  1495. {
  1496. // Stop the propagation if the current element has scrollbars.
  1497. // This prevents scrolling in parent elements, which is often unintended. If instead desired behavior is
  1498. // to scroll in parent elements when reaching top/bottom, move StopPropagation inside the next if statement.
  1499. event.StopPropagation();
  1500. const float wheel_delta = event.GetParameter< float >("wheel_delta", 0.f);
  1501. if ((wheel_delta < 0 && GetScrollTop() > 0) ||
  1502. (wheel_delta > 0 && GetScrollHeight() > GetScrollTop() + GetClientHeight()))
  1503. {
  1504. // Defined as three times the default line-height, multiplied by the dp ratio.
  1505. float default_scroll_length = 3.f * DefaultComputedValues.line_height.value;
  1506. if (const Context* context = GetContext())
  1507. default_scroll_length *= context->GetDensityIndependentPixelRatio();
  1508. SetScrollTop(GetScrollTop() + Math::RoundFloat(wheel_delta * default_scroll_length));
  1509. }
  1510. }
  1511. }
  1512. return;
  1513. }
  1514. if (event.GetPhase() == EventPhase::Target)
  1515. {
  1516. switch (event.GetId())
  1517. {
  1518. case EventId::Mouseover:
  1519. SetPseudoClass("hover", true);
  1520. break;
  1521. case EventId::Mouseout:
  1522. SetPseudoClass("hover", false);
  1523. break;
  1524. case EventId::Focus:
  1525. SetPseudoClass(FOCUS, true);
  1526. break;
  1527. case EventId::Blur:
  1528. SetPseudoClass(FOCUS, false);
  1529. break;
  1530. default:
  1531. break;
  1532. }
  1533. }
  1534. }
  1535. const Style::ComputedValues& Element::GetComputedValues() const
  1536. {
  1537. return element_meta->computed_values;
  1538. }
  1539. void Element::GetRML(String& content)
  1540. {
  1541. // First we start the open tag, add the attributes then close the open tag.
  1542. // Then comes the children in order, then we add our close tag.
  1543. content += "<";
  1544. content += tag;
  1545. for( auto& pair : attributes)
  1546. {
  1547. auto& name = pair.first;
  1548. auto& variant = pair.second;
  1549. String value;
  1550. if (variant.GetInto(value))
  1551. content += " " + name + "=\"" + value + "\"";
  1552. }
  1553. if (HasChildNodes())
  1554. {
  1555. content += ">";
  1556. GetInnerRML(content);
  1557. content += "</";
  1558. content += tag;
  1559. content += ">";
  1560. }
  1561. else
  1562. {
  1563. content += " />";
  1564. }
  1565. }
  1566. void Element::SetOwnerDocument(ElementDocument* document)
  1567. {
  1568. // If this element is a document, then never change owner_document.
  1569. if (owner_document != this)
  1570. {
  1571. if (owner_document && !document)
  1572. {
  1573. // We are detaching from the document and thereby also the context.
  1574. if (Context * context = owner_document->GetContext())
  1575. context->OnElementDetach(this);
  1576. }
  1577. if (owner_document != document)
  1578. {
  1579. owner_document = document;
  1580. for (ElementPtr& child : children)
  1581. child->SetOwnerDocument(document);
  1582. }
  1583. }
  1584. }
  1585. void Element::Release()
  1586. {
  1587. if (instancer)
  1588. instancer->ReleaseElement(this);
  1589. else
  1590. Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via RmlUi Factory. Unable to release.", GetAddress().c_str());
  1591. }
  1592. void Element::SetParent(Element* _parent)
  1593. {
  1594. // Assumes we are already detached from the hierarchy or we are detaching now.
  1595. RMLUI_ASSERT(!parent || !_parent);
  1596. parent = _parent;
  1597. if (parent)
  1598. {
  1599. // We need to update our definition and make sure we inherit the properties of our new parent.
  1600. style->DirtyDefinition();
  1601. style->DirtyInheritedProperties();
  1602. }
  1603. // The transform state may require recalculation.
  1604. if (transform_state || (parent && parent->transform_state))
  1605. DirtyTransformState(true, true);
  1606. SetOwnerDocument(parent ? parent->GetOwnerDocument() : nullptr);
  1607. }
  1608. void Element::DirtyOffset()
  1609. {
  1610. if(!offset_dirty)
  1611. {
  1612. offset_dirty = true;
  1613. if(transform_state)
  1614. DirtyTransformState(true, true);
  1615. // Not strictly true ... ?
  1616. for (size_t i = 0; i < children.size(); i++)
  1617. children[i]->DirtyOffset();
  1618. }
  1619. }
  1620. void Element::UpdateOffset()
  1621. {
  1622. using namespace Style;
  1623. const auto& computed = element_meta->computed_values;
  1624. Position position_property = computed.position;
  1625. if (position_property == Position::Absolute ||
  1626. position_property == Position::Fixed)
  1627. {
  1628. if (offset_parent != nullptr)
  1629. {
  1630. const Box& parent_box = offset_parent->GetBox();
  1631. Vector2f containing_block = parent_box.GetSize(Box::PADDING);
  1632. // If the element is anchored left, then the position is offset by that resolved value.
  1633. if (computed.left.type != Left::Auto)
  1634. relative_offset_base.x = parent_box.GetEdge(Box::BORDER, Box::LEFT) + (ResolveValue(computed.left, containing_block.x) + GetBox().GetEdge(Box::MARGIN, Box::LEFT));
  1635. // If the element is anchored right, then the position is set first so the element's right-most edge
  1636. // (including margins) will render up against the containing box's right-most content edge, and then
  1637. // offset by the resolved value.
  1638. else if (computed.right.type != Right::Auto)
  1639. relative_offset_base.x = containing_block.x + parent_box.GetEdge(Box::BORDER, Box::LEFT) - (ResolveValue(computed.right, containing_block.x) + GetBox().GetSize(Box::BORDER).x + GetBox().GetEdge(Box::MARGIN, Box::RIGHT));
  1640. // If the element is anchored top, then the position is offset by that resolved value.
  1641. if (computed.top.type != Top::Auto)
  1642. relative_offset_base.y = parent_box.GetEdge(Box::BORDER, Box::TOP) + (ResolveValue(computed.top, containing_block.y) + GetBox().GetEdge(Box::MARGIN, Box::TOP));
  1643. // If the element is anchored bottom, then the position is set first so the element's right-most edge
  1644. // (including margins) will render up against the containing box's right-most content edge, and then
  1645. // offset by the resolved value.
  1646. else if (computed.bottom.type != Bottom::Auto)
  1647. relative_offset_base.y = containing_block.y + parent_box.GetEdge(Box::BORDER, Box::TOP) - (ResolveValue(computed.bottom, containing_block.y) + GetBox().GetSize(Box::BORDER).y + GetBox().GetEdge(Box::MARGIN, Box::BOTTOM));
  1648. }
  1649. }
  1650. else if (position_property == Position::Relative)
  1651. {
  1652. if (offset_parent != nullptr)
  1653. {
  1654. const Box& parent_box = offset_parent->GetBox();
  1655. Vector2f containing_block = parent_box.GetSize();
  1656. if (computed.left.type != Left::Auto)
  1657. relative_offset_position.x = ResolveValue(computed.left, containing_block.x);
  1658. else if (computed.right.type != Right::Auto)
  1659. relative_offset_position.x = -1 * ResolveValue(computed.right, containing_block.x);
  1660. else
  1661. relative_offset_position.x = 0;
  1662. if (computed.top.type != Top::Auto)
  1663. relative_offset_position.y = ResolveValue(computed.top, containing_block.y);
  1664. else if (computed.bottom.type != Bottom::Auto)
  1665. relative_offset_position.y = -1 * ResolveValue(computed.bottom, containing_block.y);
  1666. else
  1667. relative_offset_position.y = 0;
  1668. }
  1669. }
  1670. else
  1671. {
  1672. relative_offset_position.x = 0;
  1673. relative_offset_position.y = 0;
  1674. }
  1675. }
  1676. void Element::BuildLocalStackingContext()
  1677. {
  1678. stacking_context_dirty = false;
  1679. stacking_context.clear();
  1680. BuildStackingContext(&stacking_context);
  1681. std::stable_sort(stacking_context.begin(), stacking_context.end(), ElementSortZIndex());
  1682. }
  1683. void Element::BuildStackingContext(ElementList* new_stacking_context)
  1684. {
  1685. RMLUI_ZoneScoped;
  1686. // Build the list of ordered children. Our child list is sorted within the stacking context so stacked elements
  1687. // will render in the right order; ie, positioned elements will render on top of inline elements, which will render
  1688. // on top of floated elements, which will render on top of block elements.
  1689. std::vector< std::pair< Element*, float > > ordered_children;
  1690. for (size_t i = 0; i < children.size(); ++i)
  1691. {
  1692. Element* child = children[i].get();
  1693. if (!child->IsVisible())
  1694. continue;
  1695. std::pair< Element*, float > ordered_child;
  1696. ordered_child.first = child;
  1697. if (child->GetPosition() != Style::Position::Static)
  1698. ordered_child.second = 3;
  1699. else if (child->GetFloat() != Style::Float::None)
  1700. ordered_child.second = 1;
  1701. else if (child->GetDisplay() == Style::Display::Block)
  1702. ordered_child.second = 0;
  1703. else
  1704. ordered_child.second = 2;
  1705. ordered_children.push_back(ordered_child);
  1706. }
  1707. // Sort the list!
  1708. std::stable_sort(ordered_children.begin(), ordered_children.end(), ElementSortZOrder());
  1709. // Add the list of ordered children into the stacking context in order.
  1710. for (size_t i = 0; i < ordered_children.size(); ++i)
  1711. {
  1712. new_stacking_context->push_back(ordered_children[i].first);
  1713. if (!ordered_children[i].first->local_stacking_context)
  1714. ordered_children[i].first->BuildStackingContext(new_stacking_context);
  1715. }
  1716. }
  1717. void Element::DirtyStackingContext()
  1718. {
  1719. // The first ancestor of ours that doesn't have an automatic z-index is the ancestor that is establishing our local
  1720. // stacking context.
  1721. Element* stacking_context_parent = this;
  1722. while (stacking_context_parent != nullptr &&
  1723. !stacking_context_parent->local_stacking_context)
  1724. stacking_context_parent = stacking_context_parent->GetParentNode();
  1725. if (stacking_context_parent != nullptr)
  1726. stacking_context_parent->stacking_context_dirty = true;
  1727. }
  1728. void Element::DirtyStructure()
  1729. {
  1730. structure_dirty = true;
  1731. }
  1732. void Element::UpdateStructure()
  1733. {
  1734. if (structure_dirty)
  1735. {
  1736. structure_dirty = false;
  1737. // If this element or its children depend on structured selectors, they may need to be updated.
  1738. GetStyle()->DirtyDefinition();
  1739. }
  1740. }
  1741. bool Element::Animate(const String & property_name, const Property & target_value, float duration, Tween tween, int num_iterations, bool alternate_direction, float delay, const Property* start_value)
  1742. {
  1743. bool result = false;
  1744. PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
  1745. auto it_animation = StartAnimation(property_id, start_value, num_iterations, alternate_direction, delay, false);
  1746. if (it_animation != animations.end())
  1747. {
  1748. result = it_animation->AddKey(duration, target_value, *this, tween, true);
  1749. if (!result)
  1750. animations.erase(it_animation);
  1751. }
  1752. return result;
  1753. }
  1754. bool Element::AddAnimationKey(const String & property_name, const Property & target_value, float duration, Tween tween)
  1755. {
  1756. ElementAnimation* animation = nullptr;
  1757. PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
  1758. for (auto& existing_animation : animations) {
  1759. if (existing_animation.GetPropertyId() == property_id) {
  1760. animation = &existing_animation;
  1761. break;
  1762. }
  1763. }
  1764. if (!animation)
  1765. return false;
  1766. bool result = animation->AddKey(animation->GetDuration() + duration, target_value, *this, tween, true);
  1767. return result;
  1768. }
  1769. ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, const Property* start_value, int num_iterations, bool alternate_direction, float delay, bool origin_is_animation_property)
  1770. {
  1771. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == property_id; });
  1772. if (it == animations.end())
  1773. {
  1774. animations.emplace_back();
  1775. it = animations.end() - 1;
  1776. }
  1777. Property value;
  1778. if (start_value)
  1779. {
  1780. value = *start_value;
  1781. if (!value.definition)
  1782. if(auto default_value = GetProperty(property_id))
  1783. value.definition = default_value->definition;
  1784. }
  1785. else if (auto default_value = GetProperty(property_id))
  1786. {
  1787. value = *default_value;
  1788. }
  1789. if (value.definition)
  1790. {
  1791. ElementAnimationOrigin origin = (origin_is_animation_property ? ElementAnimationOrigin::Animation : ElementAnimationOrigin::User);
  1792. double start_time = Clock::GetElapsedTime() + (double)delay;
  1793. *it = ElementAnimation{ property_id, origin, value, start_time, 0.0f, num_iterations, alternate_direction };
  1794. }
  1795. else
  1796. {
  1797. animations.erase(it);
  1798. it = animations.end();
  1799. }
  1800. return it;
  1801. }
  1802. bool Element::AddAnimationKeyTime(PropertyId property_id, const Property* target_value, float time, Tween tween)
  1803. {
  1804. if (!target_value)
  1805. target_value = style->GetProperty(property_id);
  1806. if (!target_value)
  1807. return false;
  1808. ElementAnimation* animation = nullptr;
  1809. for (auto& existing_animation : animations) {
  1810. if (existing_animation.GetPropertyId() == property_id) {
  1811. animation = &existing_animation;
  1812. break;
  1813. }
  1814. }
  1815. if (!animation)
  1816. return false;
  1817. bool result = animation->AddKey(time, *target_value, *this, tween, true);
  1818. return result;
  1819. }
  1820. bool Element::StartTransition(const Transition & transition, const Property& start_value, const Property & target_value)
  1821. {
  1822. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == transition.id; });
  1823. if (it != animations.end() && !it->IsTransition())
  1824. return false;
  1825. float duration = transition.duration;
  1826. double start_time = Clock::GetElapsedTime() + (double)transition.delay;
  1827. if (it == animations.end())
  1828. {
  1829. // Add transition as new animation
  1830. animations.push_back(
  1831. ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, start_time, 0.0f, 1, false }
  1832. );
  1833. it = (animations.end() - 1);
  1834. }
  1835. else
  1836. {
  1837. // Compress the duration based on the progress of the current animation
  1838. float f = it->GetInterpolationFactor();
  1839. f = 1.0f - (1.0f - f)*transition.reverse_adjustment_factor;
  1840. duration = duration * f;
  1841. // Replace old transition
  1842. *it = ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, start_time, 0.0f, 1, false };
  1843. }
  1844. bool result = it->AddKey(duration, target_value, *this, transition.tween, true);
  1845. if (result)
  1846. SetProperty(transition.id, start_value);
  1847. else
  1848. animations.erase(it);
  1849. return result;
  1850. }
  1851. void Element::UpdateTransition()
  1852. {
  1853. if(dirty_transition)
  1854. {
  1855. dirty_transition = false;
  1856. // Remove all transitions that are no longer in our local list
  1857. const TransitionList& keep_transitions = GetComputedValues().transition;
  1858. if (keep_transitions.all)
  1859. return;
  1860. auto it_remove = animations.end();
  1861. if (keep_transitions.none)
  1862. {
  1863. // All transitions should be removed, but only touch the animations that originate from the 'transition' property.
  1864. // Move all animations to be erased in a valid state at the end of the list, and erase later.
  1865. it_remove = std::partition(animations.begin(), animations.end(),
  1866. [](const ElementAnimation& animation) -> bool { return !animation.IsTransition(); }
  1867. );
  1868. }
  1869. else
  1870. {
  1871. // Only remove the transitions that are not in our keep list.
  1872. const auto& keep_transitions_list = keep_transitions.transitions;
  1873. it_remove = std::partition(animations.begin(), animations.end(),
  1874. [&keep_transitions_list](const ElementAnimation& animation) -> bool {
  1875. if (!animation.IsTransition())
  1876. return true;
  1877. auto it = std::find_if(keep_transitions_list.begin(), keep_transitions_list.end(),
  1878. [&animation](const Transition& transition) { return animation.GetPropertyId() == transition.id; }
  1879. );
  1880. bool keep_animation = (it != keep_transitions_list.end());
  1881. return keep_animation;
  1882. }
  1883. );
  1884. }
  1885. // We can decide what to do with ended animations here, just removing them seems to be the CSS approach.
  1886. for (auto it = it_remove; it != animations.end(); ++it)
  1887. RemoveProperty(it->GetPropertyId());
  1888. animations.erase(it_remove, animations.end());
  1889. }
  1890. }
  1891. void Element::UpdateAnimation()
  1892. {
  1893. if (dirty_animation)
  1894. {
  1895. dirty_animation = false;
  1896. const AnimationList& animation_list = element_meta->computed_values.animation;
  1897. bool element_has_animations = (!animation_list.empty() || !animations.empty());
  1898. StyleSheet* stylesheet = nullptr;
  1899. if (element_has_animations && (stylesheet = GetStyleSheet().get()))
  1900. {
  1901. // Remove existing animations
  1902. // Note: We are effectively restarting all animations whenever 'drty_animation' is set. Use the dirty flag with care,
  1903. // or find another approach which only updates actual "dirty" animations.
  1904. {
  1905. // We only touch the animations that originate from the 'animation' property.
  1906. auto it_remove = std::partition(animations.begin(), animations.end(),
  1907. [](const ElementAnimation & animation) { return animation.GetOrigin() != ElementAnimationOrigin::Animation; }
  1908. );
  1909. // We can decide what to do with ended animations here, should be consistent with removal of transitions.
  1910. for (auto it = it_remove; it != animations.end(); ++it)
  1911. RemoveProperty(it->GetPropertyId());
  1912. animations.erase(it_remove, animations.end());
  1913. }
  1914. // Start animations
  1915. for (const auto& animation : animation_list)
  1916. {
  1917. const Keyframes* keyframes_ptr = stylesheet->GetKeyframes(animation.name);
  1918. if (keyframes_ptr && keyframes_ptr->blocks.size() >= 1 && !animation.paused)
  1919. {
  1920. auto& property_ids = keyframes_ptr->property_ids;
  1921. auto& blocks = keyframes_ptr->blocks;
  1922. bool has_from_key = (blocks[0].normalized_time == 0);
  1923. bool has_to_key = (blocks.back().normalized_time == 1);
  1924. // If the first key defines initial conditions for a given property, use those values, else, use this element's current values.
  1925. for (PropertyId id : property_ids)
  1926. StartAnimation(id, (has_from_key ? blocks[0].properties.GetProperty(id) : nullptr), animation.num_iterations, animation.alternate, animation.delay, true);
  1927. // Need to skip the first and last keys if they set the initial and end conditions, respectively.
  1928. for (int i = (has_from_key ? 1 : 0); i < (int)blocks.size() + (has_to_key ? -1 : 0); i++)
  1929. {
  1930. // Add properties of current key to animation
  1931. float time = blocks[i].normalized_time * animation.duration;
  1932. for (auto& property : blocks[i].properties.GetProperties())
  1933. AddAnimationKeyTime(property.first, &property.second, time, animation.tween);
  1934. }
  1935. // If the last key defines end conditions for a given property, use those values, else, use this element's current values.
  1936. float time = animation.duration;
  1937. for (PropertyId id : property_ids)
  1938. AddAnimationKeyTime(id, (has_to_key ? blocks.back().properties.GetProperty(id) : nullptr), time, animation.tween);
  1939. }
  1940. }
  1941. }
  1942. }
  1943. }
  1944. void Element::AdvanceAnimations()
  1945. {
  1946. if (!animations.empty())
  1947. {
  1948. double time = Clock::GetElapsedTime();
  1949. for (auto& animation : animations)
  1950. {
  1951. Property property = animation.UpdateAndGetProperty(time, *this);
  1952. if (property.unit != Property::UNKNOWN)
  1953. SetProperty(animation.GetPropertyId(), property);
  1954. }
  1955. // Move all completed animations to the end of the list
  1956. auto it_completed = std::partition(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return !animation.IsComplete(); });
  1957. std::vector<Dictionary> dictionary_list;
  1958. std::vector<bool> is_transition;
  1959. dictionary_list.reserve(animations.end() - it_completed);
  1960. is_transition.reserve(animations.end() - it_completed);
  1961. for (auto it = it_completed; it != animations.end(); ++it)
  1962. {
  1963. dictionary_list.emplace_back();
  1964. dictionary_list.back().emplace("property", StyleSheetSpecification::GetPropertyName(it->GetPropertyId()));
  1965. is_transition.push_back(it->IsTransition());
  1966. }
  1967. // Need to erase elements before submitting event, as iterators might be invalidated when calling external code.
  1968. animations.erase(it_completed, animations.end());
  1969. for (size_t i = 0; i < dictionary_list.size(); i++)
  1970. DispatchEvent(is_transition[i] ? EventId::Transitionend : EventId::Animationend, dictionary_list[i]);
  1971. }
  1972. }
  1973. void Element::DirtyTransformState(bool perspective_dirty, bool transform_dirty)
  1974. {
  1975. dirty_perspective |= perspective_dirty;
  1976. dirty_transform |= transform_dirty;
  1977. }
  1978. void Element::UpdateTransformState()
  1979. {
  1980. if (!dirty_perspective && !dirty_transform)
  1981. return;
  1982. const ComputedValues& computed = element_meta->computed_values;
  1983. const Vector2f pos = GetAbsoluteOffset(Box::BORDER);
  1984. const Vector2f size = GetBox().GetSize(Box::BORDER);
  1985. bool perspective_or_transform_changed = false;
  1986. if (dirty_perspective)
  1987. {
  1988. // If perspective is set on this element, then it applies to our children. We just calculate it here,
  1989. // and let the children's transform update merge it with their transform.
  1990. bool had_perspective = (transform_state && transform_state->GetLocalPerspective());
  1991. float distance = computed.perspective;
  1992. Vector2f vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
  1993. bool have_perspective = false;
  1994. if (distance > 0.0f)
  1995. {
  1996. have_perspective = true;
  1997. // Compute the vanishing point from the perspective origin
  1998. if (computed.perspective_origin_x.type == Style::PerspectiveOrigin::Percentage)
  1999. vanish.x = pos.x + computed.perspective_origin_x.value * 0.01f * size.x;
  2000. else
  2001. vanish.x = pos.x + computed.perspective_origin_x.value;
  2002. if (computed.perspective_origin_y.type == Style::PerspectiveOrigin::Percentage)
  2003. vanish.y = pos.y + computed.perspective_origin_y.value * 0.01f * size.y;
  2004. else
  2005. vanish.y = pos.y + computed.perspective_origin_y.value;
  2006. }
  2007. if (have_perspective)
  2008. {
  2009. // Equivalent to: Translate(x,y,0) * Perspective(distance) * Translate(-x,-y,0)
  2010. Matrix4f perspective = Matrix4f::FromRows(
  2011. { 1, 0, -vanish.x / distance, 0 },
  2012. { 0, 1, -vanish.y / distance, 0 },
  2013. { 0, 0, 1, 0 },
  2014. { 0, 0, -1 / distance, 1 }
  2015. );
  2016. if (!transform_state)
  2017. transform_state = std::make_unique<TransformState>();
  2018. perspective_or_transform_changed |= transform_state->SetLocalPerspective(&perspective);
  2019. }
  2020. else if (transform_state)
  2021. transform_state->SetLocalPerspective(nullptr);
  2022. perspective_or_transform_changed |= (have_perspective != had_perspective);
  2023. dirty_perspective = false;
  2024. }
  2025. if (dirty_transform)
  2026. {
  2027. // We want to find the accumulated transform given all our ancestors. It is assumed here that the parent transform is already updated,
  2028. // so that we only need to consider our local transform and combine it with our parent's transform and perspective matrices.
  2029. bool had_transform = (transform_state && transform_state->GetTransform());
  2030. bool have_transform = false;
  2031. Matrix4f transform = Matrix4f::Identity();
  2032. if (computed.transform)
  2033. {
  2034. // First find the current element's transform
  2035. const int n = computed.transform->GetNumPrimitives();
  2036. for (int i = 0; i < n; ++i)
  2037. {
  2038. const Transforms::Primitive& primitive = computed.transform->GetPrimitive(i);
  2039. Matrix4f matrix;
  2040. if (primitive.ResolveTransform(matrix, *this))
  2041. {
  2042. transform *= matrix;
  2043. have_transform = true;
  2044. }
  2045. }
  2046. if(have_transform)
  2047. {
  2048. // Compute the transform origin
  2049. Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
  2050. if (computed.transform_origin_x.type == Style::TransformOrigin::Percentage)
  2051. transform_origin.x = pos.x + computed.transform_origin_x.value * size.x * 0.01f;
  2052. else
  2053. transform_origin.x = pos.x + computed.transform_origin_x.value;
  2054. if (computed.transform_origin_y.type == Style::TransformOrigin::Percentage)
  2055. transform_origin.y = pos.y + computed.transform_origin_y.value * size.y * 0.01f;
  2056. else
  2057. transform_origin.y = pos.y + computed.transform_origin_y.value;
  2058. transform_origin.z = computed.transform_origin_z;
  2059. // Make the transformation apply relative to the transform origin
  2060. transform = Matrix4f::Translate(transform_origin) * transform * Matrix4f::Translate(-transform_origin);
  2061. }
  2062. // We may want to include the local offsets here, as suggested by the CSS specs, so that the local transform is applied after the offset I believe
  2063. // the motivation is. Then we would need to subtract the absolute zero-offsets during geometry submit whenever we have transforms.
  2064. }
  2065. if (parent && parent->transform_state)
  2066. {
  2067. // Apply the parent's local perspective and transform.
  2068. // @performance: If we have no local transform and no parent perspective, we can effectively just point to the parent transform instead of copying it.
  2069. const TransformState& parent_state = *parent->transform_state;
  2070. if (auto parent_perspective = parent_state.GetLocalPerspective())
  2071. {
  2072. transform = *parent_perspective * transform;
  2073. have_transform = true;
  2074. }
  2075. if (auto parent_transform = parent_state.GetTransform())
  2076. {
  2077. transform = *parent_transform * transform;
  2078. have_transform = true;
  2079. }
  2080. }
  2081. if (have_transform)
  2082. {
  2083. if (!transform_state)
  2084. transform_state = std::make_unique<TransformState>();
  2085. perspective_or_transform_changed |= transform_state->SetTransform(&transform);
  2086. }
  2087. else if (transform_state)
  2088. transform_state->SetTransform(nullptr);
  2089. perspective_or_transform_changed |= (had_transform != have_transform);
  2090. }
  2091. // A change in perspective or transform will require an update to children transforms as well.
  2092. if (perspective_or_transform_changed)
  2093. {
  2094. for (size_t i = 0; i < children.size(); i++)
  2095. children[i]->DirtyTransformState(false, true);
  2096. }
  2097. // No reason to keep the transform state around if transform and perspective have been removed.
  2098. if (transform_state && !transform_state->GetTransform() && !transform_state->GetLocalPerspective())
  2099. {
  2100. transform_state.reset();
  2101. }
  2102. }
  2103. }
  2104. }