Element.cpp 76 KB

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