Element.cpp 80 KB

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