Element.cpp 73 KB

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