Element.cpp 78 KB

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