Element.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713
  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. LockLayout(true);
  1122. child->AddReference();
  1123. child->SetParent(this);
  1124. if (dom_element)
  1125. children.insert(children.end() - num_non_dom_children, child);
  1126. else
  1127. {
  1128. children.push_back(child);
  1129. num_non_dom_children++;
  1130. }
  1131. child->GetStyle()->DirtyDefinition();
  1132. all_properties_dirty = true;
  1133. child->OnChildAdd(child);
  1134. DirtyStackingContext();
  1135. DirtyStructure();
  1136. if (dom_element)
  1137. DirtyLayout();
  1138. LockLayout(false);
  1139. }
  1140. // Adds a child to this element, directly after the adjacent element. Inherits
  1141. // the dom/non-dom status from the adjacent element.
  1142. void Element::InsertBefore(Element* child, Element* adjacent_element)
  1143. {
  1144. // Find the position in the list of children of the adjacent element. If
  1145. // it's NULL or we can't find it, then we insert it at the end of the dom
  1146. // children, as a dom element.
  1147. size_t child_index = 0;
  1148. bool found_child = false;
  1149. if (adjacent_element)
  1150. {
  1151. for (child_index = 0; child_index < children.size(); child_index++)
  1152. {
  1153. if (children[child_index] == adjacent_element)
  1154. {
  1155. found_child = true;
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. if (found_child)
  1161. {
  1162. LockLayout(true);
  1163. child->AddReference();
  1164. child->SetParent(this);
  1165. if ((int) child_index >= GetNumChildren())
  1166. num_non_dom_children++;
  1167. else
  1168. DirtyLayout();
  1169. children.insert(children.begin() + child_index, child);
  1170. child->GetStyle()->DirtyDefinition();
  1171. all_properties_dirty = true;
  1172. child->OnChildAdd(child);
  1173. DirtyStackingContext();
  1174. DirtyStructure();
  1175. LockLayout(false);
  1176. }
  1177. else
  1178. {
  1179. AppendChild(child);
  1180. }
  1181. }
  1182. // Replaces the second node with the first node.
  1183. bool Element::ReplaceChild(Element* inserted_element, Element* replaced_element)
  1184. {
  1185. inserted_element->AddReference();
  1186. inserted_element->SetParent(this);
  1187. ElementList::iterator insertion_point = children.begin();
  1188. while (insertion_point != children.end() && *insertion_point != replaced_element)
  1189. {
  1190. ++insertion_point;
  1191. }
  1192. if (insertion_point == children.end())
  1193. {
  1194. AppendChild(inserted_element);
  1195. return false;
  1196. }
  1197. LockLayout(true);
  1198. children.insert(insertion_point, inserted_element);
  1199. RemoveChild(replaced_element);
  1200. inserted_element->GetStyle()->DirtyDefinition();
  1201. all_properties_dirty = true;
  1202. inserted_element->OnChildAdd(inserted_element);
  1203. LockLayout(false);
  1204. return true;
  1205. }
  1206. // Removes the specified child
  1207. bool Element::RemoveChild(Element* child)
  1208. {
  1209. size_t child_index = 0;
  1210. for (ElementList::iterator itr = children.begin(); itr != children.end(); ++itr)
  1211. {
  1212. // Add the element to the delete list
  1213. if ((*itr) == child)
  1214. {
  1215. LockLayout(true);
  1216. // Inform the context of the element's pending removal (if we have a valid context).
  1217. Context* context = GetContext();
  1218. if (context)
  1219. context->OnElementRemove(child);
  1220. child->OnChildRemove(child);
  1221. if (child_index >= children.size() - num_non_dom_children)
  1222. num_non_dom_children--;
  1223. deleted_children.push_back(child);
  1224. children.erase(itr);
  1225. // Remove the child element as the focussed child of this element.
  1226. if (child == focus)
  1227. {
  1228. focus = NULL;
  1229. // If this child (or a descendant of this child) is the context's currently
  1230. // focussed element, set the focus to us instead.
  1231. Context* context = GetContext();
  1232. if (context != NULL)
  1233. {
  1234. Element* focus_element = context->GetFocusElement();
  1235. while (focus_element != NULL)
  1236. {
  1237. if (focus_element == child)
  1238. {
  1239. Focus();
  1240. break;
  1241. }
  1242. focus_element = focus_element->GetParentNode();
  1243. }
  1244. }
  1245. }
  1246. DirtyLayout();
  1247. DirtyStackingContext();
  1248. DirtyStructure();
  1249. LockLayout(false);
  1250. return true;
  1251. }
  1252. child_index++;
  1253. }
  1254. return false;
  1255. }
  1256. bool Element::HasChildNodes() const
  1257. {
  1258. return (int) children.size() > num_non_dom_children;
  1259. }
  1260. Element* Element::GetElementById(const String& id)
  1261. {
  1262. // Check for special-case tokens.
  1263. if (id == "#self")
  1264. return this;
  1265. else if (id == "#document")
  1266. return GetOwnerDocument();
  1267. else if (id == "#parent")
  1268. return this->parent;
  1269. else
  1270. {
  1271. Element* search_root = GetOwnerDocument();
  1272. if (search_root == NULL)
  1273. search_root = this;
  1274. return ElementUtilities::GetElementById(search_root, id);
  1275. }
  1276. }
  1277. // Get all elements with the given tag.
  1278. void Element::GetElementsByTagName(ElementList& elements, const String& tag)
  1279. {
  1280. return ElementUtilities::GetElementsByTagName(elements, this, tag);
  1281. }
  1282. // Get all elements with the given class set on them.
  1283. void Element::GetElementsByClassName(ElementList& elements, const String& class_name)
  1284. {
  1285. return ElementUtilities::GetElementsByClassName(elements, this, class_name);
  1286. }
  1287. // Access the event dispatcher
  1288. EventDispatcher* Element::GetEventDispatcher() const
  1289. {
  1290. return event_dispatcher;
  1291. }
  1292. String Element::GetEventDispatcherSummary() const
  1293. {
  1294. return event_dispatcher->ToString();
  1295. }
  1296. // Access the element background.
  1297. ElementBackground* Element::GetElementBackground() const
  1298. {
  1299. return background;
  1300. }
  1301. // Access the element border.
  1302. ElementBorder* Element::GetElementBorder() const
  1303. {
  1304. return border;
  1305. }
  1306. // Access the element decorators
  1307. ElementDecoration* Element::GetElementDecoration() const
  1308. {
  1309. return decoration;
  1310. }
  1311. // Returns the element's scrollbar functionality.
  1312. ElementScroll* Element::GetElementScroll() const
  1313. {
  1314. return scroll;
  1315. }
  1316. int Element::GetClippingIgnoreDepth()
  1317. {
  1318. if (clipping_state_dirty)
  1319. {
  1320. IsClippingEnabled();
  1321. }
  1322. return clipping_ignore_depth;
  1323. }
  1324. bool Element::IsClippingEnabled()
  1325. {
  1326. if (clipping_state_dirty)
  1327. {
  1328. const auto& computed = GetComputedValues();
  1329. // Is clipping enabled for this element, yes unless both overlow properties are set to visible
  1330. clipping_enabled = computed.overflow_x != Style::Overflow::Visible
  1331. || computed.overflow_y != Style::Overflow::Visible;
  1332. // Get the clipping ignore depth from the clip property
  1333. clipping_ignore_depth = computed.clip.number;
  1334. clipping_state_dirty = false;
  1335. }
  1336. return clipping_enabled;
  1337. }
  1338. // Gets the render interface owned by this element's context.
  1339. RenderInterface* Element::GetRenderInterface()
  1340. {
  1341. Context* context = GetContext();
  1342. if (context != NULL)
  1343. return context->GetRenderInterface();
  1344. return Rocket::Core::GetRenderInterface();
  1345. }
  1346. void Element::SetInstancer(ElementInstancer* _instancer)
  1347. {
  1348. // Only record the first instancer being set as some instancers call other instancers to do their dirty work, in
  1349. // which case we don't want to update the lowest level instancer.
  1350. if (instancer == NULL)
  1351. {
  1352. instancer = _instancer;
  1353. instancer->AddReference();
  1354. }
  1355. }
  1356. // Forces the element to generate a local stacking context, regardless of the value of its z-index property.
  1357. void Element::ForceLocalStackingContext()
  1358. {
  1359. local_stacking_context_forced = true;
  1360. local_stacking_context = true;
  1361. DirtyStackingContext();
  1362. }
  1363. // Called during the update loop after children are rendered.
  1364. void Element::OnUpdate()
  1365. {
  1366. }
  1367. // Called during render after backgrounds, borders, decorators, but before children, are rendered.
  1368. void Element::OnRender()
  1369. {
  1370. }
  1371. void Element::OnResize()
  1372. {
  1373. }
  1374. // Called during a layout operation, when the element is being positioned and sized.
  1375. void Element::OnLayout()
  1376. {
  1377. }
  1378. // Called when attributes on the element are changed.
  1379. void Element::OnAttributeChange(const AttributeNameList& changed_attributes)
  1380. {
  1381. if (changed_attributes.find("id") != changed_attributes.end())
  1382. {
  1383. id = GetAttribute< String >("id", "");
  1384. style->DirtyDefinition();
  1385. }
  1386. if (changed_attributes.find("class") != changed_attributes.end())
  1387. {
  1388. style->SetClassNames(GetAttribute< String >("class", ""));
  1389. }
  1390. // Add any inline style declarations.
  1391. if (changed_attributes.find("style") != changed_attributes.end())
  1392. {
  1393. PropertyDictionary properties;
  1394. StyleSheetParser parser;
  1395. parser.ParseProperties(properties, GetAttribute< String >("style", ""));
  1396. Rocket::Core::PropertyMap property_map = properties.GetProperties();
  1397. for (Rocket::Core::PropertyMap::iterator i = property_map.begin(); i != property_map.end(); ++i)
  1398. {
  1399. SetProperty((*i).first, (*i).second);
  1400. }
  1401. }
  1402. }
  1403. // Called when properties on the element are changed.
  1404. void Element::OnPropertyChange(const PropertyNameList& changed_properties)
  1405. {
  1406. bool all_dirty = false;
  1407. {
  1408. auto& registered_properties = StyleSheetSpecification::GetRegisteredProperties();
  1409. if (&registered_properties == &changed_properties || registered_properties == changed_properties)
  1410. all_dirty = true;
  1411. }
  1412. if (!IsLayoutDirty())
  1413. {
  1414. if (all_dirty)
  1415. {
  1416. DirtyLayout();
  1417. }
  1418. else
  1419. {
  1420. // Force a relayout if any of the changed properties require it.
  1421. for (PropertyNameList::const_iterator i = changed_properties.begin(); i != changed_properties.end(); ++i)
  1422. {
  1423. const PropertyDefinition* property_definition = StyleSheetSpecification::GetProperty(*i);
  1424. if (property_definition)
  1425. {
  1426. if (property_definition->IsLayoutForced())
  1427. {
  1428. DirtyLayout();
  1429. break;
  1430. }
  1431. }
  1432. }
  1433. }
  1434. }
  1435. // Update the visibility.
  1436. if (all_dirty || changed_properties.find(VISIBILITY) != changed_properties.end() ||
  1437. changed_properties.find(DISPLAY) != changed_properties.end())
  1438. {
  1439. bool new_visibility = (element_meta->computed_values.display != Style::Display::None && element_meta->computed_values.visibility == Style::Visibility::Visible);
  1440. if (visible != new_visibility)
  1441. {
  1442. visible = new_visibility;
  1443. if (parent != NULL)
  1444. parent->DirtyStackingContext();
  1445. }
  1446. if (all_dirty ||
  1447. changed_properties.find(DISPLAY) != changed_properties.end())
  1448. {
  1449. if (parent != NULL)
  1450. parent->DirtyStructure();
  1451. }
  1452. }
  1453. // Fetch a new font face if it has been changed.
  1454. if (all_dirty ||
  1455. changed_properties.find(FONT_FAMILY) != changed_properties.end() ||
  1456. changed_properties.find(FONT_CHARSET) != changed_properties.end() ||
  1457. changed_properties.find(FONT_WEIGHT) != changed_properties.end() ||
  1458. changed_properties.find(FONT_STYLE) != changed_properties.end() ||
  1459. changed_properties.find(FONT_SIZE) != changed_properties.end())
  1460. {
  1461. // Store the old em; if it changes, then we need to dirty all em-relative properties.
  1462. int old_em = -1;
  1463. if (font_face_handle != NULL)
  1464. old_em = font_face_handle->GetLineHeight();
  1465. // Fetch the new font face.
  1466. FontFaceHandle * new_font_face_handle = ElementUtilities::GetFontFaceHandle(element_meta->computed_values);
  1467. // If this is different from our current font face, then we've got to nuke
  1468. // all our characters and tell our parent that we have to be re-laid out.
  1469. if (new_font_face_handle != font_face_handle)
  1470. {
  1471. if (font_face_handle)
  1472. font_face_handle->RemoveReference();
  1473. font_face_handle = new_font_face_handle;
  1474. // Our font face has changed; odds are, so has our em. All of our em-relative values
  1475. // have therefore probably changed as well, so we'll need to dirty them.
  1476. int new_em = -1;
  1477. if (font_face_handle != NULL)
  1478. new_em = font_face_handle->GetLineHeight();
  1479. // However, if all properties are dirty, we don't need to perform this expensive
  1480. // step as all properties are dirtied below anyway.
  1481. if (old_em != new_em && !all_dirty)
  1482. {
  1483. style->DirtyEmProperties();
  1484. }
  1485. }
  1486. else if (new_font_face_handle != NULL)
  1487. new_font_face_handle->RemoveReference();
  1488. }
  1489. // Update the position.
  1490. if (all_dirty ||
  1491. changed_properties.find(LEFT) != changed_properties.end() ||
  1492. changed_properties.find(RIGHT) != changed_properties.end() ||
  1493. changed_properties.find(TOP) != changed_properties.end() ||
  1494. changed_properties.find(BOTTOM) != changed_properties.end())
  1495. {
  1496. UpdateOffset();
  1497. DirtyOffset();
  1498. }
  1499. // Update the z-index.
  1500. if (all_dirty ||
  1501. changed_properties.find(Z_INDEX) != changed_properties.end())
  1502. {
  1503. Style::ZIndex z_index_property = element_meta->computed_values.z_index;
  1504. if (z_index_property.type == Style::ZIndex::Auto)
  1505. {
  1506. if (local_stacking_context &&
  1507. !local_stacking_context_forced)
  1508. {
  1509. // We're no longer acting as a stacking context.
  1510. local_stacking_context = false;
  1511. stacking_context_dirty = false;
  1512. stacking_context.clear();
  1513. }
  1514. // If our old z-index was not zero, then we must dirty our stacking context so we'll be re-indexed.
  1515. if (z_index != 0)
  1516. {
  1517. z_index = 0;
  1518. DirtyStackingContext();
  1519. }
  1520. }
  1521. else
  1522. {
  1523. float new_z_index = z_index_property.value;
  1524. if (new_z_index != z_index)
  1525. {
  1526. z_index = new_z_index;
  1527. if (parent != NULL)
  1528. parent->DirtyStackingContext();
  1529. }
  1530. if (!local_stacking_context)
  1531. {
  1532. local_stacking_context = true;
  1533. stacking_context_dirty = true;
  1534. }
  1535. }
  1536. }
  1537. // Dirty the background if it's changed.
  1538. if (all_dirty ||
  1539. changed_properties.find(BACKGROUND_COLOR) != changed_properties.end() ||
  1540. changed_properties.find(OPACITY) != changed_properties.end() ||
  1541. changed_properties.find(IMAGE_COLOR) != changed_properties.end()) {
  1542. background->DirtyBackground();
  1543. decoration->DirtyDecorators(true);
  1544. }
  1545. // Dirty the border if it's changed.
  1546. if (all_dirty ||
  1547. changed_properties.find(BORDER_TOP_WIDTH) != changed_properties.end() ||
  1548. changed_properties.find(BORDER_RIGHT_WIDTH) != changed_properties.end() ||
  1549. changed_properties.find(BORDER_BOTTOM_WIDTH) != changed_properties.end() ||
  1550. changed_properties.find(BORDER_LEFT_WIDTH) != changed_properties.end() ||
  1551. changed_properties.find(BORDER_TOP_COLOR) != changed_properties.end() ||
  1552. changed_properties.find(BORDER_RIGHT_COLOR) != changed_properties.end() ||
  1553. changed_properties.find(BORDER_BOTTOM_COLOR) != changed_properties.end() ||
  1554. changed_properties.find(BORDER_LEFT_COLOR) != changed_properties.end() ||
  1555. changed_properties.find(OPACITY) != changed_properties.end())
  1556. border->DirtyBorder();
  1557. // Check for clipping state changes
  1558. if (all_dirty ||
  1559. changed_properties.find(CLIP) != changed_properties.end() ||
  1560. changed_properties.find(OVERFLOW_X) != changed_properties.end() ||
  1561. changed_properties.find(OVERFLOW_Y) != changed_properties.end())
  1562. {
  1563. clipping_state_dirty = true;
  1564. }
  1565. // Check for `perspective' and `perspective-origin' changes
  1566. if (all_dirty ||
  1567. changed_properties.find(PERSPECTIVE) != changed_properties.end() ||
  1568. changed_properties.find(PERSPECTIVE_ORIGIN_X) != changed_properties.end() ||
  1569. changed_properties.find(PERSPECTIVE_ORIGIN_Y) != changed_properties.end())
  1570. {
  1571. DirtyTransformState(true, false, false);
  1572. }
  1573. // Check for `transform' and `transform-origin' changes
  1574. if (all_dirty ||
  1575. changed_properties.find(TRANSFORM) != changed_properties.end() ||
  1576. changed_properties.find(TRANSFORM_ORIGIN_X) != changed_properties.end() ||
  1577. changed_properties.find(TRANSFORM_ORIGIN_Y) != changed_properties.end() ||
  1578. changed_properties.find(TRANSFORM_ORIGIN_Z) != changed_properties.end())
  1579. {
  1580. DirtyTransformState(false, true, false);
  1581. }
  1582. // Check for `animation' changes
  1583. if (all_dirty || changed_properties.find(ANIMATION) != changed_properties.end())
  1584. {
  1585. DirtyAnimation();
  1586. }
  1587. }
  1588. void Element::DirtyProperties(const PropertyNameList& changed_properties)
  1589. {
  1590. if (all_properties_dirty)
  1591. return;
  1592. dirty_properties.insert(changed_properties.begin(), changed_properties.end());
  1593. }
  1594. void Element::UpdateDirtyProperties()
  1595. {
  1596. if (!all_properties_dirty && dirty_properties.empty())
  1597. return;
  1598. auto& update_properties = (all_properties_dirty ? StyleSheetSpecification::GetRegisteredProperties() : dirty_properties);
  1599. OnPropertyChange(update_properties);
  1600. all_properties_dirty = false;
  1601. dirty_properties.clear();
  1602. }
  1603. // Called when a child node has been added somewhere in the hierarchy
  1604. void Element::OnChildAdd(Element* child)
  1605. {
  1606. if (parent)
  1607. parent->OnChildAdd(child);
  1608. }
  1609. // Called when a child node has been removed somewhere in the hierarchy
  1610. void Element::OnChildRemove(Element* child)
  1611. {
  1612. if (parent)
  1613. parent->OnChildRemove(child);
  1614. }
  1615. // Forces a re-layout of this element, and any other children required.
  1616. void Element::DirtyLayout()
  1617. {
  1618. Element* document = GetOwnerDocument();
  1619. if (document != NULL)
  1620. document->DirtyLayout();
  1621. }
  1622. /// Increment/Decrement the layout lock
  1623. void Element::LockLayout(bool lock)
  1624. {
  1625. ElementDocument* document = GetOwnerDocument();
  1626. if (document != NULL)
  1627. document->LockLayout(lock);
  1628. }
  1629. // Forces a re-layout of this element, and any other children required.
  1630. bool Element::IsLayoutDirty()
  1631. {
  1632. Element* document = GetOwnerDocument();
  1633. if (document != NULL)
  1634. return document->IsLayoutDirty();
  1635. return false;
  1636. }
  1637. // Forces a reevaluation of applicable font effects.
  1638. void Element::DirtyFont()
  1639. {
  1640. for (size_t i = 0; i < children.size(); ++i)
  1641. children[i]->DirtyFont();
  1642. }
  1643. void Element::OnReferenceDeactivate()
  1644. {
  1645. if (instancer)
  1646. {
  1647. instancer->ReleaseElement(this);
  1648. }
  1649. else
  1650. {
  1651. // Hopefully we can just delete ourselves.
  1652. //delete this;
  1653. Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via Rocket Factory. Unable to release.", GetAddress().c_str());
  1654. }
  1655. }
  1656. void Element::ProcessEvent(Event& event)
  1657. {
  1658. if (event == MOUSEDOWN && IsPointWithinElement(Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0))) &&
  1659. event.GetParameter< int >("button", 0) == 0)
  1660. SetPseudoClass("active", true);
  1661. if (event == MOUSESCROLL)
  1662. {
  1663. if (GetScrollHeight() > GetClientHeight())
  1664. {
  1665. Style::Overflow overflow_property = element_meta->computed_values.overflow_y;
  1666. if (overflow_property == Style::Overflow::Auto ||
  1667. overflow_property == Style::Overflow::Scroll)
  1668. {
  1669. // Stop the propagation if the current element has scrollbars.
  1670. // This prevents scrolling in parent elements, which is often unintended. If instead desired behavior is
  1671. // to scroll in parent elements when reaching top/bottom, move StopPropagation inside the next if statement.
  1672. event.StopPropagation();
  1673. int wheel_delta = event.GetParameter< int >("wheel_delta", 0);
  1674. if ((wheel_delta < 0 && GetScrollTop() > 0) ||
  1675. (wheel_delta > 0 && GetScrollHeight() > GetScrollTop() + GetClientHeight()))
  1676. {
  1677. SetScrollTop(GetScrollTop() + wheel_delta * GetLineHeight());
  1678. }
  1679. }
  1680. }
  1681. return;
  1682. }
  1683. if (event.GetTargetElement() == this)
  1684. {
  1685. if (event == MOUSEOVER)
  1686. SetPseudoClass("hover", true);
  1687. else if (event == MOUSEOUT)
  1688. SetPseudoClass("hover", false);
  1689. else if (event == FOCUS)
  1690. SetPseudoClass(FOCUS, true);
  1691. else if (event == BLUR)
  1692. SetPseudoClass(FOCUS, false);
  1693. }
  1694. }
  1695. const Style::ComputedValues& Element::GetComputedValues() const
  1696. {
  1697. return element_meta->computed_values;
  1698. }
  1699. void Element::GetRML(String& content)
  1700. {
  1701. // First we start the open tag, add the attributes then close the open tag.
  1702. // Then comes the children in order, then we add our close tag.
  1703. content += "<";
  1704. content += tag;
  1705. for( auto& [name, variant] : attributes)
  1706. {
  1707. String value;
  1708. if (variant.GetInto(value))
  1709. content += " " + name + "=\"" + value + "\"";
  1710. }
  1711. if (HasChildNodes())
  1712. {
  1713. content += ">";
  1714. GetInnerRML(content);
  1715. content += "</";
  1716. content += tag;
  1717. content += ">";
  1718. }
  1719. else
  1720. {
  1721. content += " />";
  1722. }
  1723. }
  1724. void Element::SetParent(Element* _parent)
  1725. {
  1726. // If there's an old parent, detach from it first.
  1727. if (parent &&
  1728. parent != _parent)
  1729. parent->RemoveChild(this);
  1730. // Save our parent
  1731. parent = _parent;
  1732. }
  1733. void Element::ReleaseDeletedElements()
  1734. {
  1735. for (size_t i = 0; i < active_children.size(); i++)
  1736. {
  1737. active_children[i]->ReleaseDeletedElements();
  1738. }
  1739. ReleaseElements(deleted_children);
  1740. active_children = children;
  1741. }
  1742. void Element::ReleaseElements(ElementList& released_elements)
  1743. {
  1744. // Remove deleted children from this element.
  1745. while (!released_elements.empty())
  1746. {
  1747. Element* element = released_elements.back();
  1748. released_elements.pop_back();
  1749. // If this element has been added back into our list, then we remove our previous oustanding reference on it
  1750. // and continue.
  1751. if (std::find(children.begin(), children.end(), element) != children.end())
  1752. {
  1753. element->RemoveReference();
  1754. continue;
  1755. }
  1756. // Set the parent to NULL unless it's been reparented already.
  1757. if (element->GetParentNode() == this)
  1758. element->parent = NULL;
  1759. element->RemoveReference();
  1760. }
  1761. }
  1762. void Element::DirtyOffset()
  1763. {
  1764. offset_dirty = true;
  1765. if(transform_state)
  1766. DirtyTransformState(true, true, false);
  1767. // Not strictly true ... ?
  1768. for (size_t i = 0; i < children.size(); i++)
  1769. children[i]->DirtyOffset();
  1770. }
  1771. void Element::UpdateOffset()
  1772. {
  1773. using namespace Style;
  1774. const auto& computed = element_meta->computed_values;
  1775. Position position_property = computed.position;
  1776. if (position_property == Position::Absolute ||
  1777. position_property == Position::Fixed)
  1778. {
  1779. if (offset_parent != NULL)
  1780. {
  1781. const Box& parent_box = offset_parent->GetBox();
  1782. Vector2f containing_block = parent_box.GetSize(Box::PADDING);
  1783. // If the element is anchored left, then the position is offset by that resolved value.
  1784. if (computed.left.type != Left::Auto)
  1785. relative_offset_base.x = parent_box.GetEdge(Box::BORDER, Box::LEFT) + (ResolveValue(computed.left, containing_block.x) + GetBox().GetEdge(Box::MARGIN, Box::LEFT));
  1786. // If the element is anchored right, then the position is set first so the element's right-most edge
  1787. // (including margins) will render up against the containing box's right-most content edge, and then
  1788. // offset by the resolved value.
  1789. else if (computed.right.type != Right::Auto)
  1790. 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));
  1791. // If the element is anchored top, then the position is offset by that resolved value.
  1792. if (computed.top.type != Top::Auto)
  1793. relative_offset_base.y = parent_box.GetEdge(Box::BORDER, Box::TOP) + (ResolveValue(computed.top, containing_block.y) + GetBox().GetEdge(Box::MARGIN, Box::TOP));
  1794. // If the element is anchored bottom, then the position is set first so the element's right-most edge
  1795. // (including margins) will render up against the containing box's right-most content edge, and then
  1796. // offset by the resolved value.
  1797. else if (computed.bottom.type != Bottom::Auto)
  1798. 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));
  1799. }
  1800. }
  1801. else if (position_property == Position::Relative)
  1802. {
  1803. if (offset_parent != NULL)
  1804. {
  1805. const Box& parent_box = offset_parent->GetBox();
  1806. Vector2f containing_block = parent_box.GetSize();
  1807. if (computed.left.type != Left::Auto)
  1808. relative_offset_position.x = ResolveValue(computed.left, containing_block.x);
  1809. else if (computed.right.type != Right::Auto)
  1810. relative_offset_position.x = -1 * ResolveValue(computed.right, containing_block.x);
  1811. else
  1812. relative_offset_position.x = 0;
  1813. if (computed.top.type != Top::Auto)
  1814. relative_offset_position.y = ResolveValue(computed.top, containing_block.y);
  1815. else if (computed.bottom.type != Bottom::Auto)
  1816. relative_offset_position.y = -1 * ResolveValue(computed.bottom, containing_block.y);
  1817. else
  1818. relative_offset_position.y = 0;
  1819. }
  1820. }
  1821. else
  1822. {
  1823. relative_offset_position.x = 0;
  1824. relative_offset_position.y = 0;
  1825. }
  1826. }
  1827. void Element::BuildLocalStackingContext()
  1828. {
  1829. stacking_context_dirty = false;
  1830. stacking_context.clear();
  1831. BuildStackingContext(&stacking_context);
  1832. std::stable_sort(stacking_context.begin(), stacking_context.end(), ElementSortZIndex());
  1833. }
  1834. void Element::BuildStackingContext(ElementList* new_stacking_context)
  1835. {
  1836. // Build the list of ordered children. Our child list is sorted within the stacking context so stacked elements
  1837. // will render in the right order; ie, positioned elements will render on top of inline elements, which will render
  1838. // on top of floated elements, which will render on top of block elements.
  1839. std::vector< std::pair< Element*, float > > ordered_children;
  1840. for (size_t i = 0; i < children.size(); ++i)
  1841. {
  1842. Element* child = children[i];
  1843. if (!child->IsVisible())
  1844. continue;
  1845. std::pair< Element*, float > ordered_child;
  1846. ordered_child.first = child;
  1847. if (child->GetPosition() != Style::Position::Static)
  1848. ordered_child.second = 3;
  1849. else if (child->GetFloat() != Style::Float::None)
  1850. ordered_child.second = 1;
  1851. else if (child->GetDisplay() == Style::Display::Block)
  1852. ordered_child.second = 0;
  1853. else
  1854. ordered_child.second = 2;
  1855. ordered_children.push_back(ordered_child);
  1856. }
  1857. // Sort the list!
  1858. std::stable_sort(ordered_children.begin(), ordered_children.end(), ElementSortZOrder());
  1859. // Add the list of ordered children into the stacking context in order.
  1860. for (size_t i = 0; i < ordered_children.size(); ++i)
  1861. {
  1862. new_stacking_context->push_back(ordered_children[i].first);
  1863. if (!ordered_children[i].first->local_stacking_context)
  1864. ordered_children[i].first->BuildStackingContext(new_stacking_context);
  1865. }
  1866. }
  1867. void Element::DirtyStackingContext()
  1868. {
  1869. // The first ancestor of ours that doesn't have an automatic z-index is the ancestor that is establishing our local
  1870. // stacking context.
  1871. Element* stacking_context_parent = this;
  1872. while (stacking_context_parent != NULL &&
  1873. !stacking_context_parent->local_stacking_context)
  1874. stacking_context_parent = stacking_context_parent->GetParentNode();
  1875. if (stacking_context_parent != NULL)
  1876. stacking_context_parent->stacking_context_dirty = true;
  1877. }
  1878. void Element::DirtyStructure()
  1879. {
  1880. // Clear the cached owner document
  1881. owner_document = NULL;
  1882. structure_dirty = true;
  1883. }
  1884. void Element::DirtyParentStructure()
  1885. {
  1886. owner_document = NULL;
  1887. parent_structure_dirty = true;
  1888. }
  1889. void Element::UpdateStructure()
  1890. {
  1891. if (parent_structure_dirty)
  1892. {
  1893. // If children depend on structured selectors, they may need to be updated
  1894. const ElementDefinition* element_definition = GetStyle()->GetDefinition();
  1895. if (element_definition != NULL && element_definition->IsStructurallyVolatile())
  1896. {
  1897. GetStyle()->DirtyDefinition();
  1898. }
  1899. }
  1900. if (structure_dirty || parent_structure_dirty)
  1901. {
  1902. for (size_t i = 0; i < children.size(); ++i)
  1903. children[i]->DirtyParentStructure();
  1904. structure_dirty = false;
  1905. parent_structure_dirty = false;
  1906. }
  1907. }
  1908. 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)
  1909. {
  1910. bool result = false;
  1911. if (auto it_animation = StartAnimation(property_name, start_value, num_iterations, alternate_direction, delay); it_animation != animations.end())
  1912. {
  1913. result = it_animation->AddKey(duration, target_value, *this, tween, true);
  1914. if (!result)
  1915. animations.erase(it_animation);
  1916. }
  1917. return result;
  1918. }
  1919. bool Element::AddAnimationKey(const String & property_name, const Property & target_value, float duration, Tween tween)
  1920. {
  1921. ElementAnimation* animation = nullptr;
  1922. for (auto& existing_animation : animations) {
  1923. if (existing_animation.GetPropertyName() == property_name) {
  1924. animation = &existing_animation;
  1925. break;
  1926. }
  1927. }
  1928. if (!animation)
  1929. return false;
  1930. bool result = animation->AddKey(animation->GetDuration() + duration, target_value, *this, tween, true);
  1931. return result;
  1932. }
  1933. ElementAnimationList::iterator Element::StartAnimation(const String & property_name, const Property* start_value, int num_iterations, bool alternate_direction, float delay)
  1934. {
  1935. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyName() == property_name; });
  1936. if (it == animations.end())
  1937. {
  1938. animations.emplace_back();
  1939. it = animations.end() - 1;
  1940. }
  1941. Property value;
  1942. if (start_value)
  1943. {
  1944. value = *start_value;
  1945. if (!value.definition)
  1946. if(auto default_value = GetProperty(property_name))
  1947. value.definition = default_value->definition;
  1948. }
  1949. else if (auto default_value = GetProperty(property_name))
  1950. {
  1951. value = *default_value;
  1952. }
  1953. if (value.definition)
  1954. {
  1955. double start_time = Clock::GetElapsedTime() + (double)delay;
  1956. *it = ElementAnimation{ property_name, value, start_time, 0.0f, num_iterations, alternate_direction, false };
  1957. }
  1958. else
  1959. {
  1960. animations.erase(it);
  1961. it = animations.end();
  1962. }
  1963. return it;
  1964. }
  1965. bool Element::AddAnimationKeyTime(const String & property_name, const Property* target_value, float time, Tween tween)
  1966. {
  1967. if (!target_value)
  1968. target_value = GetProperty(property_name);
  1969. if (!target_value)
  1970. return false;
  1971. ElementAnimation* animation = nullptr;
  1972. for (auto& existing_animation : animations) {
  1973. if (existing_animation.GetPropertyName() == property_name) {
  1974. animation = &existing_animation;
  1975. break;
  1976. }
  1977. }
  1978. if (!animation)
  1979. return false;
  1980. bool result = animation->AddKey(time, *target_value, *this, tween, true);
  1981. return result;
  1982. }
  1983. bool Element::StartTransition(const Transition & transition, const Property& start_value, const Property & target_value)
  1984. {
  1985. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyName() == transition.name; });
  1986. if (it != animations.end() && !it->IsTransition())
  1987. return false;
  1988. float duration = transition.duration;
  1989. double start_time = Clock::GetElapsedTime() + (double)transition.delay;
  1990. if (it == animations.end())
  1991. {
  1992. // Add transition as new animation
  1993. animations.push_back(
  1994. ElementAnimation{ transition.name, start_value, start_time, 0.0f, 1, false, true }
  1995. );
  1996. it = (animations.end() - 1);
  1997. }
  1998. else
  1999. {
  2000. // Compress the duration based on the progress of the current animation
  2001. float f = it->GetInterpolationFactor();
  2002. f = 1.0f - (1.0f - f)*transition.reverse_adjustment_factor;
  2003. duration = duration * f;
  2004. // Replace old transition
  2005. *it = ElementAnimation{ transition.name, start_value, start_time, 0.0f, 1, false, true };
  2006. }
  2007. bool result = it->AddKey(duration, target_value, *this, transition.tween, true);
  2008. if (result)
  2009. SetProperty(transition.name, start_value);
  2010. else
  2011. animations.erase(it);
  2012. return result;
  2013. }
  2014. void Element::DirtyAnimation()
  2015. {
  2016. dirty_animation = true;
  2017. }
  2018. void Element::UpdateAnimation()
  2019. {
  2020. if (dirty_animation)
  2021. {
  2022. const auto& animation_list = element_meta->computed_values.animation;
  2023. StyleSheet* stylesheet = nullptr;
  2024. if (!animation_list.empty() && (stylesheet = GetStyleSheet()))
  2025. {
  2026. for (auto& animation : animation_list)
  2027. {
  2028. Keyframes* keyframes_ptr = stylesheet->GetKeyframes(animation.name);
  2029. if (keyframes_ptr && keyframes_ptr->blocks.size() >= 1 && !animation.paused)
  2030. {
  2031. auto& property_names = keyframes_ptr->property_names;
  2032. auto& blocks = keyframes_ptr->blocks;
  2033. bool has_from_key = (blocks[0].normalized_time == 0);
  2034. bool has_to_key = (blocks.back().normalized_time == 1);
  2035. // If the first key defines initial conditions for a given property, use those values, else, use this element's current values.
  2036. for (auto& property : property_names)
  2037. StartAnimation(property, (has_from_key ? blocks[0].properties.GetProperty(property) : nullptr), animation.num_iterations, animation.alternate, animation.delay);
  2038. // Need to skip the first and last keys if they set the initial and end conditions, respectively.
  2039. for (int i = (has_from_key ? 1 : 0); i < (int)blocks.size() + (has_to_key ? -1 : 0); i++)
  2040. {
  2041. // Add properties of current key to animation
  2042. float time = blocks[i].normalized_time * animation.duration;
  2043. for (auto& property : blocks[i].properties.GetProperties())
  2044. AddAnimationKeyTime(property.first, &property.second, time, animation.tween);
  2045. }
  2046. // If the last key defines end conditions for a given property, use those values, else, use this element's current values.
  2047. float time = animation.duration;
  2048. for (auto& property : property_names)
  2049. AddAnimationKeyTime(property, (has_to_key ? blocks.back().properties.GetProperty(property) : nullptr), time, animation.tween);
  2050. }
  2051. }
  2052. }
  2053. dirty_animation = false;
  2054. }
  2055. }
  2056. void Element::AdvanceAnimations()
  2057. {
  2058. if (!animations.empty())
  2059. {
  2060. double time = Clock::GetElapsedTime();
  2061. for (auto& animation : animations)
  2062. {
  2063. Property property = animation.UpdateAndGetProperty(time, *this);
  2064. if (property.unit != Property::UNKNOWN)
  2065. SetProperty(animation.GetPropertyName(), property);
  2066. }
  2067. auto it_completed = std::remove_if(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return animation.IsComplete(); });
  2068. std::vector<Dictionary> dictionary_list;
  2069. std::vector<bool> is_transition;
  2070. dictionary_list.reserve(animations.end() - it_completed);
  2071. is_transition.reserve(animations.end() - it_completed);
  2072. for (auto it = it_completed; it != animations.end(); ++it)
  2073. {
  2074. dictionary_list.emplace_back().emplace("property", it->GetPropertyName());
  2075. is_transition.push_back(it->IsTransition());
  2076. }
  2077. // Need to erase elements before submitting event, as iterators might be invalidated when calling external code.
  2078. animations.erase(it_completed, animations.end());
  2079. for (size_t i = 0; i < dictionary_list.size(); i++)
  2080. DispatchEvent(is_transition[i] ? TRANSITIONEND : ANIMATIONEND, dictionary_list[i]);
  2081. }
  2082. }
  2083. void Element::DirtyTransformState(bool perspective_changed, bool transform_changed, bool parent_transform_changed)
  2084. {
  2085. for (size_t i = 0; i < children.size(); ++i)
  2086. {
  2087. children[i]->DirtyTransformState(false, false, transform_changed || parent_transform_changed);
  2088. }
  2089. if (perspective_changed)
  2090. {
  2091. this->transform_state_perspective_dirty = true;
  2092. }
  2093. if (transform_changed)
  2094. {
  2095. this->transform_state_transform_dirty = true;
  2096. }
  2097. if (parent_transform_changed)
  2098. {
  2099. this->transform_state_parent_transform_dirty = true;
  2100. }
  2101. }
  2102. void Element::UpdateTransformState()
  2103. {
  2104. if (!(transform_state_perspective_dirty || transform_state_transform_dirty || transform_state_parent_transform_dirty))
  2105. {
  2106. return;
  2107. }
  2108. const ComputedValues& computed = element_meta->computed_values;
  2109. if (!computed.transform && computed.perspective <= 0)
  2110. {
  2111. transform_state.reset();
  2112. transform_state_perspective_dirty = false;
  2113. transform_state_transform_dirty = false;
  2114. transform_state_parent_transform_dirty = false;
  2115. return;
  2116. }
  2117. if(transform_state_perspective_dirty || transform_state_transform_dirty)
  2118. {
  2119. Context *context = GetContext();
  2120. Vector2f pos = GetAbsoluteOffset(Box::BORDER);
  2121. Vector2f size = GetBox().GetSize(Box::BORDER);
  2122. if (transform_state_perspective_dirty)
  2123. {
  2124. bool have_perspective = false;
  2125. TransformState::Perspective perspective_value;
  2126. perspective_value.vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
  2127. if (computed.perspective > 0.0f)
  2128. {
  2129. have_perspective = true;
  2130. // Compute the perspective value
  2131. perspective_value.distance = computed.perspective;
  2132. // Compute the perspective origin, if necessary
  2133. if (computed.perspective_origin_x.type == Style::PerspectiveOrigin::Percentage)
  2134. perspective_value.vanish.x = pos.x + computed.perspective_origin_x.value * 0.01f * size.x;
  2135. else
  2136. perspective_value.vanish.x = pos.x + computed.perspective_origin_x.value;
  2137. if (computed.perspective_origin_y.type == Style::PerspectiveOrigin::Percentage)
  2138. perspective_value.vanish.y = pos.y + computed.perspective_origin_y.value * 0.01f * size.y;
  2139. else
  2140. perspective_value.vanish.y = pos.y + computed.perspective_origin_y.value;
  2141. }
  2142. if (have_perspective && context)
  2143. {
  2144. if (!transform_state)
  2145. transform_state = std::make_unique<TransformState>();
  2146. perspective_value.view_size = context->GetDimensions();
  2147. transform_state->SetPerspective(&perspective_value);
  2148. }
  2149. else if (transform_state)
  2150. {
  2151. transform_state->SetPerspective(nullptr);
  2152. }
  2153. transform_state_perspective_dirty = false;
  2154. }
  2155. if (transform_state_transform_dirty)
  2156. {
  2157. bool have_local_perspective = false;
  2158. TransformState::LocalPerspective local_perspective;
  2159. bool have_transform = false;
  2160. Matrix4f transform_value = Matrix4f::Identity();
  2161. Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
  2162. if (computed.transform)
  2163. {
  2164. int n = computed.transform->GetNumPrimitives();
  2165. for (int i = 0; i < n; ++i)
  2166. {
  2167. const Transforms::Primitive &primitive = computed.transform->GetPrimitive(i);
  2168. if (primitive.ResolvePerspective(local_perspective.distance, *this))
  2169. {
  2170. have_local_perspective = true;
  2171. }
  2172. Matrix4f matrix;
  2173. if (primitive.ResolveTransform(matrix, *this))
  2174. {
  2175. transform_value *= matrix;
  2176. have_transform = true;
  2177. }
  2178. }
  2179. // Compute the transform origin
  2180. if (computed.transform_origin_x.type == Style::TransformOrigin::Percentage)
  2181. transform_origin.x = pos.x + computed.transform_origin_x.value * size.x * 0.01f;
  2182. else
  2183. transform_origin.x = pos.x + computed.transform_origin_x.value;
  2184. if (computed.transform_origin_y.type == Style::TransformOrigin::Percentage)
  2185. transform_origin.y = pos.y + computed.transform_origin_y.value * size.y * 0.01f;
  2186. else
  2187. transform_origin.y = pos.y + computed.transform_origin_y.value;
  2188. transform_origin.z = computed.transform_origin_z;
  2189. }
  2190. if (have_local_perspective && context)
  2191. {
  2192. if (!transform_state)
  2193. transform_state = std::make_unique<TransformState>();
  2194. local_perspective.view_size = context->GetDimensions();
  2195. transform_state->SetLocalPerspective(&local_perspective);
  2196. }
  2197. else if(transform_state)
  2198. {
  2199. transform_state->SetLocalPerspective(nullptr);
  2200. }
  2201. if (have_transform)
  2202. {
  2203. // TODO: If we're using the global projection matrix
  2204. // (perspective < 0), then scale the coordinates from
  2205. // pixel space to 3D unit space.
  2206. // Transform the Rocket context so that the computed `transform_origin'
  2207. // lies at the coordinate system origin.
  2208. transform_value =
  2209. Matrix4f::Translate(transform_origin)
  2210. * transform_value
  2211. * Matrix4f::Translate(-transform_origin);
  2212. if (!transform_state)
  2213. transform_state = std::make_unique<TransformState>();
  2214. transform_state->SetTransform(&transform_value);
  2215. }
  2216. else if (transform_state)
  2217. {
  2218. transform_state->SetTransform(nullptr);
  2219. }
  2220. transform_state_transform_dirty = false;
  2221. }
  2222. }
  2223. if (transform_state_parent_transform_dirty)
  2224. {
  2225. // We need to clean up from the top-most to the bottom-most dirt.
  2226. if (parent)
  2227. {
  2228. parent->UpdateTransformState();
  2229. }
  2230. if (transform_state)
  2231. {
  2232. // Store the parent's new full transform as our parent transform
  2233. Element *node = nullptr;
  2234. Matrix4f parent_transform;
  2235. for (node = parent; node; node = node->parent)
  2236. {
  2237. if (node->GetTransformState() && node->GetTransformState()->GetRecursiveTransform(&parent_transform))
  2238. {
  2239. transform_state->SetParentRecursiveTransform(&parent_transform);
  2240. break;
  2241. }
  2242. }
  2243. if (!node)
  2244. {
  2245. transform_state->SetParentRecursiveTransform(nullptr);
  2246. }
  2247. }
  2248. transform_state_parent_transform_dirty = false;
  2249. }
  2250. // If we neither have a local perspective, nor a perspective nor a
  2251. // transform, we don't need to keep the large TransformState object
  2252. // around. GetEffectiveTransformState() will then recursively visit
  2253. // parents in order to find a non-trivial TransformState.
  2254. if (transform_state && !transform_state->GetLocalPerspective(nullptr) && !transform_state->GetPerspective(nullptr) && !transform_state->GetTransform(nullptr))
  2255. {
  2256. transform_state.reset();
  2257. }
  2258. }
  2259. }
  2260. }