Element.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692
  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. ElementStyleIterator Element::IteratePropertiesBegin() const
  733. {
  734. return style->begin();
  735. }
  736. ElementStyleIterator Element::IteratePropertiesEnd() const
  737. {
  738. return style->end();
  739. }
  740. // Sets or removes a pseudo-class on the element.
  741. void Element::SetPseudoClass(const String& pseudo_class, bool activate)
  742. {
  743. style->SetPseudoClass(pseudo_class, activate);
  744. }
  745. // Checks if a specific pseudo-class has been set on the element.
  746. bool Element::IsPseudoClassSet(const String& pseudo_class) const
  747. {
  748. return style->IsPseudoClassSet(pseudo_class);
  749. }
  750. // Checks if a complete set of pseudo-classes are set on the element.
  751. bool Element::ArePseudoClassesSet(const PseudoClassList& pseudo_classes) const
  752. {
  753. for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
  754. {
  755. if (!IsPseudoClassSet(*i))
  756. return false;
  757. }
  758. return true;
  759. }
  760. // Gets a list of the current active pseudo classes
  761. const PseudoClassList& Element::GetActivePseudoClasses() const
  762. {
  763. return style->GetActivePseudoClasses();
  764. }
  765. /// Get the named attribute
  766. Variant* Element::GetAttribute(const String& name)
  767. {
  768. return GetIf(attributes, name);
  769. }
  770. // Checks if the element has a certain attribute.
  771. bool Element::HasAttribute(const String& name) const
  772. {
  773. return attributes.find(name) != attributes.end();
  774. }
  775. // Removes an attribute from the element
  776. void Element::RemoveAttribute(const String& name)
  777. {
  778. auto it = attributes.find(name);
  779. if (it != attributes.end())
  780. {
  781. attributes.erase(it);
  782. AttributeNameList changed_attributes;
  783. changed_attributes.insert(name);
  784. OnAttributeChange(changed_attributes);
  785. }
  786. }
  787. // Gets the outer most focus element down the tree from this node
  788. Element* Element::GetFocusLeafNode()
  789. {
  790. // If there isn't a focus, then we are the leaf.
  791. if (!focus)
  792. {
  793. return this;
  794. }
  795. // Recurse down the tree until we found the leaf focus element
  796. Element* focus_element = focus;
  797. while (focus_element->focus)
  798. focus_element = focus_element->focus;
  799. return focus_element;
  800. }
  801. // Returns the element's context.
  802. Context* Element::GetContext()
  803. {
  804. ElementDocument* document = GetOwnerDocument();
  805. if (document != NULL)
  806. return document->GetContext();
  807. return NULL;
  808. }
  809. // Set a group of attributes
  810. void Element::SetAttributes(const ElementAttributes* _attributes)
  811. {
  812. attributes.reserve(attributes.size() + _attributes->size());
  813. for (auto& pair : *_attributes)
  814. attributes[pair.first] = pair.second;
  815. AttributeNameList changed_attributes;
  816. changed_attributes.reserve(_attributes->size());
  817. for (auto& pair : *_attributes)
  818. changed_attributes.insert(pair.first);
  819. OnAttributeChange(changed_attributes);
  820. }
  821. // Returns the number of attributes on the element.
  822. int Element::GetNumAttributes() const
  823. {
  824. return (int)attributes.size();
  825. }
  826. // Iterates over all decorators attached to the element.
  827. bool Element::IterateDecorators(int& index, PseudoClassList& pseudo_classes, String& name, Decorator*& decorator, DecoratorDataHandle& decorator_data)
  828. {
  829. return decoration->IterateDecorators(index, pseudo_classes, name, decorator, decorator_data);
  830. }
  831. // Gets the name of the element.
  832. const String& Element::GetTagName() const
  833. {
  834. return tag;
  835. }
  836. // Gets the ID of the element.
  837. const String& Element::GetId() const
  838. {
  839. return id;
  840. }
  841. // Sets the ID of the element.
  842. void Element::SetId(const String& _id)
  843. {
  844. SetAttribute("id", _id);
  845. }
  846. // Gets the horizontal offset from the context's left edge to element's left border edge.
  847. float Element::GetAbsoluteLeft()
  848. {
  849. return GetAbsoluteOffset(Box::BORDER).x;
  850. }
  851. // Gets the vertical offset from the context's top edge to element's top border edge.
  852. float Element::GetAbsoluteTop()
  853. {
  854. return GetAbsoluteOffset(Box::BORDER).y;
  855. }
  856. // Gets the width of the left border of an element.
  857. float Element::GetClientLeft()
  858. {
  859. return GetBox().GetPosition(client_area).x;
  860. }
  861. // Gets the height of the top border of an element.
  862. float Element::GetClientTop()
  863. {
  864. return GetBox().GetPosition(client_area).y;
  865. }
  866. // Gets the inner width of the element.
  867. float Element::GetClientWidth()
  868. {
  869. return GetBox().GetSize(client_area).x - scroll->GetScrollbarSize(ElementScroll::VERTICAL);
  870. }
  871. // Gets the inner height of the element.
  872. float Element::GetClientHeight()
  873. {
  874. return GetBox().GetSize(client_area).y - scroll->GetScrollbarSize(ElementScroll::HORIZONTAL);
  875. }
  876. // Returns the element from which all offset calculations are currently computed.
  877. Element* Element::GetOffsetParent()
  878. {
  879. return offset_parent;
  880. }
  881. // Gets the distance from this element's left border to its offset parent's left border.
  882. float Element::GetOffsetLeft()
  883. {
  884. return relative_offset_base.x + relative_offset_position.x;
  885. }
  886. // Gets the distance from this element's top border to its offset parent's top border.
  887. float Element::GetOffsetTop()
  888. {
  889. return relative_offset_base.y + relative_offset_position.y;
  890. }
  891. // Gets the width of the element, including the client area, padding, borders and scrollbars, but not margins.
  892. float Element::GetOffsetWidth()
  893. {
  894. return GetBox().GetSize(Box::BORDER).x;
  895. }
  896. // Gets the height of the element, including the client area, padding, borders and scrollbars, but not margins.
  897. float Element::GetOffsetHeight()
  898. {
  899. return GetBox().GetSize(Box::BORDER).y;
  900. }
  901. // Gets the left scroll offset of the element.
  902. float Element::GetScrollLeft()
  903. {
  904. return scroll_offset.x;
  905. }
  906. // Sets the left scroll offset of the element.
  907. void Element::SetScrollLeft(float scroll_left)
  908. {
  909. scroll_offset.x = Math::Clamp(scroll_left, 0.0f, GetScrollWidth() - GetClientWidth());
  910. scroll->UpdateScrollbar(ElementScroll::HORIZONTAL);
  911. DirtyOffset();
  912. DispatchEvent("scroll", Dictionary());
  913. }
  914. // Gets the top scroll offset of the element.
  915. float Element::GetScrollTop()
  916. {
  917. return scroll_offset.y;
  918. }
  919. // Sets the top scroll offset of the element.
  920. void Element::SetScrollTop(float scroll_top)
  921. {
  922. scroll_offset.y = Math::Clamp(scroll_top, 0.0f, GetScrollHeight() - GetClientHeight());
  923. scroll->UpdateScrollbar(ElementScroll::VERTICAL);
  924. DirtyOffset();
  925. DispatchEvent("scroll", Dictionary());
  926. }
  927. // Gets the width of the scrollable content of the element; it includes the element padding but not its margin.
  928. float Element::GetScrollWidth()
  929. {
  930. return Math::Max(content_box.x, GetClientWidth());
  931. }
  932. // Gets the height of the scrollable content of the element; it includes the element padding but not its margin.
  933. float Element::GetScrollHeight()
  934. {
  935. return Math::Max(content_box.y, GetClientHeight());
  936. }
  937. // Gets the object representing the declarations of an element's style attributes.
  938. ElementStyle* Element::GetStyle()
  939. {
  940. return style;
  941. }
  942. // Gets the document this element belongs to.
  943. ElementDocument* Element::GetOwnerDocument()
  944. {
  945. if (parent == NULL)
  946. return NULL;
  947. if (!owner_document)
  948. {
  949. owner_document = parent->GetOwnerDocument();
  950. }
  951. return owner_document;
  952. }
  953. // Gets this element's parent node.
  954. Element* Element::GetParentNode() const
  955. {
  956. return parent;
  957. }
  958. // Gets the element immediately following this one in the tree.
  959. Element* Element::GetNextSibling() const
  960. {
  961. if (parent == NULL)
  962. return NULL;
  963. for (size_t i = 0; i < parent->children.size() - (parent->num_non_dom_children + 1); i++)
  964. {
  965. if (parent->children[i] == this)
  966. return parent->children[i + 1];
  967. }
  968. return NULL;
  969. }
  970. // Gets the element immediately preceding this one in the tree.
  971. Element* Element::GetPreviousSibling() const
  972. {
  973. if (parent == NULL)
  974. return NULL;
  975. for (size_t i = 1; i < parent->children.size() - parent->num_non_dom_children; i++)
  976. {
  977. if (parent->children[i] == this)
  978. return parent->children[i - 1];
  979. }
  980. return NULL;
  981. }
  982. // Returns the first child of this element.
  983. Element* Element::GetFirstChild() const
  984. {
  985. if (GetNumChildren() > 0)
  986. return children[0];
  987. return NULL;
  988. }
  989. // Gets the last child of this element.
  990. Element* Element::GetLastChild() const
  991. {
  992. if (GetNumChildren() > 0)
  993. return *(children.end() - (num_non_dom_children + 1));
  994. return NULL;
  995. }
  996. Element* Element::GetChild(int index) const
  997. {
  998. if (index < 0 || index >= (int) children.size())
  999. return NULL;
  1000. return children[index];
  1001. }
  1002. int Element::GetNumChildren(bool include_non_dom_elements) const
  1003. {
  1004. return (int) children.size() - (include_non_dom_elements ? 0 : num_non_dom_children);
  1005. }
  1006. // Gets the markup and content of the element.
  1007. void Element::GetInnerRML(String& content) const
  1008. {
  1009. for (int i = 0; i < GetNumChildren(); i++)
  1010. {
  1011. children[i]->GetRML(content);
  1012. }
  1013. }
  1014. // Gets the markup and content of the element.
  1015. String Element::GetInnerRML() const {
  1016. String result;
  1017. GetInnerRML(result);
  1018. return result;
  1019. }
  1020. // Sets the markup and content of the element. All existing children will be replaced.
  1021. void Element::SetInnerRML(const String& rml)
  1022. {
  1023. // Remove all DOM children.
  1024. while ((int) children.size() > num_non_dom_children)
  1025. RemoveChild(children.front());
  1026. Factory::InstanceElementText(this, rml);
  1027. }
  1028. // Sets the current element as the focus object.
  1029. bool Element::Focus()
  1030. {
  1031. // Are we allowed focus?
  1032. Style::Focus focus_property = element_meta->computed_values.focus;
  1033. if (focus_property == Style::Focus::None)
  1034. return false;
  1035. // Ask our context if we can switch focus.
  1036. Context* context = GetContext();
  1037. if (context == NULL)
  1038. return false;
  1039. if (!context->OnFocusChange(this))
  1040. return false;
  1041. // Set this as the end of the focus chain.
  1042. focus = NULL;
  1043. // Update the focus chain up the hierarchy.
  1044. Element* element = this;
  1045. while (element->GetParentNode())
  1046. {
  1047. element->GetParentNode()->focus = element;
  1048. element = element->GetParentNode();
  1049. }
  1050. return true;
  1051. }
  1052. // Removes focus from from this element.
  1053. void Element::Blur()
  1054. {
  1055. if (parent)
  1056. {
  1057. Context* context = GetContext();
  1058. if (context == NULL)
  1059. return;
  1060. if (context->GetFocusElement() == this)
  1061. {
  1062. parent->Focus();
  1063. }
  1064. else if (parent->focus == this)
  1065. {
  1066. parent->focus = NULL;
  1067. }
  1068. }
  1069. }
  1070. // Fakes a mouse click on this element.
  1071. void Element::Click()
  1072. {
  1073. Context* context = GetContext();
  1074. if (context == NULL)
  1075. return;
  1076. context->GenerateClickEvent(this);
  1077. }
  1078. // Adds an event listener
  1079. void Element::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  1080. {
  1081. event_dispatcher->AttachEvent(event, listener, in_capture_phase);
  1082. }
  1083. // Removes an event listener from this element.
  1084. void Element::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  1085. {
  1086. event_dispatcher->DetachEvent(event, listener, in_capture_phase);
  1087. }
  1088. // Dispatches the specified event
  1089. bool Element::DispatchEvent(const String& event, const Dictionary& parameters, bool interruptible)
  1090. {
  1091. return event_dispatcher->DispatchEvent(this, event, parameters, interruptible);
  1092. }
  1093. // Scrolls the parent element's contents so that this element is visible.
  1094. void Element::ScrollIntoView(bool align_with_top)
  1095. {
  1096. Vector2f size(0, 0);
  1097. if (!align_with_top)
  1098. {
  1099. size.y = main_box.GetOffset().y +
  1100. main_box.GetSize(Box::BORDER).y;
  1101. }
  1102. Element* scroll_parent = parent;
  1103. while (scroll_parent != NULL)
  1104. {
  1105. Style::Overflow overflow_x_property = scroll_parent->GetComputedValues().overflow_x;
  1106. Style::Overflow overflow_y_property = scroll_parent->GetComputedValues().overflow_y;
  1107. if ((overflow_x_property != Style::Overflow::Visible &&
  1108. scroll_parent->GetScrollWidth() > scroll_parent->GetClientWidth()) ||
  1109. (overflow_y_property != Style::Overflow::Visible &&
  1110. scroll_parent->GetScrollHeight() > scroll_parent->GetClientHeight()))
  1111. {
  1112. Vector2f offset = scroll_parent->GetAbsoluteOffset(Box::BORDER) - GetAbsoluteOffset(Box::BORDER);
  1113. Vector2f scroll_offset(scroll_parent->GetScrollLeft(), scroll_parent->GetScrollTop());
  1114. scroll_offset -= offset;
  1115. scroll_offset.x += scroll_parent->GetClientLeft();
  1116. scroll_offset.y += scroll_parent->GetClientTop();
  1117. if (!align_with_top)
  1118. scroll_offset.y -= (scroll_parent->GetClientHeight() - size.y);
  1119. if (overflow_x_property != Style::Overflow::Visible)
  1120. scroll_parent->SetScrollLeft(scroll_offset.x);
  1121. if (overflow_y_property != Style::Overflow::Visible)
  1122. scroll_parent->SetScrollTop(scroll_offset.y);
  1123. }
  1124. scroll_parent = scroll_parent->GetParentNode();
  1125. }
  1126. }
  1127. // Appends a child to this element
  1128. void Element::AppendChild(Element* child, bool dom_element)
  1129. {
  1130. child->AddReference();
  1131. child->SetParent(this);
  1132. if (dom_element)
  1133. children.insert(children.end() - num_non_dom_children, child);
  1134. else
  1135. {
  1136. children.push_back(child);
  1137. num_non_dom_children++;
  1138. }
  1139. child->GetStyle()->DirtyDefinition();
  1140. Element* ancestor = child;
  1141. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1142. ancestor->OnChildAdd(child);
  1143. DirtyStackingContext();
  1144. DirtyStructure();
  1145. if (dom_element)
  1146. DirtyLayout();
  1147. }
  1148. // Adds a child to this element, directly after the adjacent element. Inherits
  1149. // the dom/non-dom status from the adjacent element.
  1150. void Element::InsertBefore(Element* child, Element* adjacent_element)
  1151. {
  1152. // Find the position in the list of children of the adjacent element. If
  1153. // it's NULL or we can't find it, then we insert it at the end of the dom
  1154. // children, as a dom element.
  1155. size_t child_index = 0;
  1156. bool found_child = false;
  1157. if (adjacent_element)
  1158. {
  1159. for (child_index = 0; child_index < children.size(); child_index++)
  1160. {
  1161. if (children[child_index] == adjacent_element)
  1162. {
  1163. found_child = true;
  1164. break;
  1165. }
  1166. }
  1167. }
  1168. if (found_child)
  1169. {
  1170. child->AddReference();
  1171. child->SetParent(this);
  1172. if ((int) child_index >= GetNumChildren())
  1173. num_non_dom_children++;
  1174. else
  1175. DirtyLayout();
  1176. children.insert(children.begin() + child_index, child);
  1177. child->GetStyle()->DirtyDefinition();
  1178. Element* ancestor = child;
  1179. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1180. ancestor->OnChildAdd(child);
  1181. DirtyStackingContext();
  1182. DirtyStructure();
  1183. }
  1184. else
  1185. {
  1186. AppendChild(child);
  1187. }
  1188. }
  1189. // Replaces the second node with the first node.
  1190. bool Element::ReplaceChild(Element* inserted_element, Element* replaced_element)
  1191. {
  1192. inserted_element->AddReference();
  1193. inserted_element->SetParent(this);
  1194. ElementList::iterator insertion_point = children.begin();
  1195. while (insertion_point != children.end() && *insertion_point != replaced_element)
  1196. {
  1197. ++insertion_point;
  1198. }
  1199. if (insertion_point == children.end())
  1200. {
  1201. AppendChild(inserted_element);
  1202. return false;
  1203. }
  1204. children.insert(insertion_point, inserted_element);
  1205. RemoveChild(replaced_element);
  1206. inserted_element->GetStyle()->DirtyDefinition();
  1207. Element* ancestor = inserted_element;
  1208. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1209. ancestor->OnChildAdd(inserted_element);
  1210. return true;
  1211. }
  1212. // Removes the specified child
  1213. bool Element::RemoveChild(Element* child)
  1214. {
  1215. size_t child_index = 0;
  1216. for (ElementList::iterator itr = children.begin(); itr != children.end(); ++itr)
  1217. {
  1218. // Add the element to the delete list
  1219. if ((*itr) == child)
  1220. {
  1221. // Inform the context of the element's pending removal (if we have a valid context).
  1222. Context* context = GetContext();
  1223. if (context)
  1224. context->OnElementRemove(child);
  1225. Element* ancestor = child;
  1226. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1227. ancestor->OnChildRemove(child);
  1228. if (child_index >= children.size() - num_non_dom_children)
  1229. num_non_dom_children--;
  1230. deleted_children.push_back(child);
  1231. children.erase(itr);
  1232. // Remove the child element as the focussed child of this element.
  1233. if (child == focus)
  1234. {
  1235. focus = NULL;
  1236. // If this child (or a descendant of this child) is the context's currently
  1237. // focussed element, set the focus to us instead.
  1238. Context* context = GetContext();
  1239. if (context != NULL)
  1240. {
  1241. Element* focus_element = context->GetFocusElement();
  1242. while (focus_element != NULL)
  1243. {
  1244. if (focus_element == child)
  1245. {
  1246. Focus();
  1247. break;
  1248. }
  1249. focus_element = focus_element->GetParentNode();
  1250. }
  1251. }
  1252. }
  1253. DirtyLayout();
  1254. DirtyStackingContext();
  1255. DirtyStructure();
  1256. return true;
  1257. }
  1258. child_index++;
  1259. }
  1260. return false;
  1261. }
  1262. bool Element::HasChildNodes() const
  1263. {
  1264. return (int) children.size() > num_non_dom_children;
  1265. }
  1266. Element* Element::GetElementById(const String& id)
  1267. {
  1268. // Check for special-case tokens.
  1269. if (id == "#self")
  1270. return this;
  1271. else if (id == "#document")
  1272. return GetOwnerDocument();
  1273. else if (id == "#parent")
  1274. return this->parent;
  1275. else
  1276. {
  1277. Element* search_root = GetOwnerDocument();
  1278. if (search_root == NULL)
  1279. search_root = this;
  1280. return ElementUtilities::GetElementById(search_root, id);
  1281. }
  1282. }
  1283. // Get all elements with the given tag.
  1284. void Element::GetElementsByTagName(ElementList& elements, const String& tag)
  1285. {
  1286. return ElementUtilities::GetElementsByTagName(elements, this, tag);
  1287. }
  1288. // Get all elements with the given class set on them.
  1289. void Element::GetElementsByClassName(ElementList& elements, const String& class_name)
  1290. {
  1291. return ElementUtilities::GetElementsByClassName(elements, this, class_name);
  1292. }
  1293. // Access the event dispatcher
  1294. EventDispatcher* Element::GetEventDispatcher() const
  1295. {
  1296. return event_dispatcher;
  1297. }
  1298. String Element::GetEventDispatcherSummary() const
  1299. {
  1300. return event_dispatcher->ToString();
  1301. }
  1302. // Access the element background.
  1303. ElementBackground* Element::GetElementBackground() const
  1304. {
  1305. return background;
  1306. }
  1307. // Access the element border.
  1308. ElementBorder* Element::GetElementBorder() const
  1309. {
  1310. return border;
  1311. }
  1312. // Access the element decorators
  1313. ElementDecoration* Element::GetElementDecoration() const
  1314. {
  1315. return decoration;
  1316. }
  1317. // Returns the element's scrollbar functionality.
  1318. ElementScroll* Element::GetElementScroll() const
  1319. {
  1320. return scroll;
  1321. }
  1322. int Element::GetClippingIgnoreDepth()
  1323. {
  1324. if (clipping_state_dirty)
  1325. {
  1326. IsClippingEnabled();
  1327. }
  1328. return clipping_ignore_depth;
  1329. }
  1330. bool Element::IsClippingEnabled()
  1331. {
  1332. if (clipping_state_dirty)
  1333. {
  1334. const auto& computed = GetComputedValues();
  1335. // Is clipping enabled for this element, yes unless both overlow properties are set to visible
  1336. clipping_enabled = computed.overflow_x != Style::Overflow::Visible
  1337. || computed.overflow_y != Style::Overflow::Visible;
  1338. // Get the clipping ignore depth from the clip property
  1339. clipping_ignore_depth = computed.clip.number;
  1340. clipping_state_dirty = false;
  1341. }
  1342. return clipping_enabled;
  1343. }
  1344. // Gets the render interface owned by this element's context.
  1345. RenderInterface* Element::GetRenderInterface()
  1346. {
  1347. Context* context = GetContext();
  1348. if (context != NULL)
  1349. return context->GetRenderInterface();
  1350. return Rocket::Core::GetRenderInterface();
  1351. }
  1352. void Element::SetInstancer(ElementInstancer* _instancer)
  1353. {
  1354. // Only record the first instancer being set as some instancers call other instancers to do their dirty work, in
  1355. // which case we don't want to update the lowest level instancer.
  1356. if (instancer == NULL)
  1357. {
  1358. instancer = _instancer;
  1359. instancer->AddReference();
  1360. }
  1361. }
  1362. // Forces the element to generate a local stacking context, regardless of the value of its z-index property.
  1363. void Element::ForceLocalStackingContext()
  1364. {
  1365. local_stacking_context_forced = true;
  1366. local_stacking_context = true;
  1367. DirtyStackingContext();
  1368. }
  1369. // Called during the update loop after children are rendered.
  1370. void Element::OnUpdate()
  1371. {
  1372. }
  1373. // Called during render after backgrounds, borders, decorators, but before children, are rendered.
  1374. void Element::OnRender()
  1375. {
  1376. }
  1377. void Element::OnResize()
  1378. {
  1379. }
  1380. // Called during a layout operation, when the element is being positioned and sized.
  1381. void Element::OnLayout()
  1382. {
  1383. }
  1384. // Called when attributes on the element are changed.
  1385. void Element::OnAttributeChange(const AttributeNameList& changed_attributes)
  1386. {
  1387. if (changed_attributes.find("id") != changed_attributes.end())
  1388. {
  1389. id = GetAttribute< String >("id", "");
  1390. style->DirtyDefinition();
  1391. }
  1392. if (changed_attributes.find("class") != changed_attributes.end())
  1393. {
  1394. style->SetClassNames(GetAttribute< String >("class", ""));
  1395. }
  1396. // Add any inline style declarations.
  1397. if (changed_attributes.find("style") != changed_attributes.end())
  1398. {
  1399. PropertyDictionary properties;
  1400. StyleSheetParser parser;
  1401. parser.ParseProperties(properties, GetAttribute< String >("style", ""));
  1402. Rocket::Core::PropertyMap property_map = properties.GetProperties();
  1403. for (Rocket::Core::PropertyMap::iterator i = property_map.begin(); i != property_map.end(); ++i)
  1404. {
  1405. SetProperty((*i).first, (*i).second);
  1406. }
  1407. }
  1408. }
  1409. // Called when properties on the element are changed.
  1410. void Element::OnPropertyChange(const PropertyNameList& changed_properties)
  1411. {
  1412. bool all_dirty = false;
  1413. {
  1414. auto& registered_properties = StyleSheetSpecification::GetRegisteredProperties();
  1415. if (&registered_properties == &changed_properties || registered_properties == changed_properties)
  1416. all_dirty = true;
  1417. }
  1418. if (!IsLayoutDirty())
  1419. {
  1420. if (all_dirty)
  1421. {
  1422. DirtyLayout();
  1423. }
  1424. else
  1425. {
  1426. // Force a relayout if any of the changed properties require it.
  1427. for (PropertyNameList::const_iterator i = changed_properties.begin(); i != changed_properties.end(); ++i)
  1428. {
  1429. const PropertyDefinition* property_definition = StyleSheetSpecification::GetProperty(*i);
  1430. if (property_definition)
  1431. {
  1432. if (property_definition->IsLayoutForced())
  1433. {
  1434. DirtyLayout();
  1435. break;
  1436. }
  1437. }
  1438. }
  1439. }
  1440. }
  1441. // Update the visibility.
  1442. if (all_dirty || changed_properties.find(VISIBILITY) != changed_properties.end() ||
  1443. changed_properties.find(DISPLAY) != changed_properties.end())
  1444. {
  1445. bool new_visibility = (element_meta->computed_values.display != Style::Display::None && element_meta->computed_values.visibility == Style::Visibility::Visible);
  1446. if (visible != new_visibility)
  1447. {
  1448. visible = new_visibility;
  1449. if (parent != NULL)
  1450. parent->DirtyStackingContext();
  1451. }
  1452. if (all_dirty ||
  1453. changed_properties.find(DISPLAY) != changed_properties.end())
  1454. {
  1455. if (parent != NULL)
  1456. parent->DirtyStructure();
  1457. }
  1458. }
  1459. // Fetch a new font face if it has been changed.
  1460. if (all_dirty ||
  1461. changed_properties.find(FONT_FAMILY) != changed_properties.end() ||
  1462. changed_properties.find(FONT_CHARSET) != changed_properties.end() ||
  1463. changed_properties.find(FONT_WEIGHT) != changed_properties.end() ||
  1464. changed_properties.find(FONT_STYLE) != changed_properties.end() ||
  1465. changed_properties.find(FONT_SIZE) != changed_properties.end())
  1466. {
  1467. // Fetch the new font face.
  1468. FontFaceHandle* new_font_face_handle = ElementUtilities::GetFontFaceHandle(element_meta->computed_values);
  1469. // If this is different from our current font face, then we've got to nuke
  1470. // all our characters and tell our parent that we have to be re-laid out.
  1471. if (new_font_face_handle != font_face_handle)
  1472. {
  1473. if (font_face_handle)
  1474. font_face_handle->RemoveReference();
  1475. font_face_handle = new_font_face_handle;
  1476. }
  1477. else if (new_font_face_handle != NULL)
  1478. new_font_face_handle->RemoveReference();
  1479. }
  1480. // Update the position.
  1481. if (all_dirty ||
  1482. changed_properties.find(LEFT) != changed_properties.end() ||
  1483. changed_properties.find(RIGHT) != changed_properties.end() ||
  1484. changed_properties.find(TOP) != changed_properties.end() ||
  1485. changed_properties.find(BOTTOM) != changed_properties.end())
  1486. {
  1487. // TODO: This should happen during/after layout, as the containing box is not properly defined yet
  1488. UpdateOffset();
  1489. DirtyOffset();
  1490. }
  1491. // Update the z-index.
  1492. if (all_dirty ||
  1493. changed_properties.find(Z_INDEX) != changed_properties.end())
  1494. {
  1495. Style::ZIndex z_index_property = element_meta->computed_values.z_index;
  1496. if (z_index_property.type == Style::ZIndex::Auto)
  1497. {
  1498. if (local_stacking_context &&
  1499. !local_stacking_context_forced)
  1500. {
  1501. // We're no longer acting as a stacking context.
  1502. local_stacking_context = false;
  1503. stacking_context_dirty = false;
  1504. stacking_context.clear();
  1505. }
  1506. // If our old z-index was not zero, then we must dirty our stacking context so we'll be re-indexed.
  1507. if (z_index != 0)
  1508. {
  1509. z_index = 0;
  1510. DirtyStackingContext();
  1511. }
  1512. }
  1513. else
  1514. {
  1515. float new_z_index = z_index_property.value;
  1516. if (new_z_index != z_index)
  1517. {
  1518. z_index = new_z_index;
  1519. if (parent != NULL)
  1520. parent->DirtyStackingContext();
  1521. }
  1522. if (!local_stacking_context)
  1523. {
  1524. local_stacking_context = true;
  1525. stacking_context_dirty = true;
  1526. }
  1527. }
  1528. }
  1529. // Dirty the background if it's changed.
  1530. if (all_dirty ||
  1531. changed_properties.find(BACKGROUND_COLOR) != changed_properties.end() ||
  1532. changed_properties.find(OPACITY) != changed_properties.end() ||
  1533. changed_properties.find(IMAGE_COLOR) != changed_properties.end()) {
  1534. background->DirtyBackground();
  1535. decoration->DirtyDecorators(true);
  1536. }
  1537. // Dirty the border if it's changed.
  1538. if (all_dirty ||
  1539. changed_properties.find(BORDER_TOP_WIDTH) != changed_properties.end() ||
  1540. changed_properties.find(BORDER_RIGHT_WIDTH) != changed_properties.end() ||
  1541. changed_properties.find(BORDER_BOTTOM_WIDTH) != changed_properties.end() ||
  1542. changed_properties.find(BORDER_LEFT_WIDTH) != changed_properties.end() ||
  1543. changed_properties.find(BORDER_TOP_COLOR) != changed_properties.end() ||
  1544. changed_properties.find(BORDER_RIGHT_COLOR) != changed_properties.end() ||
  1545. changed_properties.find(BORDER_BOTTOM_COLOR) != changed_properties.end() ||
  1546. changed_properties.find(BORDER_LEFT_COLOR) != changed_properties.end() ||
  1547. changed_properties.find(OPACITY) != changed_properties.end())
  1548. border->DirtyBorder();
  1549. // Check for clipping state changes
  1550. if (all_dirty ||
  1551. changed_properties.find(CLIP) != changed_properties.end() ||
  1552. changed_properties.find(OVERFLOW_X) != changed_properties.end() ||
  1553. changed_properties.find(OVERFLOW_Y) != changed_properties.end())
  1554. {
  1555. clipping_state_dirty = true;
  1556. }
  1557. // Check for `perspective' and `perspective-origin' changes
  1558. if (all_dirty ||
  1559. changed_properties.find(PERSPECTIVE) != changed_properties.end() ||
  1560. changed_properties.find(PERSPECTIVE_ORIGIN_X) != changed_properties.end() ||
  1561. changed_properties.find(PERSPECTIVE_ORIGIN_Y) != changed_properties.end())
  1562. {
  1563. DirtyTransformState(true, false, false);
  1564. }
  1565. // Check for `transform' and `transform-origin' changes
  1566. if (all_dirty ||
  1567. changed_properties.find(TRANSFORM) != changed_properties.end() ||
  1568. changed_properties.find(TRANSFORM_ORIGIN_X) != changed_properties.end() ||
  1569. changed_properties.find(TRANSFORM_ORIGIN_Y) != changed_properties.end() ||
  1570. changed_properties.find(TRANSFORM_ORIGIN_Z) != changed_properties.end())
  1571. {
  1572. DirtyTransformState(false, true, false);
  1573. }
  1574. // Check for `animation' changes
  1575. if (all_dirty || changed_properties.find(ANIMATION) != changed_properties.end())
  1576. {
  1577. DirtyAnimation();
  1578. }
  1579. }
  1580. void Element::UpdateDirtyProperties(const DirtyPropertyList& dirty_properties)
  1581. {
  1582. if (dirty_properties.Empty())
  1583. return;
  1584. if(dirty_properties.AllDirty())
  1585. {
  1586. OnPropertyChange(StyleSheetSpecification::GetRegisteredProperties());
  1587. }
  1588. else
  1589. {
  1590. OnPropertyChange(dirty_properties.GetList());
  1591. }
  1592. // TODO: Add the following check back
  1593. //#ifdef ROCKET_DEBUG
  1594. // if (all_properties_dirty || !dirty_properties.empty())
  1595. // 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.");
  1596. //#endif
  1597. }
  1598. // Called when a child node has been added somewhere in the hierarchy
  1599. void Element::OnChildAdd(Element* child)
  1600. {
  1601. }
  1602. // Called when a child node has been removed somewhere in the hierarchy
  1603. void Element::OnChildRemove(Element* child)
  1604. {
  1605. }
  1606. // Forces a re-layout of this element, and any other children required.
  1607. void Element::DirtyLayout()
  1608. {
  1609. Element* document = GetOwnerDocument();
  1610. if (document != NULL)
  1611. document->DirtyLayout();
  1612. }
  1613. // Forces a re-layout of this element, and any other children required.
  1614. bool Element::IsLayoutDirty()
  1615. {
  1616. Element* document = GetOwnerDocument();
  1617. if (document != NULL)
  1618. return document->IsLayoutDirty();
  1619. return false;
  1620. }
  1621. // Forces a reevaluation of applicable font effects.
  1622. void Element::DirtyFont()
  1623. {
  1624. for (size_t i = 0; i < children.size(); ++i)
  1625. children[i]->DirtyFont();
  1626. }
  1627. void Element::OnReferenceDeactivate()
  1628. {
  1629. if (instancer)
  1630. {
  1631. instancer->ReleaseElement(this);
  1632. }
  1633. else
  1634. {
  1635. // Hopefully we can just delete ourselves.
  1636. //delete this;
  1637. Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via Rocket Factory. Unable to release.", GetAddress().c_str());
  1638. }
  1639. }
  1640. void Element::ProcessEvent(Event& event)
  1641. {
  1642. if (event == MOUSEDOWN && IsPointWithinElement(Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0))) &&
  1643. event.GetParameter< int >("button", 0) == 0)
  1644. SetPseudoClass("active", true);
  1645. if (event == MOUSESCROLL)
  1646. {
  1647. if (GetScrollHeight() > GetClientHeight())
  1648. {
  1649. Style::Overflow overflow_property = element_meta->computed_values.overflow_y;
  1650. if (overflow_property == Style::Overflow::Auto ||
  1651. overflow_property == Style::Overflow::Scroll)
  1652. {
  1653. // Stop the propagation if the current element has scrollbars.
  1654. // This prevents scrolling in parent elements, which is often unintended. If instead desired behavior is
  1655. // to scroll in parent elements when reaching top/bottom, move StopPropagation inside the next if statement.
  1656. event.StopPropagation();
  1657. int wheel_delta = event.GetParameter< int >("wheel_delta", 0);
  1658. if ((wheel_delta < 0 && GetScrollTop() > 0) ||
  1659. (wheel_delta > 0 && GetScrollHeight() > GetScrollTop() + GetClientHeight()))
  1660. {
  1661. SetScrollTop(GetScrollTop() + wheel_delta * GetLineHeight());
  1662. }
  1663. }
  1664. }
  1665. return;
  1666. }
  1667. if (event.GetTargetElement() == this)
  1668. {
  1669. if (event == MOUSEOVER)
  1670. SetPseudoClass("hover", true);
  1671. else if (event == MOUSEOUT)
  1672. SetPseudoClass("hover", false);
  1673. else if (event == FOCUS)
  1674. SetPseudoClass(FOCUS, true);
  1675. else if (event == BLUR)
  1676. SetPseudoClass(FOCUS, false);
  1677. }
  1678. }
  1679. const Style::ComputedValues& Element::GetComputedValues() const
  1680. {
  1681. return element_meta->computed_values;
  1682. }
  1683. void Element::GetRML(String& content)
  1684. {
  1685. // First we start the open tag, add the attributes then close the open tag.
  1686. // Then comes the children in order, then we add our close tag.
  1687. content += "<";
  1688. content += tag;
  1689. for( auto& pair : attributes)
  1690. {
  1691. auto& name = pair.first;
  1692. auto& variant = pair.second;
  1693. String value;
  1694. if (variant.GetInto(value))
  1695. content += " " + name + "=\"" + value + "\"";
  1696. }
  1697. if (HasChildNodes())
  1698. {
  1699. content += ">";
  1700. GetInnerRML(content);
  1701. content += "</";
  1702. content += tag;
  1703. content += ">";
  1704. }
  1705. else
  1706. {
  1707. content += " />";
  1708. }
  1709. }
  1710. void Element::SetParent(Element* _parent)
  1711. {
  1712. // If there's an old parent, detach from it first.
  1713. if (parent &&
  1714. parent != _parent)
  1715. parent->RemoveChild(this);
  1716. // Save our parent
  1717. parent = _parent;
  1718. }
  1719. void Element::ReleaseDeletedElements()
  1720. {
  1721. for (size_t i = 0; i < active_children.size(); i++)
  1722. {
  1723. active_children[i]->ReleaseDeletedElements();
  1724. }
  1725. ReleaseElements(deleted_children);
  1726. active_children = children;
  1727. }
  1728. void Element::ReleaseElements(ElementList& released_elements)
  1729. {
  1730. // Remove deleted children from this element.
  1731. while (!released_elements.empty())
  1732. {
  1733. Element* element = released_elements.back();
  1734. released_elements.pop_back();
  1735. // If this element has been added back into our list, then we remove our previous oustanding reference on it
  1736. // and continue.
  1737. if (std::find(children.begin(), children.end(), element) != children.end())
  1738. {
  1739. element->RemoveReference();
  1740. continue;
  1741. }
  1742. // Set the parent to NULL unless it's been reparented already.
  1743. if (element->GetParentNode() == this)
  1744. element->parent = NULL;
  1745. element->RemoveReference();
  1746. }
  1747. }
  1748. void Element::DirtyOffset()
  1749. {
  1750. offset_dirty = true;
  1751. if(transform_state)
  1752. DirtyTransformState(true, true, false);
  1753. // Not strictly true ... ?
  1754. for (size_t i = 0; i < children.size(); i++)
  1755. children[i]->DirtyOffset();
  1756. }
  1757. void Element::UpdateOffset()
  1758. {
  1759. using namespace Style;
  1760. const auto& computed = element_meta->computed_values;
  1761. Position position_property = computed.position;
  1762. if (position_property == Position::Absolute ||
  1763. position_property == Position::Fixed)
  1764. {
  1765. if (offset_parent != NULL)
  1766. {
  1767. const Box& parent_box = offset_parent->GetBox();
  1768. Vector2f containing_block = parent_box.GetSize(Box::PADDING);
  1769. // If the element is anchored left, then the position is offset by that resolved value.
  1770. if (computed.left.type != Left::Auto)
  1771. relative_offset_base.x = parent_box.GetEdge(Box::BORDER, Box::LEFT) + (ResolveValue(computed.left, containing_block.x) + GetBox().GetEdge(Box::MARGIN, Box::LEFT));
  1772. // If the element is anchored right, then the position is set first so the element's right-most edge
  1773. // (including margins) will render up against the containing box's right-most content edge, and then
  1774. // offset by the resolved value.
  1775. else if (computed.right.type != Right::Auto)
  1776. 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));
  1777. // If the element is anchored top, then the position is offset by that resolved value.
  1778. if (computed.top.type != Top::Auto)
  1779. relative_offset_base.y = parent_box.GetEdge(Box::BORDER, Box::TOP) + (ResolveValue(computed.top, containing_block.y) + GetBox().GetEdge(Box::MARGIN, Box::TOP));
  1780. // If the element is anchored bottom, then the position is set first so the element's right-most edge
  1781. // (including margins) will render up against the containing box's right-most content edge, and then
  1782. // offset by the resolved value.
  1783. else if (computed.bottom.type != Bottom::Auto)
  1784. 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));
  1785. }
  1786. }
  1787. else if (position_property == Position::Relative)
  1788. {
  1789. if (offset_parent != NULL)
  1790. {
  1791. const Box& parent_box = offset_parent->GetBox();
  1792. Vector2f containing_block = parent_box.GetSize();
  1793. if (computed.left.type != Left::Auto)
  1794. relative_offset_position.x = ResolveValue(computed.left, containing_block.x);
  1795. else if (computed.right.type != Right::Auto)
  1796. relative_offset_position.x = -1 * ResolveValue(computed.right, containing_block.x);
  1797. else
  1798. relative_offset_position.x = 0;
  1799. if (computed.top.type != Top::Auto)
  1800. relative_offset_position.y = ResolveValue(computed.top, containing_block.y);
  1801. else if (computed.bottom.type != Bottom::Auto)
  1802. relative_offset_position.y = -1 * ResolveValue(computed.bottom, containing_block.y);
  1803. else
  1804. relative_offset_position.y = 0;
  1805. }
  1806. }
  1807. else
  1808. {
  1809. relative_offset_position.x = 0;
  1810. relative_offset_position.y = 0;
  1811. }
  1812. }
  1813. void Element::BuildLocalStackingContext()
  1814. {
  1815. stacking_context_dirty = false;
  1816. stacking_context.clear();
  1817. BuildStackingContext(&stacking_context);
  1818. std::stable_sort(stacking_context.begin(), stacking_context.end(), ElementSortZIndex());
  1819. }
  1820. void Element::BuildStackingContext(ElementList* new_stacking_context)
  1821. {
  1822. // Build the list of ordered children. Our child list is sorted within the stacking context so stacked elements
  1823. // will render in the right order; ie, positioned elements will render on top of inline elements, which will render
  1824. // on top of floated elements, which will render on top of block elements.
  1825. std::vector< std::pair< Element*, float > > ordered_children;
  1826. for (size_t i = 0; i < children.size(); ++i)
  1827. {
  1828. Element* child = children[i];
  1829. if (!child->IsVisible())
  1830. continue;
  1831. std::pair< Element*, float > ordered_child;
  1832. ordered_child.first = child;
  1833. if (child->GetPosition() != Style::Position::Static)
  1834. ordered_child.second = 3;
  1835. else if (child->GetFloat() != Style::Float::None)
  1836. ordered_child.second = 1;
  1837. else if (child->GetDisplay() == Style::Display::Block)
  1838. ordered_child.second = 0;
  1839. else
  1840. ordered_child.second = 2;
  1841. ordered_children.push_back(ordered_child);
  1842. }
  1843. // Sort the list!
  1844. std::stable_sort(ordered_children.begin(), ordered_children.end(), ElementSortZOrder());
  1845. // Add the list of ordered children into the stacking context in order.
  1846. for (size_t i = 0; i < ordered_children.size(); ++i)
  1847. {
  1848. new_stacking_context->push_back(ordered_children[i].first);
  1849. if (!ordered_children[i].first->local_stacking_context)
  1850. ordered_children[i].first->BuildStackingContext(new_stacking_context);
  1851. }
  1852. }
  1853. void Element::DirtyStackingContext()
  1854. {
  1855. // The first ancestor of ours that doesn't have an automatic z-index is the ancestor that is establishing our local
  1856. // stacking context.
  1857. Element* stacking_context_parent = this;
  1858. while (stacking_context_parent != NULL &&
  1859. !stacking_context_parent->local_stacking_context)
  1860. stacking_context_parent = stacking_context_parent->GetParentNode();
  1861. if (stacking_context_parent != NULL)
  1862. stacking_context_parent->stacking_context_dirty = true;
  1863. }
  1864. void Element::DirtyStructure()
  1865. {
  1866. // Clear the cached owner document
  1867. owner_document = NULL;
  1868. structure_dirty = true;
  1869. }
  1870. void Element::DirtyParentStructure()
  1871. {
  1872. owner_document = NULL;
  1873. parent_structure_dirty = true;
  1874. }
  1875. void Element::UpdateStructure()
  1876. {
  1877. if (parent_structure_dirty)
  1878. {
  1879. // If children depend on structured selectors, they may need to be updated
  1880. const ElementDefinition* element_definition = GetStyle()->GetDefinition();
  1881. if (element_definition != NULL && element_definition->IsStructurallyVolatile())
  1882. {
  1883. GetStyle()->DirtyDefinition();
  1884. }
  1885. }
  1886. if (structure_dirty || parent_structure_dirty)
  1887. {
  1888. for (size_t i = 0; i < children.size(); ++i)
  1889. children[i]->DirtyParentStructure();
  1890. structure_dirty = false;
  1891. parent_structure_dirty = false;
  1892. }
  1893. }
  1894. 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)
  1895. {
  1896. bool result = false;
  1897. auto it_animation = StartAnimation(property_name, start_value, num_iterations, alternate_direction, delay);
  1898. if (it_animation != animations.end())
  1899. {
  1900. result = it_animation->AddKey(duration, target_value, *this, tween, true);
  1901. if (!result)
  1902. animations.erase(it_animation);
  1903. }
  1904. return result;
  1905. }
  1906. bool Element::AddAnimationKey(const String & property_name, const Property & target_value, float duration, Tween tween)
  1907. {
  1908. ElementAnimation* animation = nullptr;
  1909. for (auto& existing_animation : animations) {
  1910. if (existing_animation.GetPropertyName() == property_name) {
  1911. animation = &existing_animation;
  1912. break;
  1913. }
  1914. }
  1915. if (!animation)
  1916. return false;
  1917. bool result = animation->AddKey(animation->GetDuration() + duration, target_value, *this, tween, true);
  1918. return result;
  1919. }
  1920. ElementAnimationList::iterator Element::StartAnimation(const String & property_name, const Property* start_value, int num_iterations, bool alternate_direction, float delay)
  1921. {
  1922. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyName() == property_name; });
  1923. if (it == animations.end())
  1924. {
  1925. animations.emplace_back();
  1926. it = animations.end() - 1;
  1927. }
  1928. Property value;
  1929. if (start_value)
  1930. {
  1931. value = *start_value;
  1932. if (!value.definition)
  1933. if(auto default_value = GetProperty(property_name))
  1934. value.definition = default_value->definition;
  1935. }
  1936. else if (auto default_value = GetProperty(property_name))
  1937. {
  1938. value = *default_value;
  1939. }
  1940. if (value.definition)
  1941. {
  1942. double start_time = Clock::GetElapsedTime() + (double)delay;
  1943. *it = ElementAnimation{ property_name, value, start_time, 0.0f, num_iterations, alternate_direction, false };
  1944. }
  1945. else
  1946. {
  1947. animations.erase(it);
  1948. it = animations.end();
  1949. }
  1950. return it;
  1951. }
  1952. bool Element::AddAnimationKeyTime(const String & property_name, const Property* target_value, float time, Tween tween)
  1953. {
  1954. if (!target_value)
  1955. target_value = GetProperty(property_name);
  1956. if (!target_value)
  1957. return false;
  1958. ElementAnimation* animation = nullptr;
  1959. for (auto& existing_animation : animations) {
  1960. if (existing_animation.GetPropertyName() == property_name) {
  1961. animation = &existing_animation;
  1962. break;
  1963. }
  1964. }
  1965. if (!animation)
  1966. return false;
  1967. bool result = animation->AddKey(time, *target_value, *this, tween, true);
  1968. return result;
  1969. }
  1970. bool Element::StartTransition(const Transition & transition, const Property& start_value, const Property & target_value)
  1971. {
  1972. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyName() == transition.name; });
  1973. if (it != animations.end() && !it->IsTransition())
  1974. return false;
  1975. float duration = transition.duration;
  1976. double start_time = Clock::GetElapsedTime() + (double)transition.delay;
  1977. if (it == animations.end())
  1978. {
  1979. // Add transition as new animation
  1980. animations.push_back(
  1981. ElementAnimation{ transition.name, start_value, start_time, 0.0f, 1, false, true }
  1982. );
  1983. it = (animations.end() - 1);
  1984. }
  1985. else
  1986. {
  1987. // Compress the duration based on the progress of the current animation
  1988. float f = it->GetInterpolationFactor();
  1989. f = 1.0f - (1.0f - f)*transition.reverse_adjustment_factor;
  1990. duration = duration * f;
  1991. // Replace old transition
  1992. *it = ElementAnimation{ transition.name, start_value, start_time, 0.0f, 1, false, true };
  1993. }
  1994. bool result = it->AddKey(duration, target_value, *this, transition.tween, true);
  1995. if (result)
  1996. SetProperty(transition.name, start_value);
  1997. else
  1998. animations.erase(it);
  1999. return result;
  2000. }
  2001. void Element::DirtyAnimation()
  2002. {
  2003. dirty_animation = true;
  2004. }
  2005. void Element::UpdateAnimation()
  2006. {
  2007. if (dirty_animation)
  2008. {
  2009. const auto& animation_list = element_meta->computed_values.animation;
  2010. StyleSheet* stylesheet = nullptr;
  2011. if (!animation_list.empty() && (stylesheet = GetStyleSheet()))
  2012. {
  2013. for (auto& animation : animation_list)
  2014. {
  2015. Keyframes* keyframes_ptr = stylesheet->GetKeyframes(animation.name);
  2016. if (keyframes_ptr && keyframes_ptr->blocks.size() >= 1 && !animation.paused)
  2017. {
  2018. auto& property_names = keyframes_ptr->property_names;
  2019. auto& blocks = keyframes_ptr->blocks;
  2020. bool has_from_key = (blocks[0].normalized_time == 0);
  2021. bool has_to_key = (blocks.back().normalized_time == 1);
  2022. // If the first key defines initial conditions for a given property, use those values, else, use this element's current values.
  2023. for (auto& property : property_names)
  2024. StartAnimation(property, (has_from_key ? blocks[0].properties.GetProperty(property) : nullptr), animation.num_iterations, animation.alternate, animation.delay);
  2025. // Need to skip the first and last keys if they set the initial and end conditions, respectively.
  2026. for (int i = (has_from_key ? 1 : 0); i < (int)blocks.size() + (has_to_key ? -1 : 0); i++)
  2027. {
  2028. // Add properties of current key to animation
  2029. float time = blocks[i].normalized_time * animation.duration;
  2030. for (auto& property : blocks[i].properties.GetProperties())
  2031. AddAnimationKeyTime(property.first, &property.second, time, animation.tween);
  2032. }
  2033. // If the last key defines end conditions for a given property, use those values, else, use this element's current values.
  2034. float time = animation.duration;
  2035. for (auto& property : property_names)
  2036. AddAnimationKeyTime(property, (has_to_key ? blocks.back().properties.GetProperty(property) : nullptr), time, animation.tween);
  2037. }
  2038. }
  2039. }
  2040. dirty_animation = false;
  2041. }
  2042. }
  2043. void Element::AdvanceAnimations()
  2044. {
  2045. if (!animations.empty())
  2046. {
  2047. double time = Clock::GetElapsedTime();
  2048. for (auto& animation : animations)
  2049. {
  2050. Property property = animation.UpdateAndGetProperty(time, *this);
  2051. if (property.unit != Property::UNKNOWN)
  2052. SetProperty(animation.GetPropertyName(), property);
  2053. }
  2054. auto it_completed = std::remove_if(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return animation.IsComplete(); });
  2055. std::vector<Dictionary> dictionary_list;
  2056. std::vector<bool> is_transition;
  2057. dictionary_list.reserve(animations.end() - it_completed);
  2058. is_transition.reserve(animations.end() - it_completed);
  2059. for (auto it = it_completed; it != animations.end(); ++it)
  2060. {
  2061. dictionary_list.emplace_back();
  2062. dictionary_list.back().emplace("property", it->GetPropertyName());
  2063. is_transition.push_back(it->IsTransition());
  2064. }
  2065. // Need to erase elements before submitting event, as iterators might be invalidated when calling external code.
  2066. animations.erase(it_completed, animations.end());
  2067. for (size_t i = 0; i < dictionary_list.size(); i++)
  2068. DispatchEvent(is_transition[i] ? TRANSITIONEND : ANIMATIONEND, dictionary_list[i]);
  2069. }
  2070. }
  2071. void Element::DirtyTransformState(bool perspective_changed, bool transform_changed, bool parent_transform_changed)
  2072. {
  2073. for (size_t i = 0; i < children.size(); ++i)
  2074. {
  2075. children[i]->DirtyTransformState(false, false, transform_changed || parent_transform_changed);
  2076. }
  2077. if (perspective_changed)
  2078. {
  2079. this->transform_state_perspective_dirty = true;
  2080. }
  2081. if (transform_changed)
  2082. {
  2083. this->transform_state_transform_dirty = true;
  2084. }
  2085. if (parent_transform_changed)
  2086. {
  2087. this->transform_state_parent_transform_dirty = true;
  2088. }
  2089. }
  2090. void Element::UpdateTransformState()
  2091. {
  2092. if (!(transform_state_perspective_dirty || transform_state_transform_dirty || transform_state_parent_transform_dirty))
  2093. {
  2094. return;
  2095. }
  2096. const ComputedValues& computed = element_meta->computed_values;
  2097. if (!computed.transform && computed.perspective <= 0)
  2098. {
  2099. transform_state.reset();
  2100. transform_state_perspective_dirty = false;
  2101. transform_state_transform_dirty = false;
  2102. transform_state_parent_transform_dirty = false;
  2103. return;
  2104. }
  2105. if(transform_state_perspective_dirty || transform_state_transform_dirty)
  2106. {
  2107. Context *context = GetContext();
  2108. Vector2f pos = GetAbsoluteOffset(Box::BORDER);
  2109. Vector2f size = GetBox().GetSize(Box::BORDER);
  2110. if (transform_state_perspective_dirty)
  2111. {
  2112. bool have_perspective = false;
  2113. TransformState::Perspective perspective_value;
  2114. perspective_value.vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
  2115. if (computed.perspective > 0.0f)
  2116. {
  2117. have_perspective = true;
  2118. // Compute the perspective value
  2119. perspective_value.distance = computed.perspective;
  2120. // Compute the perspective origin, if necessary
  2121. if (computed.perspective_origin_x.type == Style::PerspectiveOrigin::Percentage)
  2122. perspective_value.vanish.x = pos.x + computed.perspective_origin_x.value * 0.01f * size.x;
  2123. else
  2124. perspective_value.vanish.x = pos.x + computed.perspective_origin_x.value;
  2125. if (computed.perspective_origin_y.type == Style::PerspectiveOrigin::Percentage)
  2126. perspective_value.vanish.y = pos.y + computed.perspective_origin_y.value * 0.01f * size.y;
  2127. else
  2128. perspective_value.vanish.y = pos.y + computed.perspective_origin_y.value;
  2129. }
  2130. if (have_perspective && context)
  2131. {
  2132. if (!transform_state)
  2133. transform_state.reset(new TransformState);
  2134. perspective_value.view_size = context->GetDimensions();
  2135. transform_state->SetPerspective(&perspective_value);
  2136. }
  2137. else if (transform_state)
  2138. {
  2139. transform_state->SetPerspective(nullptr);
  2140. }
  2141. transform_state_perspective_dirty = false;
  2142. }
  2143. if (transform_state_transform_dirty)
  2144. {
  2145. bool have_local_perspective = false;
  2146. TransformState::LocalPerspective local_perspective;
  2147. bool have_transform = false;
  2148. Matrix4f transform_value = Matrix4f::Identity();
  2149. Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
  2150. if (computed.transform)
  2151. {
  2152. int n = computed.transform->GetNumPrimitives();
  2153. for (int i = 0; i < n; ++i)
  2154. {
  2155. const Transforms::Primitive &primitive = computed.transform->GetPrimitive(i);
  2156. if (primitive.ResolvePerspective(local_perspective.distance, *this))
  2157. {
  2158. have_local_perspective = true;
  2159. }
  2160. Matrix4f matrix;
  2161. if (primitive.ResolveTransform(matrix, *this))
  2162. {
  2163. transform_value *= matrix;
  2164. have_transform = true;
  2165. }
  2166. }
  2167. // Compute the transform origin
  2168. if (computed.transform_origin_x.type == Style::TransformOrigin::Percentage)
  2169. transform_origin.x = pos.x + computed.transform_origin_x.value * size.x * 0.01f;
  2170. else
  2171. transform_origin.x = pos.x + computed.transform_origin_x.value;
  2172. if (computed.transform_origin_y.type == Style::TransformOrigin::Percentage)
  2173. transform_origin.y = pos.y + computed.transform_origin_y.value * size.y * 0.01f;
  2174. else
  2175. transform_origin.y = pos.y + computed.transform_origin_y.value;
  2176. transform_origin.z = computed.transform_origin_z;
  2177. }
  2178. if (have_local_perspective && context)
  2179. {
  2180. if (!transform_state)
  2181. transform_state.reset(new TransformState);
  2182. local_perspective.view_size = context->GetDimensions();
  2183. transform_state->SetLocalPerspective(&local_perspective);
  2184. }
  2185. else if(transform_state)
  2186. {
  2187. transform_state->SetLocalPerspective(nullptr);
  2188. }
  2189. if (have_transform)
  2190. {
  2191. // TODO: If we're using the global projection matrix
  2192. // (perspective < 0), then scale the coordinates from
  2193. // pixel space to 3D unit space.
  2194. // Transform the Rocket context so that the computed `transform_origin'
  2195. // lies at the coordinate system origin.
  2196. transform_value =
  2197. Matrix4f::Translate(transform_origin)
  2198. * transform_value
  2199. * Matrix4f::Translate(-transform_origin);
  2200. if (!transform_state)
  2201. transform_state.reset(new TransformState);
  2202. transform_state->SetTransform(&transform_value);
  2203. }
  2204. else if (transform_state)
  2205. {
  2206. transform_state->SetTransform(nullptr);
  2207. }
  2208. transform_state_transform_dirty = false;
  2209. }
  2210. }
  2211. if (transform_state_parent_transform_dirty)
  2212. {
  2213. // We need to clean up from the top-most to the bottom-most dirt.
  2214. if (parent)
  2215. {
  2216. parent->UpdateTransformState();
  2217. }
  2218. if (transform_state)
  2219. {
  2220. // Store the parent's new full transform as our parent transform
  2221. Element *node = nullptr;
  2222. Matrix4f parent_transform;
  2223. for (node = parent; node; node = node->parent)
  2224. {
  2225. if (node->GetTransformState() && node->GetTransformState()->GetRecursiveTransform(&parent_transform))
  2226. {
  2227. transform_state->SetParentRecursiveTransform(&parent_transform);
  2228. break;
  2229. }
  2230. }
  2231. if (!node)
  2232. {
  2233. transform_state->SetParentRecursiveTransform(nullptr);
  2234. }
  2235. }
  2236. transform_state_parent_transform_dirty = false;
  2237. }
  2238. // If we neither have a local perspective, nor a perspective nor a
  2239. // transform, we don't need to keep the large TransformState object
  2240. // around. GetEffectiveTransformState() will then recursively visit
  2241. // parents in order to find a non-trivial TransformState.
  2242. if (transform_state && !transform_state->GetLocalPerspective(nullptr) && !transform_state->GetPerspective(nullptr) && !transform_state->GetTransform(nullptr))
  2243. {
  2244. transform_state.reset();
  2245. }
  2246. }
  2247. }
  2248. }