Element.cpp 78 KB

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