Element.cpp 73 KB

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