Element.cpp 72 KB

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