Element.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709
  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 "ComputeProperty.h"
  35. #include "ElementAnimation.h"
  36. #include "ElementBackground.h"
  37. #include "ElementBorder.h"
  38. #include "ElementDefinition.h"
  39. #include "ElementStyle.h"
  40. #include "EventDispatcher.h"
  41. #include "EventSpecification.h"
  42. #include "ElementDecoration.h"
  43. #include "FontFaceHandle.h"
  44. #include "LayoutEngine.h"
  45. #include "PluginRegistry.h"
  46. #include "Pool.h"
  47. #include "StyleSheetParser.h"
  48. #include "XMLParseTools.h"
  49. #include "../../Include/Rocket/Core/Core.h"
  50. namespace Rocket {
  51. namespace Core {
  52. /**
  53. STL function object for sorting elements by z-type (ie, float-types before general types, etc).
  54. @author Peter Curry
  55. */
  56. class ElementSortZOrder
  57. {
  58. public:
  59. bool operator()(const std::pair< Element*, float >& lhs, const std::pair< Element*, float >& rhs) const
  60. {
  61. return lhs.second < rhs.second;
  62. }
  63. };
  64. /**
  65. STL function object for sorting elements by z-index property.
  66. @author Peter Curry
  67. */
  68. class ElementSortZIndex
  69. {
  70. public:
  71. bool operator()(const Element* lhs, const Element* rhs) const
  72. {
  73. // Check the z-index.
  74. return lhs->GetZIndex() < rhs->GetZIndex();
  75. }
  76. };
  77. // Determines how many levels up in the hierarchy the OnChildAdd and OnChildRemove are called (starting at the child itself)
  78. static constexpr int ChildNotifyLevels = 2;
  79. struct ElementMetaChunk;
  80. static Pool< ElementMetaChunk > element_meta_chunk_pool(200, true);
  81. // Meta objects for element collected in a single struct to reduce memory allocations
  82. struct ElementMeta
  83. {
  84. ElementMeta(Element* el) : event_dispatcher(el), style(el), background(el), border(el), decoration(el), scroll(el) {}
  85. EventDispatcher event_dispatcher;
  86. ElementStyle style;
  87. ElementBackground background;
  88. ElementBorder border;
  89. ElementDecoration decoration;
  90. ElementScroll scroll;
  91. Style::ComputedValues computed_values;
  92. void* operator new(size_t size)
  93. {
  94. void* memory = element_meta_chunk_pool.AllocateObject();
  95. return memory;
  96. }
  97. void operator delete(void* chunk)
  98. {
  99. element_meta_chunk_pool.DeallocateObject((ElementMetaChunk*)chunk);
  100. }
  101. };
  102. struct alignas(ElementMeta) ElementMetaChunk
  103. {
  104. ElementMetaChunk() { memset(buffer, 0, size); }
  105. static constexpr size_t size = sizeof(ElementMeta);
  106. char buffer[size];
  107. };
  108. /// Constructs a new libRocket element.
  109. 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),
  110. transform_state(), transform_state_perspective_dirty(true), transform_state_transform_dirty(true), transform_state_parent_transform_dirty(true), dirty_animation(false)
  111. {
  112. ROCKET_ASSERT(tag == ToLower(tag));
  113. parent = NULL;
  114. focus = NULL;
  115. instancer = NULL;
  116. owner_document = NULL;
  117. offset_fixed = false;
  118. offset_parent = NULL;
  119. offset_dirty = true;
  120. client_area = Box::PADDING;
  121. num_non_dom_children = 0;
  122. visible = true;
  123. z_index = 0;
  124. local_stacking_context = false;
  125. local_stacking_context_forced = false;
  126. stacking_context_dirty = false;
  127. structure_dirty = false;
  128. parent_structure_dirty = false;
  129. computed_values_are_default_initialized = true;
  130. box_dirty = false;
  131. font_face_handle = NULL;
  132. clipping_ignore_depth = 0;
  133. clipping_enabled = false;
  134. clipping_state_dirty = true;
  135. element_meta = new ElementMeta(this);
  136. event_dispatcher = &element_meta->event_dispatcher;
  137. style = &element_meta->style;
  138. background = &element_meta->background;
  139. border = &element_meta->border;
  140. decoration = &element_meta->decoration;
  141. scroll = &element_meta->scroll;
  142. }
  143. Element::~Element()
  144. {
  145. ROCKET_ASSERT(parent == NULL);
  146. PluginRegistry::NotifyElementDestroy(this);
  147. // Remove scrollbar elements before we delete the children!
  148. scroll->ClearScrollbars();
  149. // A simplified version of RemoveChild() for destruction.
  150. for (Element* child : children)
  151. {
  152. Element* child_ancestor = child;
  153. for (int i = 0; i <= ChildNotifyLevels && child_ancestor; i++, child_ancestor = child_ancestor->GetParentNode())
  154. child_ancestor->OnChildRemove(child);
  155. }
  156. if (deleted_children.empty())
  157. deleted_children = std::move(children);
  158. else
  159. deleted_children.insert(deleted_children.end(), children.begin(), children.end());
  160. children.clear();
  161. num_non_dom_children = 0;
  162. // Release all deleted children.
  163. ReleaseElements(deleted_children);
  164. delete element_meta;
  165. if (font_face_handle != NULL)
  166. font_face_handle->RemoveReference();
  167. if (instancer)
  168. instancer->RemoveReference();
  169. }
  170. void Element::Update(float dp_ratio)
  171. {
  172. ReleaseElements(deleted_children);
  173. OnUpdate();
  174. UpdateStructure();
  175. style->UpdateDefinition();
  176. scroll->Update();
  177. UpdateAnimation();
  178. AdvanceAnimations();
  179. if(style->AnyPropertiesDirty())
  180. {
  181. const ComputedValues* parent_values = nullptr;
  182. const ComputedValues* document_values = nullptr;
  183. if (parent)
  184. parent_values = &parent->GetComputedValues();
  185. if (auto doc = GetOwnerDocument())
  186. document_values = &doc->GetComputedValues();
  187. // Compute values and clear dirty properties
  188. auto dirty_properties = style->ComputeValues(element_meta->computed_values, parent_values, document_values, computed_values_are_default_initialized, dp_ratio);
  189. computed_values_are_default_initialized = false;
  190. // Computed values are just calculated and can safely be used in OnPropertyChange.
  191. // However, new properties set during this call will not be available until the next update loop.
  192. // Enable ROCKET_DEBUG to get a warning when this happens.
  193. if (dirty_properties.AllDirty())
  194. OnPropertyChange(StyleSheetSpecification::GetRegisteredProperties());
  195. else if(!dirty_properties.Empty())
  196. OnPropertyChange(dirty_properties.GetList());
  197. #ifdef ROCKET_DEBUG
  198. if (style->AnyPropertiesDirty())
  199. 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.");
  200. #endif
  201. }
  202. if (box_dirty)
  203. {
  204. box_dirty = false;
  205. OnResize();
  206. }
  207. UpdateTransformState();
  208. for (size_t i = 0; i < children.size(); i++)
  209. children[i]->Update(dp_ratio);
  210. }
  211. void Element::Render()
  212. {
  213. // Rebuild our stacking context if necessary.
  214. if (stacking_context_dirty)
  215. BuildLocalStackingContext();
  216. // Apply our transform
  217. ElementUtilities::ApplyTransform(*this);
  218. // Render all elements in our local stacking context that have a z-index beneath our local index of 0.
  219. size_t i = 0;
  220. for (; i < stacking_context.size() && stacking_context[i]->z_index < 0; ++i)
  221. stacking_context[i]->Render();
  222. // Set up the clipping region for this element.
  223. if (ElementUtilities::SetClippingRegion(this))
  224. {
  225. background->RenderBackground();
  226. border->RenderBorder();
  227. decoration->RenderDecorators();
  228. OnRender();
  229. }
  230. // Render the rest of the elements in the stacking context.
  231. for (; i < stacking_context.size(); ++i)
  232. stacking_context[i]->Render();
  233. // Unapply our transform
  234. ElementUtilities::UnapplyTransform(*this);
  235. }
  236. // Clones this element, returning a new, unparented element.
  237. Element* Element::Clone() const
  238. {
  239. Element* clone = NULL;
  240. if (instancer != NULL)
  241. {
  242. clone = instancer->InstanceElement(NULL, GetTagName(), attributes);
  243. if (clone != NULL)
  244. clone->SetInstancer(instancer);
  245. }
  246. else
  247. clone = Factory::InstanceElement(NULL, GetTagName(), GetTagName(), attributes);
  248. if (clone != NULL)
  249. {
  250. String inner_rml;
  251. GetInnerRML(inner_rml);
  252. clone->SetInnerRML(inner_rml);
  253. }
  254. return clone;
  255. }
  256. // Sets or removes a class on the element.
  257. void Element::SetClass(const String& class_name, bool activate)
  258. {
  259. style->SetClass(class_name, activate);
  260. }
  261. // Checks if a class is set on the element.
  262. bool Element::IsClassSet(const String& class_name) const
  263. {
  264. return style->IsClassSet(class_name);
  265. }
  266. // Specifies the entire list of classes for this element. This will replace any others specified.
  267. void Element::SetClassNames(const String& class_names)
  268. {
  269. SetAttribute("class", class_names);
  270. }
  271. /// Return the active class list
  272. String Element::GetClassNames() const
  273. {
  274. return style->GetClassNames();
  275. }
  276. // Returns the active style sheet for this element. This may be NULL.
  277. StyleSheet* Element::GetStyleSheet() const
  278. {
  279. return style->GetStyleSheet();
  280. }
  281. // Returns the element's definition, updating if necessary.
  282. const ElementDefinition* Element::GetDefinition()
  283. {
  284. return style->GetDefinition();
  285. }
  286. // Fills an String with the full address of this element.
  287. String Element::GetAddress(bool include_pseudo_classes) const
  288. {
  289. // Add the tag name onto the address.
  290. String address(tag);
  291. // Add the ID if we have one.
  292. if (!id.empty())
  293. {
  294. address += "#";
  295. address += id;
  296. }
  297. String classes = style->GetClassNames();
  298. if (!classes.empty())
  299. {
  300. classes = Replace(classes, ".", " ");
  301. address += ".";
  302. address += classes;
  303. }
  304. if (include_pseudo_classes)
  305. {
  306. const PseudoClassList& pseudo_classes = style->GetActivePseudoClasses();
  307. for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
  308. {
  309. address += ":";
  310. address += (*i);
  311. }
  312. }
  313. if (parent)
  314. {
  315. address += " < ";
  316. return address + parent->GetAddress(true);
  317. }
  318. else
  319. return address;
  320. }
  321. // Sets the position of this element, as a two-dimensional offset from another element.
  322. void Element::SetOffset(const Vector2f& offset, Element* _offset_parent, bool _offset_fixed)
  323. {
  324. _offset_fixed |= GetPosition() == Style::Position::Fixed;
  325. // If our offset has definitely changed, or any of our parenting has, then these are set and
  326. // updated based on our left / right / top / bottom properties.
  327. if (relative_offset_base != offset ||
  328. offset_parent != _offset_parent ||
  329. offset_fixed != _offset_fixed)
  330. {
  331. relative_offset_base = offset;
  332. offset_fixed = _offset_fixed;
  333. offset_parent = _offset_parent;
  334. UpdateOffset();
  335. DirtyOffset();
  336. }
  337. // Otherwise, our offset is updated in case left / right / top / bottom will have an impact on
  338. // our final position, and our children are dirtied if they do.
  339. else
  340. {
  341. Vector2f& old_base = relative_offset_base;
  342. Vector2f& old_position = relative_offset_position;
  343. UpdateOffset();
  344. if (old_base != relative_offset_base ||
  345. old_position != relative_offset_position)
  346. DirtyOffset();
  347. }
  348. }
  349. // Returns the position of the top-left corner of one of the areas of this element's primary box.
  350. Vector2f Element::GetRelativeOffset(Box::Area area)
  351. {
  352. return relative_offset_base + relative_offset_position + GetBox().GetPosition(area);
  353. }
  354. // Returns the position of the top-left corner of one of the areas of this element's primary box.
  355. Vector2f Element::GetAbsoluteOffset(Box::Area area)
  356. {
  357. if (offset_dirty)
  358. {
  359. offset_dirty = false;
  360. if (offset_parent != NULL)
  361. absolute_offset = offset_parent->GetAbsoluteOffset(Box::BORDER) + relative_offset_base + relative_offset_position;
  362. else
  363. absolute_offset = relative_offset_base + relative_offset_position;
  364. // Add any parent scrolling onto our position as well. Could cache this if required.
  365. if (!offset_fixed)
  366. {
  367. Element* scroll_parent = parent;
  368. while (scroll_parent != NULL)
  369. {
  370. absolute_offset -= (scroll_parent->scroll_offset + scroll_parent->content_offset);
  371. if (scroll_parent == offset_parent)
  372. break;
  373. else
  374. scroll_parent = scroll_parent->parent;
  375. }
  376. }
  377. }
  378. return absolute_offset + GetBox().GetPosition(area);
  379. }
  380. // Sets an alternate area to use as the client area.
  381. void Element::SetClientArea(Box::Area _client_area)
  382. {
  383. client_area = _client_area;
  384. }
  385. // Returns the area the element uses as its client area.
  386. Box::Area Element::GetClientArea() const
  387. {
  388. return client_area;
  389. }
  390. // Sets the dimensions of the element's internal content.
  391. void Element::SetContentBox(const Vector2f& _content_offset, const Vector2f& _content_box)
  392. {
  393. if (content_offset != _content_offset ||
  394. content_box != _content_box)
  395. {
  396. // Seems to be jittering a wee bit; might need to be looked at.
  397. scroll_offset.x += (content_offset.x - _content_offset.x);
  398. scroll_offset.y += (content_offset.y - _content_offset.y);
  399. content_offset = _content_offset;
  400. content_box = _content_box;
  401. scroll_offset.x = Math::Min(scroll_offset.x, GetScrollWidth() - GetClientWidth());
  402. scroll_offset.y = Math::Min(scroll_offset.y, GetScrollHeight() - GetClientHeight());
  403. DirtyOffset();
  404. }
  405. }
  406. // Sets the box describing the size of the element.
  407. void Element::SetBox(const Box& box)
  408. {
  409. if (box != main_box || additional_boxes.size() > 0)
  410. {
  411. main_box = box;
  412. additional_boxes.clear();
  413. box_dirty = true;
  414. background->DirtyBackground();
  415. border->DirtyBorder();
  416. decoration->DirtyDecorators(true);
  417. }
  418. }
  419. // Adds a box to the end of the list describing this element's geometry.
  420. void Element::AddBox(const Box& box)
  421. {
  422. additional_boxes.push_back(box);
  423. box_dirty = true;
  424. background->DirtyBackground();
  425. border->DirtyBorder();
  426. decoration->DirtyDecorators(true);
  427. }
  428. // Returns one of the boxes describing the size of the element.
  429. const Box& Element::GetBox()
  430. {
  431. return main_box;
  432. }
  433. // Returns one of the boxes describing the size of the element.
  434. const Box& Element::GetBox(int index)
  435. {
  436. if (index < 1)
  437. return main_box;
  438. int additional_box_index = index - 1;
  439. if (additional_box_index >= (int)additional_boxes.size())
  440. return main_box;
  441. return additional_boxes[additional_box_index];
  442. }
  443. // Returns the number of boxes making up this element's geometry.
  444. int Element::GetNumBoxes()
  445. {
  446. return 1 + (int)additional_boxes.size();
  447. }
  448. // Returns the baseline of the element, in pixels offset from the bottom of the element's content area.
  449. float Element::GetBaseline() const
  450. {
  451. return 0;
  452. }
  453. // Gets the intrinsic dimensions of this element, if it is of a type that has an inherent size.
  454. bool Element::GetIntrinsicDimensions(Vector2f& ROCKET_UNUSED_PARAMETER(dimensions))
  455. {
  456. ROCKET_UNUSED(dimensions);
  457. return false;
  458. }
  459. // Checks if a given point in screen coordinates lies within the bordered area of this element.
  460. bool Element::IsPointWithinElement(const Vector2f& point)
  461. {
  462. Vector2f position = GetAbsoluteOffset(Box::BORDER);
  463. for (int i = 0; i < GetNumBoxes(); ++i)
  464. {
  465. const Box& box = GetBox(i);
  466. Vector2f box_position = position + box.GetOffset();
  467. Vector2f box_dimensions = box.GetSize(Box::BORDER);
  468. if (point.x >= box_position.x &&
  469. point.x <= (box_position.x + box_dimensions.x) &&
  470. point.y >= box_position.y &&
  471. point.y <= (box_position.y + box_dimensions.y))
  472. {
  473. return true;
  474. }
  475. }
  476. return false;
  477. }
  478. // Returns the visibility of the element.
  479. bool Element::IsVisible() const
  480. {
  481. return visible;
  482. }
  483. // Returns the z-index of the element.
  484. float Element::GetZIndex() const
  485. {
  486. return z_index;
  487. }
  488. // Returns the element's font face handle.
  489. FontFaceHandle* Element::GetFontFaceHandle() const
  490. {
  491. return font_face_handle;
  492. }
  493. // Sets a local property override on the element.
  494. bool Element::SetProperty(const String& name, const String& value)
  495. {
  496. return style->SetProperty(name, value);
  497. }
  498. // Removes a local property override on the element.
  499. void Element::RemoveProperty(const String& name)
  500. {
  501. style->RemoveProperty(name);
  502. }
  503. // Sets a local property override on the element to a pre-parsed value.
  504. bool Element::SetProperty(const String& name, const Property& property)
  505. {
  506. return style->SetProperty(name, property);
  507. }
  508. // Returns one of this element's properties.
  509. const Property* Element::GetProperty(const String& name)
  510. {
  511. return style->GetProperty(name);
  512. }
  513. // Returns one of this element's properties.
  514. const Property* Element::GetLocalProperty(const String& name)
  515. {
  516. return style->GetLocalProperty(name);
  517. }
  518. const PropertyMap * Element::GetLocalProperties()
  519. {
  520. return style->GetLocalProperties();
  521. }
  522. // Resolves one of this element's style.
  523. float Element::ResolveLengthPercentage(const Property *property, float base_value)
  524. {
  525. return style->ResolveLengthPercentage(property, base_value);
  526. }
  527. Vector2f Element::GetContainingBlock()
  528. {
  529. Vector2f containing_block(0, 0);
  530. if (offset_parent != NULL)
  531. {
  532. using namespace Style;
  533. Position position_property = GetPosition();
  534. const Box& parent_box = offset_parent->GetBox();
  535. if (position_property == Position::Static || position_property == Position::Relative)
  536. {
  537. containing_block = parent_box.GetSize();
  538. }
  539. else if(position_property == Position::Absolute || position_property == Position::Fixed)
  540. {
  541. containing_block = parent_box.GetSize(Box::PADDING);
  542. }
  543. }
  544. return containing_block;
  545. }
  546. Style::Position Element::GetPosition()
  547. {
  548. return element_meta->computed_values.position;
  549. }
  550. Style::Float Element::GetFloat()
  551. {
  552. return element_meta->computed_values.float_;
  553. }
  554. Style::Display Element::GetDisplay()
  555. {
  556. return element_meta->computed_values.display;
  557. }
  558. float Element::GetLineHeight()
  559. {
  560. return element_meta->computed_values.line_height.value;
  561. }
  562. // Returns this element's TransformState
  563. const TransformState *Element::GetTransformState() const noexcept
  564. {
  565. return transform_state.get();
  566. }
  567. // Returns the TransformStates that are effective for this element.
  568. void Element::GetEffectiveTransformState(
  569. const TransformState **local_perspective,
  570. const TransformState **perspective,
  571. const TransformState **transform
  572. ) const noexcept
  573. {
  574. if (local_perspective)
  575. {
  576. *local_perspective = nullptr;
  577. }
  578. if (perspective)
  579. {
  580. *perspective = nullptr;
  581. }
  582. if (transform)
  583. {
  584. *transform = nullptr;
  585. }
  586. const Element *perspective_node = nullptr, *transform_node = nullptr;
  587. // Find the TransformState to use for unprojecting.
  588. if (transform_state.get() && transform_state->GetLocalPerspective(nullptr))
  589. {
  590. if (local_perspective)
  591. {
  592. *local_perspective = transform_state.get();
  593. }
  594. }
  595. else
  596. {
  597. const Element *node = nullptr;
  598. for (node = parent; node; node = node->parent)
  599. {
  600. if (node->transform_state.get() && node->transform_state->GetPerspective(nullptr))
  601. {
  602. if (perspective)
  603. {
  604. *perspective = node->transform_state.get();
  605. }
  606. perspective_node = node;
  607. break;
  608. }
  609. }
  610. }
  611. // Find the TransformState to use for transforming.
  612. const Element *node = nullptr;
  613. for (node = this; node; node = node->parent)
  614. {
  615. if (node->transform_state.get() && node->transform_state->GetRecursiveTransform(nullptr))
  616. {
  617. if (transform)
  618. {
  619. *transform = node->transform_state.get();
  620. }
  621. transform_node = node;
  622. break;
  623. }
  624. }
  625. }
  626. // Project a 2D point in pixel coordinates onto the element's plane.
  627. Vector2f Element::Project(const Vector2f& point) const noexcept
  628. {
  629. const 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() const
  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(EventId::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(EventId::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. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  1088. event_dispatcher->AttachEvent(id, listener, in_capture_phase);
  1089. }
  1090. // Removes an event listener from this element.
  1091. void Element::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  1092. {
  1093. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  1094. event_dispatcher->DetachEvent(id, listener, in_capture_phase);
  1095. }
  1096. // Dispatches the specified event
  1097. bool Element::DispatchEvent(const String& type, const Dictionary& parameters)
  1098. {
  1099. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  1100. return event_dispatcher->DispatchEvent(this, specification.id, type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
  1101. }
  1102. // Dispatches the specified event
  1103. bool Element::DispatchEvent(const String& type, const Dictionary& parameters, bool interruptible, bool bubbles)
  1104. {
  1105. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  1106. return event_dispatcher->DispatchEvent(this, specification.id, type, parameters, interruptible, bubbles, specification.default_action_phase);
  1107. }
  1108. // Dispatches the specified event
  1109. bool Element::DispatchEvent(EventId id, const Dictionary& parameters)
  1110. {
  1111. const EventSpecification& specification = EventSpecificationInterface::Get(id);
  1112. return event_dispatcher->DispatchEvent(this, specification.id, specification.type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
  1113. }
  1114. // Scrolls the parent element's contents so that this element is visible.
  1115. void Element::ScrollIntoView(bool align_with_top)
  1116. {
  1117. Vector2f size(0, 0);
  1118. if (!align_with_top)
  1119. {
  1120. size.y = main_box.GetOffset().y +
  1121. main_box.GetSize(Box::BORDER).y;
  1122. }
  1123. Element* scroll_parent = parent;
  1124. while (scroll_parent != NULL)
  1125. {
  1126. Style::Overflow overflow_x_property = scroll_parent->GetComputedValues().overflow_x;
  1127. Style::Overflow overflow_y_property = scroll_parent->GetComputedValues().overflow_y;
  1128. if ((overflow_x_property != Style::Overflow::Visible &&
  1129. scroll_parent->GetScrollWidth() > scroll_parent->GetClientWidth()) ||
  1130. (overflow_y_property != Style::Overflow::Visible &&
  1131. scroll_parent->GetScrollHeight() > scroll_parent->GetClientHeight()))
  1132. {
  1133. Vector2f offset = scroll_parent->GetAbsoluteOffset(Box::BORDER) - GetAbsoluteOffset(Box::BORDER);
  1134. Vector2f scroll_offset(scroll_parent->GetScrollLeft(), scroll_parent->GetScrollTop());
  1135. scroll_offset -= offset;
  1136. scroll_offset.x += scroll_parent->GetClientLeft();
  1137. scroll_offset.y += scroll_parent->GetClientTop();
  1138. if (!align_with_top)
  1139. scroll_offset.y -= (scroll_parent->GetClientHeight() - size.y);
  1140. if (overflow_x_property != Style::Overflow::Visible)
  1141. scroll_parent->SetScrollLeft(scroll_offset.x);
  1142. if (overflow_y_property != Style::Overflow::Visible)
  1143. scroll_parent->SetScrollTop(scroll_offset.y);
  1144. }
  1145. scroll_parent = scroll_parent->GetParentNode();
  1146. }
  1147. }
  1148. // Appends a child to this element
  1149. void Element::AppendChild(Element* child, bool dom_element)
  1150. {
  1151. child->AddReference();
  1152. child->SetParent(this);
  1153. if (dom_element)
  1154. children.insert(children.end() - num_non_dom_children, child);
  1155. else
  1156. {
  1157. children.push_back(child);
  1158. num_non_dom_children++;
  1159. }
  1160. child->GetStyle()->DirtyDefinition();
  1161. Element* ancestor = child;
  1162. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1163. ancestor->OnChildAdd(child);
  1164. DirtyStackingContext();
  1165. DirtyStructure();
  1166. if (dom_element)
  1167. DirtyLayout();
  1168. }
  1169. // Adds a child to this element, directly after the adjacent element. Inherits
  1170. // the dom/non-dom status from the adjacent element.
  1171. void Element::InsertBefore(Element* child, Element* adjacent_element)
  1172. {
  1173. // Find the position in the list of children of the adjacent element. If
  1174. // it's NULL or we can't find it, then we insert it at the end of the dom
  1175. // children, as a dom element.
  1176. size_t child_index = 0;
  1177. bool found_child = false;
  1178. if (adjacent_element)
  1179. {
  1180. for (child_index = 0; child_index < children.size(); child_index++)
  1181. {
  1182. if (children[child_index] == adjacent_element)
  1183. {
  1184. found_child = true;
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. if (found_child)
  1190. {
  1191. child->AddReference();
  1192. child->SetParent(this);
  1193. if ((int) child_index >= GetNumChildren())
  1194. num_non_dom_children++;
  1195. else
  1196. DirtyLayout();
  1197. children.insert(children.begin() + child_index, child);
  1198. child->GetStyle()->DirtyDefinition();
  1199. Element* ancestor = child;
  1200. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1201. ancestor->OnChildAdd(child);
  1202. DirtyStackingContext();
  1203. DirtyStructure();
  1204. }
  1205. else
  1206. {
  1207. AppendChild(child);
  1208. }
  1209. }
  1210. // Replaces the second node with the first node.
  1211. bool Element::ReplaceChild(Element* inserted_element, Element* replaced_element)
  1212. {
  1213. ElementList::iterator insertion_point = children.begin();
  1214. while (insertion_point != children.end() && *insertion_point != replaced_element)
  1215. {
  1216. ++insertion_point;
  1217. }
  1218. if (insertion_point == children.end())
  1219. {
  1220. AppendChild(inserted_element);
  1221. return false;
  1222. }
  1223. inserted_element->AddReference();
  1224. inserted_element->SetParent(this);
  1225. children.insert(insertion_point, inserted_element);
  1226. RemoveChild(replaced_element);
  1227. inserted_element->GetStyle()->DirtyDefinition();
  1228. Element* ancestor = inserted_element;
  1229. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1230. ancestor->OnChildAdd(inserted_element);
  1231. return true;
  1232. }
  1233. // Removes the specified child
  1234. bool Element::RemoveChild(Element* child)
  1235. {
  1236. size_t child_index = 0;
  1237. for (ElementList::iterator itr = children.begin(); itr != children.end(); ++itr)
  1238. {
  1239. // Add the element to the delete list
  1240. if ((*itr) == child)
  1241. {
  1242. // Inform the context of the element's pending removal (if we have a valid context).
  1243. Context* context = GetContext();
  1244. if (context)
  1245. context->OnElementRemove(child);
  1246. Element* ancestor = child;
  1247. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1248. ancestor->OnChildRemove(child);
  1249. if (child_index >= children.size() - num_non_dom_children)
  1250. num_non_dom_children--;
  1251. deleted_children.push_back(child);
  1252. children.erase(itr);
  1253. // Remove the child element as the focussed child of this element.
  1254. if (child == focus)
  1255. {
  1256. focus = NULL;
  1257. // If this child (or a descendant of this child) is the context's currently
  1258. // focussed element, set the focus to us instead.
  1259. Context* context = GetContext();
  1260. if (context != NULL)
  1261. {
  1262. Element* focus_element = context->GetFocusElement();
  1263. while (focus_element != NULL)
  1264. {
  1265. if (focus_element == child)
  1266. {
  1267. Focus();
  1268. break;
  1269. }
  1270. focus_element = focus_element->GetParentNode();
  1271. }
  1272. }
  1273. }
  1274. DirtyLayout();
  1275. DirtyStackingContext();
  1276. DirtyStructure();
  1277. return true;
  1278. }
  1279. child_index++;
  1280. }
  1281. return false;
  1282. }
  1283. bool Element::HasChildNodes() const
  1284. {
  1285. return (int) children.size() > num_non_dom_children;
  1286. }
  1287. Element* Element::GetElementById(const String& id)
  1288. {
  1289. // Check for special-case tokens.
  1290. if (id == "#self")
  1291. return this;
  1292. else if (id == "#document")
  1293. return GetOwnerDocument();
  1294. else if (id == "#parent")
  1295. return this->parent;
  1296. else
  1297. {
  1298. Element* search_root = GetOwnerDocument();
  1299. if (search_root == NULL)
  1300. search_root = this;
  1301. return ElementUtilities::GetElementById(search_root, id);
  1302. }
  1303. }
  1304. // Get all elements with the given tag.
  1305. void Element::GetElementsByTagName(ElementList& elements, const String& tag)
  1306. {
  1307. return ElementUtilities::GetElementsByTagName(elements, this, tag);
  1308. }
  1309. // Get all elements with the given class set on them.
  1310. void Element::GetElementsByClassName(ElementList& elements, const String& class_name)
  1311. {
  1312. return ElementUtilities::GetElementsByClassName(elements, this, class_name);
  1313. }
  1314. // Access the event dispatcher
  1315. EventDispatcher* Element::GetEventDispatcher() const
  1316. {
  1317. return event_dispatcher;
  1318. }
  1319. String Element::GetEventDispatcherSummary() const
  1320. {
  1321. return event_dispatcher->ToString();
  1322. }
  1323. // Access the element background.
  1324. ElementBackground* Element::GetElementBackground() const
  1325. {
  1326. return background;
  1327. }
  1328. // Access the element border.
  1329. ElementBorder* Element::GetElementBorder() const
  1330. {
  1331. return border;
  1332. }
  1333. // Access the element decorators
  1334. ElementDecoration* Element::GetElementDecoration() const
  1335. {
  1336. return decoration;
  1337. }
  1338. // Returns the element's scrollbar functionality.
  1339. ElementScroll* Element::GetElementScroll() const
  1340. {
  1341. return scroll;
  1342. }
  1343. int Element::GetClippingIgnoreDepth()
  1344. {
  1345. if (clipping_state_dirty)
  1346. {
  1347. IsClippingEnabled();
  1348. }
  1349. return clipping_ignore_depth;
  1350. }
  1351. bool Element::IsClippingEnabled()
  1352. {
  1353. if (clipping_state_dirty)
  1354. {
  1355. const auto& computed = GetComputedValues();
  1356. // Is clipping enabled for this element, yes unless both overlow properties are set to visible
  1357. clipping_enabled = computed.overflow_x != Style::Overflow::Visible
  1358. || computed.overflow_y != Style::Overflow::Visible;
  1359. // Get the clipping ignore depth from the clip property
  1360. clipping_ignore_depth = computed.clip.number;
  1361. clipping_state_dirty = false;
  1362. }
  1363. return clipping_enabled;
  1364. }
  1365. // Gets the render interface owned by this element's context.
  1366. RenderInterface* Element::GetRenderInterface()
  1367. {
  1368. Context* context = GetContext();
  1369. if (context != NULL)
  1370. return context->GetRenderInterface();
  1371. return Rocket::Core::GetRenderInterface();
  1372. }
  1373. void Element::SetInstancer(ElementInstancer* _instancer)
  1374. {
  1375. // Only record the first instancer being set as some instancers call other instancers to do their dirty work, in
  1376. // which case we don't want to update the lowest level instancer.
  1377. if (instancer == NULL)
  1378. {
  1379. instancer = _instancer;
  1380. instancer->AddReference();
  1381. }
  1382. }
  1383. // Forces the element to generate a local stacking context, regardless of the value of its z-index property.
  1384. void Element::ForceLocalStackingContext()
  1385. {
  1386. local_stacking_context_forced = true;
  1387. local_stacking_context = true;
  1388. DirtyStackingContext();
  1389. }
  1390. // Called during the update loop after children are rendered.
  1391. void Element::OnUpdate()
  1392. {
  1393. }
  1394. // Called during render after backgrounds, borders, decorators, but before children, are rendered.
  1395. void Element::OnRender()
  1396. {
  1397. }
  1398. void Element::OnResize()
  1399. {
  1400. }
  1401. // Called during a layout operation, when the element is being positioned and sized.
  1402. void Element::OnLayout()
  1403. {
  1404. }
  1405. // Called when attributes on the element are changed.
  1406. void Element::OnAttributeChange(const AttributeNameList& changed_attributes)
  1407. {
  1408. if (changed_attributes.find("id") != changed_attributes.end())
  1409. {
  1410. id = GetAttribute< String >("id", "");
  1411. style->DirtyDefinition();
  1412. }
  1413. if (changed_attributes.find("class") != changed_attributes.end())
  1414. {
  1415. style->SetClassNames(GetAttribute< String >("class", ""));
  1416. }
  1417. // Add any inline style declarations.
  1418. if (changed_attributes.find("style") != changed_attributes.end())
  1419. {
  1420. PropertyDictionary properties;
  1421. StyleSheetParser parser;
  1422. parser.ParseProperties(properties, GetAttribute< String >("style", ""));
  1423. Rocket::Core::PropertyMap property_map = properties.GetProperties();
  1424. for (Rocket::Core::PropertyMap::iterator i = property_map.begin(); i != property_map.end(); ++i)
  1425. {
  1426. SetProperty((*i).first, (*i).second);
  1427. }
  1428. }
  1429. }
  1430. // Called when properties on the element are changed.
  1431. void Element::OnPropertyChange(const PropertyNameList& changed_properties)
  1432. {
  1433. bool all_dirty = false;
  1434. {
  1435. auto& registered_properties = StyleSheetSpecification::GetRegisteredProperties();
  1436. if (&registered_properties == &changed_properties || registered_properties == changed_properties)
  1437. all_dirty = true;
  1438. }
  1439. if (!IsLayoutDirty())
  1440. {
  1441. if (all_dirty)
  1442. {
  1443. DirtyLayout();
  1444. }
  1445. else
  1446. {
  1447. // Force a relayout if any of the changed properties require it.
  1448. for (PropertyNameList::const_iterator i = changed_properties.begin(); i != changed_properties.end(); ++i)
  1449. {
  1450. const PropertyDefinition* property_definition = StyleSheetSpecification::GetProperty(*i);
  1451. if (property_definition)
  1452. {
  1453. if (property_definition->IsLayoutForced())
  1454. {
  1455. DirtyLayout();
  1456. break;
  1457. }
  1458. }
  1459. }
  1460. }
  1461. }
  1462. // Update the visibility.
  1463. if (all_dirty || changed_properties.find(VISIBILITY) != changed_properties.end() ||
  1464. changed_properties.find(DISPLAY) != changed_properties.end())
  1465. {
  1466. bool new_visibility = (element_meta->computed_values.display != Style::Display::None && element_meta->computed_values.visibility == Style::Visibility::Visible);
  1467. if (visible != new_visibility)
  1468. {
  1469. visible = new_visibility;
  1470. if (parent != NULL)
  1471. parent->DirtyStackingContext();
  1472. }
  1473. if (all_dirty ||
  1474. changed_properties.find(DISPLAY) != changed_properties.end())
  1475. {
  1476. if (parent != NULL)
  1477. parent->DirtyStructure();
  1478. }
  1479. }
  1480. // Fetch a new font face if it has been changed.
  1481. if (all_dirty ||
  1482. changed_properties.find(FONT_FAMILY) != changed_properties.end() ||
  1483. changed_properties.find(FONT_CHARSET) != changed_properties.end() ||
  1484. changed_properties.find(FONT_WEIGHT) != changed_properties.end() ||
  1485. changed_properties.find(FONT_STYLE) != changed_properties.end() ||
  1486. changed_properties.find(FONT_SIZE) != changed_properties.end())
  1487. {
  1488. // Fetch the new font face.
  1489. FontFaceHandle* new_font_face_handle = ElementUtilities::GetFontFaceHandle(element_meta->computed_values);
  1490. // If this is different from our current font face, then we've got to nuke
  1491. // all our characters and tell our parent that we have to be re-laid out.
  1492. if (new_font_face_handle != font_face_handle)
  1493. {
  1494. if (font_face_handle)
  1495. font_face_handle->RemoveReference();
  1496. font_face_handle = new_font_face_handle;
  1497. }
  1498. else if (new_font_face_handle != NULL)
  1499. new_font_face_handle->RemoveReference();
  1500. }
  1501. // Update the position.
  1502. if (all_dirty ||
  1503. changed_properties.find(LEFT) != changed_properties.end() ||
  1504. changed_properties.find(RIGHT) != changed_properties.end() ||
  1505. changed_properties.find(TOP) != changed_properties.end() ||
  1506. changed_properties.find(BOTTOM) != changed_properties.end())
  1507. {
  1508. // TODO: This should happen during/after layout, as the containing box is not properly defined yet
  1509. UpdateOffset();
  1510. DirtyOffset();
  1511. }
  1512. // Update the z-index.
  1513. if (all_dirty ||
  1514. changed_properties.find(Z_INDEX) != changed_properties.end())
  1515. {
  1516. Style::ZIndex z_index_property = element_meta->computed_values.z_index;
  1517. if (z_index_property.type == Style::ZIndex::Auto)
  1518. {
  1519. if (local_stacking_context &&
  1520. !local_stacking_context_forced)
  1521. {
  1522. // We're no longer acting as a stacking context.
  1523. local_stacking_context = false;
  1524. stacking_context_dirty = false;
  1525. stacking_context.clear();
  1526. }
  1527. // If our old z-index was not zero, then we must dirty our stacking context so we'll be re-indexed.
  1528. if (z_index != 0)
  1529. {
  1530. z_index = 0;
  1531. DirtyStackingContext();
  1532. }
  1533. }
  1534. else
  1535. {
  1536. float new_z_index = z_index_property.value;
  1537. if (new_z_index != z_index)
  1538. {
  1539. z_index = new_z_index;
  1540. if (parent != NULL)
  1541. parent->DirtyStackingContext();
  1542. }
  1543. if (!local_stacking_context)
  1544. {
  1545. local_stacking_context = true;
  1546. stacking_context_dirty = true;
  1547. }
  1548. }
  1549. }
  1550. // Dirty the background if it's changed.
  1551. if (all_dirty ||
  1552. changed_properties.find(BACKGROUND_COLOR) != changed_properties.end() ||
  1553. changed_properties.find(OPACITY) != changed_properties.end() ||
  1554. changed_properties.find(IMAGE_COLOR) != changed_properties.end()) {
  1555. background->DirtyBackground();
  1556. decoration->DirtyDecorators(true);
  1557. }
  1558. // Dirty the border if it's changed.
  1559. if (all_dirty ||
  1560. changed_properties.find(BORDER_TOP_WIDTH) != changed_properties.end() ||
  1561. changed_properties.find(BORDER_RIGHT_WIDTH) != changed_properties.end() ||
  1562. changed_properties.find(BORDER_BOTTOM_WIDTH) != changed_properties.end() ||
  1563. changed_properties.find(BORDER_LEFT_WIDTH) != changed_properties.end() ||
  1564. changed_properties.find(BORDER_TOP_COLOR) != changed_properties.end() ||
  1565. changed_properties.find(BORDER_RIGHT_COLOR) != changed_properties.end() ||
  1566. changed_properties.find(BORDER_BOTTOM_COLOR) != changed_properties.end() ||
  1567. changed_properties.find(BORDER_LEFT_COLOR) != changed_properties.end() ||
  1568. changed_properties.find(OPACITY) != changed_properties.end())
  1569. border->DirtyBorder();
  1570. // Check for clipping state changes
  1571. if (all_dirty ||
  1572. changed_properties.find(CLIP) != changed_properties.end() ||
  1573. changed_properties.find(OVERFLOW_X) != changed_properties.end() ||
  1574. changed_properties.find(OVERFLOW_Y) != changed_properties.end())
  1575. {
  1576. clipping_state_dirty = true;
  1577. }
  1578. // Check for `perspective' and `perspective-origin' changes
  1579. if (all_dirty ||
  1580. changed_properties.find(PERSPECTIVE) != changed_properties.end() ||
  1581. changed_properties.find(PERSPECTIVE_ORIGIN_X) != changed_properties.end() ||
  1582. changed_properties.find(PERSPECTIVE_ORIGIN_Y) != changed_properties.end())
  1583. {
  1584. DirtyTransformState(true, false, false);
  1585. }
  1586. // Check for `transform' and `transform-origin' changes
  1587. if (all_dirty ||
  1588. changed_properties.find(TRANSFORM) != changed_properties.end() ||
  1589. changed_properties.find(TRANSFORM_ORIGIN_X) != changed_properties.end() ||
  1590. changed_properties.find(TRANSFORM_ORIGIN_Y) != changed_properties.end() ||
  1591. changed_properties.find(TRANSFORM_ORIGIN_Z) != changed_properties.end())
  1592. {
  1593. DirtyTransformState(false, true, false);
  1594. }
  1595. // Check for `animation' changes
  1596. if (all_dirty || changed_properties.find(ANIMATION) != changed_properties.end())
  1597. {
  1598. DirtyAnimation();
  1599. }
  1600. }
  1601. // Called when a child node has been added somewhere in the hierarchy
  1602. void Element::OnChildAdd(Element* child)
  1603. {
  1604. }
  1605. // Called when a child node has been removed somewhere in the hierarchy
  1606. void Element::OnChildRemove(Element* child)
  1607. {
  1608. }
  1609. // Forces a re-layout of this element, and any other children required.
  1610. void Element::DirtyLayout()
  1611. {
  1612. Element* document = GetOwnerDocument();
  1613. if (document != NULL)
  1614. document->DirtyLayout();
  1615. }
  1616. // Forces a re-layout of this element, and any other children required.
  1617. bool Element::IsLayoutDirty()
  1618. {
  1619. Element* document = GetOwnerDocument();
  1620. if (document != NULL)
  1621. return document->IsLayoutDirty();
  1622. return false;
  1623. }
  1624. // Forces a reevaluation of applicable font effects.
  1625. void Element::DirtyFont()
  1626. {
  1627. for (size_t i = 0; i < children.size(); ++i)
  1628. children[i]->DirtyFont();
  1629. }
  1630. void Element::OnReferenceDeactivate()
  1631. {
  1632. if (instancer)
  1633. {
  1634. instancer->ReleaseElement(this);
  1635. }
  1636. else
  1637. {
  1638. // Hopefully we can just delete ourselves.
  1639. //delete this;
  1640. Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via Rocket Factory. Unable to release.", GetAddress().c_str());
  1641. }
  1642. }
  1643. void Element::ProcessDefaultAction(Event& event)
  1644. {
  1645. if (event == EventId::Mousedown && IsPointWithinElement(Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0))) &&
  1646. event.GetParameter< int >("button", 0) == 0)
  1647. SetPseudoClass("active", true);
  1648. if (event == EventId::Mousescroll)
  1649. {
  1650. if (GetScrollHeight() > GetClientHeight())
  1651. {
  1652. Style::Overflow overflow_property = element_meta->computed_values.overflow_y;
  1653. if (overflow_property == Style::Overflow::Auto ||
  1654. overflow_property == Style::Overflow::Scroll)
  1655. {
  1656. // Stop the propagation if the current element has scrollbars.
  1657. // This prevents scrolling in parent elements, which is often unintended. If instead desired behavior is
  1658. // to scroll in parent elements when reaching top/bottom, move StopPropagation inside the next if statement.
  1659. event.StopPropagation();
  1660. const float wheel_delta = event.GetParameter< float >("wheel_delta", 0.f);
  1661. if ((wheel_delta < 0 && GetScrollTop() > 0) ||
  1662. (wheel_delta > 0 && GetScrollHeight() > GetScrollTop() + GetClientHeight()))
  1663. {
  1664. // Defined as three times the default line-height, multiplied by the dp ratio.
  1665. float default_scroll_length = 3.f * DefaultComputedValues.line_height.value;
  1666. if (const Context* context = GetContext())
  1667. default_scroll_length *= context->GetDensityIndependentPixelRatio();
  1668. SetScrollTop(GetScrollTop() + Math::RoundFloat(wheel_delta * default_scroll_length));
  1669. }
  1670. }
  1671. }
  1672. return;
  1673. }
  1674. if (event.GetPhase() == EventPhase::Target)
  1675. {
  1676. switch (event.GetId())
  1677. {
  1678. case EventId::Mouseover:
  1679. SetPseudoClass("hover", true);
  1680. break;
  1681. case EventId::Mouseout:
  1682. SetPseudoClass("hover", false);
  1683. break;
  1684. case EventId::Focus:
  1685. SetPseudoClass(FOCUS, true);
  1686. break;
  1687. case EventId::Blur:
  1688. SetPseudoClass(FOCUS, false);
  1689. break;
  1690. default:
  1691. break;
  1692. }
  1693. }
  1694. }
  1695. const Style::ComputedValues& Element::GetComputedValues() const
  1696. {
  1697. return element_meta->computed_values;
  1698. }
  1699. void Element::GetRML(String& content)
  1700. {
  1701. // First we start the open tag, add the attributes then close the open tag.
  1702. // Then comes the children in order, then we add our close tag.
  1703. content += "<";
  1704. content += tag;
  1705. for( auto& pair : attributes)
  1706. {
  1707. auto& name = pair.first;
  1708. auto& variant = pair.second;
  1709. String value;
  1710. if (variant.GetInto(value))
  1711. content += " " + name + "=\"" + value + "\"";
  1712. }
  1713. if (HasChildNodes())
  1714. {
  1715. content += ">";
  1716. GetInnerRML(content);
  1717. content += "</";
  1718. content += tag;
  1719. content += ">";
  1720. }
  1721. else
  1722. {
  1723. content += " />";
  1724. }
  1725. }
  1726. void Element::SetOwnerDocument(ElementDocument* document)
  1727. {
  1728. // If this element is a document, then never change owner_document. Otherwise, this can happen when attaching to the root element.
  1729. if(owner_document != document && owner_document != this)
  1730. {
  1731. owner_document = document;
  1732. for (Element* child : children)
  1733. child->SetOwnerDocument(document);
  1734. }
  1735. }
  1736. void Element::SetParent(Element* _parent)
  1737. {
  1738. // If there's an old parent, detach from it first.
  1739. if (parent &&
  1740. parent != _parent)
  1741. parent->RemoveChild(this);
  1742. parent = _parent;
  1743. SetOwnerDocument(parent ? parent->GetOwnerDocument() : nullptr);
  1744. }
  1745. void Element::ReleaseElements(ElementList& released_elements)
  1746. {
  1747. // Remove deleted children from this element.
  1748. while (!released_elements.empty())
  1749. {
  1750. Element* element = released_elements.back();
  1751. released_elements.pop_back();
  1752. // If this element has been added back into our list, then we remove our previous oustanding reference on it
  1753. // and continue.
  1754. if (std::find(children.begin(), children.end(), element) != children.end())
  1755. {
  1756. element->RemoveReference();
  1757. continue;
  1758. }
  1759. // Set the parent to NULL unless it's been reparented already.
  1760. if (element->GetParentNode() == this)
  1761. {
  1762. element->parent = nullptr;
  1763. element->SetOwnerDocument(nullptr);
  1764. }
  1765. element->RemoveReference();
  1766. }
  1767. }
  1768. void Element::DirtyOffset()
  1769. {
  1770. offset_dirty = true;
  1771. if(transform_state)
  1772. DirtyTransformState(true, true, false);
  1773. // Not strictly true ... ?
  1774. for (size_t i = 0; i < children.size(); i++)
  1775. children[i]->DirtyOffset();
  1776. }
  1777. void Element::UpdateOffset()
  1778. {
  1779. using namespace Style;
  1780. const auto& computed = element_meta->computed_values;
  1781. Position position_property = computed.position;
  1782. if (position_property == Position::Absolute ||
  1783. position_property == Position::Fixed)
  1784. {
  1785. if (offset_parent != NULL)
  1786. {
  1787. const Box& parent_box = offset_parent->GetBox();
  1788. Vector2f containing_block = parent_box.GetSize(Box::PADDING);
  1789. // If the element is anchored left, then the position is offset by that resolved value.
  1790. if (computed.left.type != Left::Auto)
  1791. relative_offset_base.x = parent_box.GetEdge(Box::BORDER, Box::LEFT) + (ResolveValue(computed.left, containing_block.x) + GetBox().GetEdge(Box::MARGIN, Box::LEFT));
  1792. // If the element is anchored right, then the position is set first so the element's right-most edge
  1793. // (including margins) will render up against the containing box's right-most content edge, and then
  1794. // offset by the resolved value.
  1795. else if (computed.right.type != Right::Auto)
  1796. relative_offset_base.x = containing_block.x + parent_box.GetEdge(Box::BORDER, Box::LEFT) - (ResolveValue(computed.right, containing_block.x) + GetBox().GetSize(Box::BORDER).x + GetBox().GetEdge(Box::MARGIN, Box::RIGHT));
  1797. // If the element is anchored top, then the position is offset by that resolved value.
  1798. if (computed.top.type != Top::Auto)
  1799. relative_offset_base.y = parent_box.GetEdge(Box::BORDER, Box::TOP) + (ResolveValue(computed.top, containing_block.y) + GetBox().GetEdge(Box::MARGIN, Box::TOP));
  1800. // If the element is anchored bottom, then the position is set first so the element's right-most edge
  1801. // (including margins) will render up against the containing box's right-most content edge, and then
  1802. // offset by the resolved value.
  1803. else if (computed.bottom.type != Bottom::Auto)
  1804. relative_offset_base.y = containing_block.y + parent_box.GetEdge(Box::BORDER, Box::TOP) - (ResolveValue(computed.bottom, containing_block.y) + GetBox().GetSize(Box::BORDER).y + GetBox().GetEdge(Box::MARGIN, Box::BOTTOM));
  1805. }
  1806. }
  1807. else if (position_property == Position::Relative)
  1808. {
  1809. if (offset_parent != NULL)
  1810. {
  1811. const Box& parent_box = offset_parent->GetBox();
  1812. Vector2f containing_block = parent_box.GetSize();
  1813. if (computed.left.type != Left::Auto)
  1814. relative_offset_position.x = ResolveValue(computed.left, containing_block.x);
  1815. else if (computed.right.type != Right::Auto)
  1816. relative_offset_position.x = -1 * ResolveValue(computed.right, containing_block.x);
  1817. else
  1818. relative_offset_position.x = 0;
  1819. if (computed.top.type != Top::Auto)
  1820. relative_offset_position.y = ResolveValue(computed.top, containing_block.y);
  1821. else if (computed.bottom.type != Bottom::Auto)
  1822. relative_offset_position.y = -1 * ResolveValue(computed.bottom, containing_block.y);
  1823. else
  1824. relative_offset_position.y = 0;
  1825. }
  1826. }
  1827. else
  1828. {
  1829. relative_offset_position.x = 0;
  1830. relative_offset_position.y = 0;
  1831. }
  1832. }
  1833. void Element::BuildLocalStackingContext()
  1834. {
  1835. stacking_context_dirty = false;
  1836. stacking_context.clear();
  1837. BuildStackingContext(&stacking_context);
  1838. std::stable_sort(stacking_context.begin(), stacking_context.end(), ElementSortZIndex());
  1839. }
  1840. void Element::BuildStackingContext(ElementList* new_stacking_context)
  1841. {
  1842. // Build the list of ordered children. Our child list is sorted within the stacking context so stacked elements
  1843. // will render in the right order; ie, positioned elements will render on top of inline elements, which will render
  1844. // on top of floated elements, which will render on top of block elements.
  1845. std::vector< std::pair< Element*, float > > ordered_children;
  1846. for (size_t i = 0; i < children.size(); ++i)
  1847. {
  1848. Element* child = children[i];
  1849. if (!child->IsVisible())
  1850. continue;
  1851. std::pair< Element*, float > ordered_child;
  1852. ordered_child.first = child;
  1853. if (child->GetPosition() != Style::Position::Static)
  1854. ordered_child.second = 3;
  1855. else if (child->GetFloat() != Style::Float::None)
  1856. ordered_child.second = 1;
  1857. else if (child->GetDisplay() == Style::Display::Block)
  1858. ordered_child.second = 0;
  1859. else
  1860. ordered_child.second = 2;
  1861. ordered_children.push_back(ordered_child);
  1862. }
  1863. // Sort the list!
  1864. std::stable_sort(ordered_children.begin(), ordered_children.end(), ElementSortZOrder());
  1865. // Add the list of ordered children into the stacking context in order.
  1866. for (size_t i = 0; i < ordered_children.size(); ++i)
  1867. {
  1868. new_stacking_context->push_back(ordered_children[i].first);
  1869. if (!ordered_children[i].first->local_stacking_context)
  1870. ordered_children[i].first->BuildStackingContext(new_stacking_context);
  1871. }
  1872. }
  1873. void Element::DirtyStackingContext()
  1874. {
  1875. // The first ancestor of ours that doesn't have an automatic z-index is the ancestor that is establishing our local
  1876. // stacking context.
  1877. Element* stacking_context_parent = this;
  1878. while (stacking_context_parent != NULL &&
  1879. !stacking_context_parent->local_stacking_context)
  1880. stacking_context_parent = stacking_context_parent->GetParentNode();
  1881. if (stacking_context_parent != NULL)
  1882. stacking_context_parent->stacking_context_dirty = true;
  1883. }
  1884. void Element::DirtyStructure()
  1885. {
  1886. // Clear the cached owner document
  1887. structure_dirty = true;
  1888. }
  1889. void Element::DirtyParentStructure()
  1890. {
  1891. parent_structure_dirty = true;
  1892. }
  1893. void Element::UpdateStructure()
  1894. {
  1895. if (parent_structure_dirty)
  1896. {
  1897. // If children depend on structured selectors, they may need to be updated
  1898. const ElementDefinition* element_definition = GetStyle()->GetDefinition();
  1899. if (element_definition != NULL && element_definition->IsStructurallyVolatile())
  1900. {
  1901. GetStyle()->DirtyDefinition();
  1902. }
  1903. }
  1904. if (structure_dirty || parent_structure_dirty)
  1905. {
  1906. for (size_t i = 0; i < children.size(); ++i)
  1907. children[i]->DirtyParentStructure();
  1908. structure_dirty = false;
  1909. parent_structure_dirty = false;
  1910. }
  1911. }
  1912. 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)
  1913. {
  1914. bool result = false;
  1915. auto it_animation = StartAnimation(property_name, start_value, num_iterations, alternate_direction, delay);
  1916. if (it_animation != animations.end())
  1917. {
  1918. result = it_animation->AddKey(duration, target_value, *this, tween, true);
  1919. if (!result)
  1920. animations.erase(it_animation);
  1921. }
  1922. return result;
  1923. }
  1924. bool Element::AddAnimationKey(const String & property_name, const Property & target_value, float duration, Tween tween)
  1925. {
  1926. ElementAnimation* animation = nullptr;
  1927. for (auto& existing_animation : animations) {
  1928. if (existing_animation.GetPropertyName() == property_name) {
  1929. animation = &existing_animation;
  1930. break;
  1931. }
  1932. }
  1933. if (!animation)
  1934. return false;
  1935. bool result = animation->AddKey(animation->GetDuration() + duration, target_value, *this, tween, true);
  1936. return result;
  1937. }
  1938. ElementAnimationList::iterator Element::StartAnimation(const String & property_name, const Property* start_value, int num_iterations, bool alternate_direction, float delay)
  1939. {
  1940. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyName() == property_name; });
  1941. if (it == animations.end())
  1942. {
  1943. animations.emplace_back();
  1944. it = animations.end() - 1;
  1945. }
  1946. Property value;
  1947. if (start_value)
  1948. {
  1949. value = *start_value;
  1950. if (!value.definition)
  1951. if(auto default_value = GetProperty(property_name))
  1952. value.definition = default_value->definition;
  1953. }
  1954. else if (auto default_value = GetProperty(property_name))
  1955. {
  1956. value = *default_value;
  1957. }
  1958. if (value.definition)
  1959. {
  1960. double start_time = Clock::GetElapsedTime() + (double)delay;
  1961. *it = ElementAnimation{ property_name, value, start_time, 0.0f, num_iterations, alternate_direction, false };
  1962. }
  1963. else
  1964. {
  1965. animations.erase(it);
  1966. it = animations.end();
  1967. }
  1968. return it;
  1969. }
  1970. bool Element::AddAnimationKeyTime(const String & property_name, const Property* target_value, float time, Tween tween)
  1971. {
  1972. if (!target_value)
  1973. target_value = GetProperty(property_name);
  1974. if (!target_value)
  1975. return false;
  1976. ElementAnimation* animation = nullptr;
  1977. for (auto& existing_animation : animations) {
  1978. if (existing_animation.GetPropertyName() == property_name) {
  1979. animation = &existing_animation;
  1980. break;
  1981. }
  1982. }
  1983. if (!animation)
  1984. return false;
  1985. bool result = animation->AddKey(time, *target_value, *this, tween, true);
  1986. return result;
  1987. }
  1988. bool Element::StartTransition(const Transition & transition, const Property& start_value, const Property & target_value)
  1989. {
  1990. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyName() == transition.name; });
  1991. if (it != animations.end() && !it->IsTransition())
  1992. return false;
  1993. float duration = transition.duration;
  1994. double start_time = Clock::GetElapsedTime() + (double)transition.delay;
  1995. if (it == animations.end())
  1996. {
  1997. // Add transition as new animation
  1998. animations.push_back(
  1999. ElementAnimation{ transition.name, start_value, start_time, 0.0f, 1, false, true }
  2000. );
  2001. it = (animations.end() - 1);
  2002. }
  2003. else
  2004. {
  2005. // Compress the duration based on the progress of the current animation
  2006. float f = it->GetInterpolationFactor();
  2007. f = 1.0f - (1.0f - f)*transition.reverse_adjustment_factor;
  2008. duration = duration * f;
  2009. // Replace old transition
  2010. *it = ElementAnimation{ transition.name, start_value, start_time, 0.0f, 1, false, true };
  2011. }
  2012. bool result = it->AddKey(duration, target_value, *this, transition.tween, true);
  2013. if (result)
  2014. SetProperty(transition.name, start_value);
  2015. else
  2016. animations.erase(it);
  2017. return result;
  2018. }
  2019. void Element::DirtyAnimation()
  2020. {
  2021. dirty_animation = true;
  2022. }
  2023. void Element::UpdateAnimation()
  2024. {
  2025. if (dirty_animation)
  2026. {
  2027. const auto& animation_list = element_meta->computed_values.animation;
  2028. StyleSheet* stylesheet = nullptr;
  2029. if (!animation_list.empty() && (stylesheet = GetStyleSheet()))
  2030. {
  2031. for (auto& animation : animation_list)
  2032. {
  2033. Keyframes* keyframes_ptr = stylesheet->GetKeyframes(animation.name);
  2034. if (keyframes_ptr && keyframes_ptr->blocks.size() >= 1 && !animation.paused)
  2035. {
  2036. auto& property_names = keyframes_ptr->property_names;
  2037. auto& blocks = keyframes_ptr->blocks;
  2038. bool has_from_key = (blocks[0].normalized_time == 0);
  2039. bool has_to_key = (blocks.back().normalized_time == 1);
  2040. // If the first key defines initial conditions for a given property, use those values, else, use this element's current values.
  2041. for (auto& property : property_names)
  2042. StartAnimation(property, (has_from_key ? blocks[0].properties.GetProperty(property) : nullptr), animation.num_iterations, animation.alternate, animation.delay);
  2043. // Need to skip the first and last keys if they set the initial and end conditions, respectively.
  2044. for (int i = (has_from_key ? 1 : 0); i < (int)blocks.size() + (has_to_key ? -1 : 0); i++)
  2045. {
  2046. // Add properties of current key to animation
  2047. float time = blocks[i].normalized_time * animation.duration;
  2048. for (auto& property : blocks[i].properties.GetProperties())
  2049. AddAnimationKeyTime(property.first, &property.second, time, animation.tween);
  2050. }
  2051. // If the last key defines end conditions for a given property, use those values, else, use this element's current values.
  2052. float time = animation.duration;
  2053. for (auto& property : property_names)
  2054. AddAnimationKeyTime(property, (has_to_key ? blocks.back().properties.GetProperty(property) : nullptr), time, animation.tween);
  2055. }
  2056. }
  2057. }
  2058. dirty_animation = false;
  2059. }
  2060. }
  2061. void Element::AdvanceAnimations()
  2062. {
  2063. if (!animations.empty())
  2064. {
  2065. double time = Clock::GetElapsedTime();
  2066. for (auto& animation : animations)
  2067. {
  2068. Property property = animation.UpdateAndGetProperty(time, *this);
  2069. if (property.unit != Property::UNKNOWN)
  2070. SetProperty(animation.GetPropertyName(), property);
  2071. }
  2072. auto it_completed = std::remove_if(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return animation.IsComplete(); });
  2073. std::vector<Dictionary> dictionary_list;
  2074. std::vector<bool> is_transition;
  2075. dictionary_list.reserve(animations.end() - it_completed);
  2076. is_transition.reserve(animations.end() - it_completed);
  2077. for (auto it = it_completed; it != animations.end(); ++it)
  2078. {
  2079. dictionary_list.emplace_back();
  2080. dictionary_list.back().emplace("property", it->GetPropertyName());
  2081. is_transition.push_back(it->IsTransition());
  2082. }
  2083. // Need to erase elements before submitting event, as iterators might be invalidated when calling external code.
  2084. animations.erase(it_completed, animations.end());
  2085. for (size_t i = 0; i < dictionary_list.size(); i++)
  2086. DispatchEvent(is_transition[i] ? EventId::Transitionend : EventId::Animationend, dictionary_list[i]);
  2087. }
  2088. }
  2089. void Element::DirtyTransformState(bool perspective_changed, bool transform_changed, bool parent_transform_changed)
  2090. {
  2091. for (size_t i = 0; i < children.size(); ++i)
  2092. {
  2093. children[i]->DirtyTransformState(false, false, transform_changed || parent_transform_changed);
  2094. }
  2095. if (perspective_changed)
  2096. {
  2097. this->transform_state_perspective_dirty = true;
  2098. }
  2099. if (transform_changed)
  2100. {
  2101. this->transform_state_transform_dirty = true;
  2102. }
  2103. if (parent_transform_changed)
  2104. {
  2105. this->transform_state_parent_transform_dirty = true;
  2106. }
  2107. }
  2108. void Element::UpdateTransformState()
  2109. {
  2110. if (!(transform_state_perspective_dirty || transform_state_transform_dirty || transform_state_parent_transform_dirty))
  2111. {
  2112. return;
  2113. }
  2114. const ComputedValues& computed = element_meta->computed_values;
  2115. if (!computed.transform && computed.perspective <= 0)
  2116. {
  2117. transform_state.reset();
  2118. transform_state_perspective_dirty = false;
  2119. transform_state_transform_dirty = false;
  2120. transform_state_parent_transform_dirty = false;
  2121. return;
  2122. }
  2123. if(transform_state_perspective_dirty || transform_state_transform_dirty)
  2124. {
  2125. Context *context = GetContext();
  2126. Vector2f pos = GetAbsoluteOffset(Box::BORDER);
  2127. Vector2f size = GetBox().GetSize(Box::BORDER);
  2128. if (transform_state_perspective_dirty)
  2129. {
  2130. bool have_perspective = false;
  2131. TransformState::Perspective perspective_value;
  2132. perspective_value.vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
  2133. if (computed.perspective > 0.0f)
  2134. {
  2135. have_perspective = true;
  2136. // Compute the perspective value
  2137. perspective_value.distance = computed.perspective;
  2138. // Compute the perspective origin, if necessary
  2139. if (computed.perspective_origin_x.type == Style::PerspectiveOrigin::Percentage)
  2140. perspective_value.vanish.x = pos.x + computed.perspective_origin_x.value * 0.01f * size.x;
  2141. else
  2142. perspective_value.vanish.x = pos.x + computed.perspective_origin_x.value;
  2143. if (computed.perspective_origin_y.type == Style::PerspectiveOrigin::Percentage)
  2144. perspective_value.vanish.y = pos.y + computed.perspective_origin_y.value * 0.01f * size.y;
  2145. else
  2146. perspective_value.vanish.y = pos.y + computed.perspective_origin_y.value;
  2147. }
  2148. if (have_perspective && context)
  2149. {
  2150. if (!transform_state)
  2151. transform_state.reset(new TransformState);
  2152. perspective_value.view_size = context->GetDimensions();
  2153. transform_state->SetPerspective(&perspective_value);
  2154. }
  2155. else if (transform_state)
  2156. {
  2157. transform_state->SetPerspective(nullptr);
  2158. }
  2159. transform_state_perspective_dirty = false;
  2160. }
  2161. if (transform_state_transform_dirty)
  2162. {
  2163. bool have_local_perspective = false;
  2164. TransformState::LocalPerspective local_perspective;
  2165. bool have_transform = false;
  2166. Matrix4f transform_value = Matrix4f::Identity();
  2167. Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
  2168. if (computed.transform)
  2169. {
  2170. int n = computed.transform->GetNumPrimitives();
  2171. for (int i = 0; i < n; ++i)
  2172. {
  2173. const Transforms::Primitive &primitive = computed.transform->GetPrimitive(i);
  2174. if (primitive.ResolvePerspective(local_perspective.distance, *this))
  2175. {
  2176. have_local_perspective = true;
  2177. }
  2178. Matrix4f matrix;
  2179. if (primitive.ResolveTransform(matrix, *this))
  2180. {
  2181. transform_value *= matrix;
  2182. have_transform = true;
  2183. }
  2184. }
  2185. // Compute the transform origin
  2186. if (computed.transform_origin_x.type == Style::TransformOrigin::Percentage)
  2187. transform_origin.x = pos.x + computed.transform_origin_x.value * size.x * 0.01f;
  2188. else
  2189. transform_origin.x = pos.x + computed.transform_origin_x.value;
  2190. if (computed.transform_origin_y.type == Style::TransformOrigin::Percentage)
  2191. transform_origin.y = pos.y + computed.transform_origin_y.value * size.y * 0.01f;
  2192. else
  2193. transform_origin.y = pos.y + computed.transform_origin_y.value;
  2194. transform_origin.z = computed.transform_origin_z;
  2195. }
  2196. if (have_local_perspective && context)
  2197. {
  2198. if (!transform_state)
  2199. transform_state.reset(new TransformState);
  2200. local_perspective.view_size = context->GetDimensions();
  2201. transform_state->SetLocalPerspective(&local_perspective);
  2202. }
  2203. else if(transform_state)
  2204. {
  2205. transform_state->SetLocalPerspective(nullptr);
  2206. }
  2207. if (have_transform)
  2208. {
  2209. // TODO: If we're using the global projection matrix
  2210. // (perspective < 0), then scale the coordinates from
  2211. // pixel space to 3D unit space.
  2212. // Transform the Rocket context so that the computed `transform_origin'
  2213. // lies at the coordinate system origin.
  2214. transform_value =
  2215. Matrix4f::Translate(transform_origin)
  2216. * transform_value
  2217. * Matrix4f::Translate(-transform_origin);
  2218. if (!transform_state)
  2219. transform_state.reset(new TransformState);
  2220. transform_state->SetTransform(&transform_value);
  2221. }
  2222. else if (transform_state)
  2223. {
  2224. transform_state->SetTransform(nullptr);
  2225. }
  2226. transform_state_transform_dirty = false;
  2227. }
  2228. }
  2229. if (transform_state_parent_transform_dirty)
  2230. {
  2231. // We need to clean up from the top-most to the bottom-most dirt.
  2232. if (parent)
  2233. {
  2234. parent->UpdateTransformState();
  2235. }
  2236. if (transform_state)
  2237. {
  2238. // Store the parent's new full transform as our parent transform
  2239. Element *node = nullptr;
  2240. Matrix4f parent_transform;
  2241. for (node = parent; node; node = node->parent)
  2242. {
  2243. if (node->GetTransformState() && node->GetTransformState()->GetRecursiveTransform(&parent_transform))
  2244. {
  2245. transform_state->SetParentRecursiveTransform(&parent_transform);
  2246. break;
  2247. }
  2248. }
  2249. if (!node)
  2250. {
  2251. transform_state->SetParentRecursiveTransform(nullptr);
  2252. }
  2253. }
  2254. transform_state_parent_transform_dirty = false;
  2255. }
  2256. // If we neither have a local perspective, nor a perspective nor a
  2257. // transform, we don't need to keep the large TransformState object
  2258. // around. GetEffectiveTransformState() will then recursively visit
  2259. // parents in order to find a non-trivial TransformState.
  2260. if (transform_state && !transform_state->GetLocalPerspective(nullptr) && !transform_state->GetPerspective(nullptr) && !transform_state->GetTransform(nullptr))
  2261. {
  2262. transform_state.reset();
  2263. }
  2264. }
  2265. }
  2266. }