Element.cpp 72 KB

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