Element.cpp 72 KB

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