Element.cpp 78 KB

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