Element.cpp 78 KB

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