Element.cpp 76 KB

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