Element.cpp 76 KB

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