Element.cpp 72 KB

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