Element.cpp 78 KB

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