Element.cpp 72 KB

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