Element.cpp 72 KB

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