Element.cpp 72 KB

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