Element.cpp 73 KB

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