Element.cpp 78 KB

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