Element.cpp 73 KB

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