| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583 |
- /*
- * This source file is part of RmlUi, the HTML/CSS Interface Middleware
- *
- * For the latest information, see http://github.com/mikke89/RmlUi
- *
- * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
- * Copyright (c) 2019 The RmlUi Team, and contributors
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- */
-
- #include "../../Include/RmlUi/Core/Element.h"
- #include "../../Include/RmlUi/Core/Context.h"
- #include "../../Include/RmlUi/Core/Core.h"
- #include "../../Include/RmlUi/Core/ElementDocument.h"
- #include "../../Include/RmlUi/Core/ElementInstancer.h"
- #include "../../Include/RmlUi/Core/ElementScroll.h"
- #include "../../Include/RmlUi/Core/ElementUtilities.h"
- #include "../../Include/RmlUi/Core/Factory.h"
- #include "../../Include/RmlUi/Core/Dictionary.h"
- #include "../../Include/RmlUi/Core/Profiling.h"
- #include "../../Include/RmlUi/Core/PropertyIdSet.h"
- #include "../../Include/RmlUi/Core/PropertiesIteratorView.h"
- #include "../../Include/RmlUi/Core/PropertyDefinition.h"
- #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
- #include "../../Include/RmlUi/Core/TransformPrimitive.h"
- #include "../../Include/RmlUi/Core/TransformState.h"
- #include "Clock.h"
- #include "ComputeProperty.h"
- #include "ElementAnimation.h"
- #include "ElementBackground.h"
- #include "ElementBorder.h"
- #include "ElementDefinition.h"
- #include "ElementStyle.h"
- #include "EventDispatcher.h"
- #include "EventSpecification.h"
- #include "ElementDecoration.h"
- #include "LayoutEngine.h"
- #include "PluginRegistry.h"
- #include "PropertiesIterator.h"
- #include "Pool.h"
- #include "StyleSheetParser.h"
- #include "StringCache.h"
- #include "XMLParseTools.h"
- #include <algorithm>
- namespace Rml {
- namespace Core {
- /**
- STL function object for sorting elements by z-type (ie, float-types before general types, etc).
- @author Peter Curry
- */
- class ElementSortZOrder
- {
- public:
- bool operator()(const std::pair< Element*, float >& lhs, const std::pair< Element*, float >& rhs) const
- {
- return lhs.second < rhs.second;
- }
- };
- /**
- STL function object for sorting elements by z-index property.
- @author Peter Curry
- */
- class ElementSortZIndex
- {
- public:
- bool operator()(const Element* lhs, const Element* rhs) const
- {
- // Check the z-index.
- return lhs->GetZIndex() < rhs->GetZIndex();
- }
- };
- // Determines how many levels up in the hierarchy the OnChildAdd and OnChildRemove are called (starting at the child itself)
- static constexpr int ChildNotifyLevels = 2;
- // Meta objects for element collected in a single struct to reduce memory allocations
- struct ElementMeta
- {
- ElementMeta(Element* el) : event_dispatcher(el), style(el), background(el), border(el), decoration(el), scroll(el) {}
- EventDispatcher event_dispatcher;
- ElementStyle style;
- ElementBackground background;
- ElementBorder border;
- ElementDecoration decoration;
- ElementScroll scroll;
- Style::ComputedValues computed_values;
- };
- static Pool< ElementMeta > element_meta_chunk_pool(200, true);
- /// Constructs a new RmlUi element.
- 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),
- transform_state(), dirty_transform(false), dirty_perspective(false), dirty_animation(false), dirty_transition(false)
- {
- RMLUI_ASSERT(tag == StringUtilities::ToLower(tag));
- parent = nullptr;
- focus = nullptr;
- instancer = nullptr;
- owner_document = nullptr;
- offset_fixed = false;
- offset_parent = nullptr;
- offset_dirty = true;
- client_area = Box::PADDING;
- num_non_dom_children = 0;
- visible = true;
- z_index = 0;
- local_stacking_context = false;
- local_stacking_context_forced = false;
- stacking_context_dirty = false;
- structure_dirty = false;
- computed_values_are_default_initialized = true;
- clipping_ignore_depth = 0;
- clipping_enabled = false;
- clipping_state_dirty = true;
- meta = element_meta_chunk_pool.AllocateAndConstruct(this);
- data_model = nullptr;
- }
- Element::~Element()
- {
- RMLUI_ASSERT(parent == nullptr);
- PluginRegistry::NotifyElementDestroy(this);
- // Remove scrollbar elements before we delete the children!
- meta->scroll.ClearScrollbars();
- // A simplified version of RemoveChild() for destruction.
- for (ElementPtr& child : children)
- {
- Element* child_ancestor = child.get();
- for (int i = 0; i <= ChildNotifyLevels && child_ancestor; i++, child_ancestor = child_ancestor->GetParentNode())
- child_ancestor->OnChildRemove(child.get());
- child->SetParent(nullptr);
- }
- children.clear();
- num_non_dom_children = 0;
- element_meta_chunk_pool.DestroyAndDeallocate(meta);
- }
- void Element::Update(float dp_ratio)
- {
- RMLUI_ZoneScoped;
- OnUpdate();
- UpdateStructure();
- HandleTransitionProperty();
- HandleAnimationProperty();
- AdvanceAnimations();
- meta->scroll.Update();
- UpdateProperties();
- // Do en extra pass over the animations and properties if the 'animation' property was just changed.
- if (dirty_animation)
- {
- HandleAnimationProperty();
- AdvanceAnimations();
- UpdateProperties();
- }
- for (size_t i = 0; i < children.size(); i++)
- children[i]->Update(dp_ratio);
- }
- void Element::UpdateProperties()
- {
- meta->style.UpdateDefinition();
- if (meta->style.AnyPropertiesDirty())
- {
- const ComputedValues* parent_values = nullptr;
- if (parent)
- parent_values = &parent->GetComputedValues();
- const ComputedValues* document_values = nullptr;
- float dp_ratio = 1.0f;
- if (auto doc = GetOwnerDocument())
- {
- document_values = &doc->GetComputedValues();
- if (Context * context = doc->GetContext())
- dp_ratio = context->GetDensityIndependentPixelRatio();
- }
- // Compute values and clear dirty properties
- PropertyIdSet dirty_properties = meta->style.ComputeValues(meta->computed_values, parent_values, document_values, computed_values_are_default_initialized, dp_ratio);
- computed_values_are_default_initialized = false;
- // Computed values are just calculated and can safely be used in OnPropertyChange.
- // However, new properties set during this call will not be available until the next update loop.
- if (!dirty_properties.Empty())
- OnPropertyChange(dirty_properties);
- }
- }
- void Element::Render()
- {
- #ifdef RMLUI_ENABLE_PROFILING
- auto name = GetAddress(false, false);
- RMLUI_ZoneScoped;
- RMLUI_ZoneText(name.c_str(), name.size());
- #endif
- // Rebuild our stacking context if necessary.
- if (stacking_context_dirty)
- BuildLocalStackingContext();
- UpdateTransformState();
- // Render all elements in our local stacking context that have a z-index beneath our local index of 0.
- size_t i = 0;
- for (; i < stacking_context.size() && stacking_context[i]->z_index < 0; ++i)
- stacking_context[i]->Render();
- // Apply our transform
- ElementUtilities::ApplyTransform(*this);
- // Set up the clipping region for this element.
- if (ElementUtilities::SetClippingRegion(this))
- {
- meta->background.RenderBackground();
- meta->border.RenderBorder();
- meta->decoration.RenderDecorators();
- {
- RMLUI_ZoneScopedNC("OnRender", 0x228B22);
- OnRender();
- }
- }
- // Render the rest of the elements in the stacking context.
- for (; i < stacking_context.size(); ++i)
- stacking_context[i]->Render();
- }
- // Clones this element, returning a new, unparented element.
- ElementPtr Element::Clone() const
- {
- ElementPtr clone;
- if (instancer)
- {
- clone = instancer->InstanceElement(nullptr, GetTagName(), attributes);
- if (clone)
- clone->SetInstancer(instancer);
- }
- else
- clone = Factory::InstanceElement(nullptr, GetTagName(), GetTagName(), attributes);
- if (clone != nullptr)
- {
- String inner_rml;
- GetInnerRML(inner_rml);
- clone->SetInnerRML(inner_rml);
- }
- return clone;
- }
- // Sets or removes a class on the element.
- void Element::SetClass(const String& class_name, bool activate)
- {
- meta->style.SetClass(class_name, activate);
- }
- // Checks if a class is set on the element.
- bool Element::IsClassSet(const String& class_name) const
- {
- return meta->style.IsClassSet(class_name);
- }
- // Specifies the entire list of classes for this element. This will replace any others specified.
- void Element::SetClassNames(const String& class_names)
- {
- SetAttribute("class", class_names);
- }
- /// Return the active class list
- String Element::GetClassNames() const
- {
- return meta->style.GetClassNames();
- }
- // Returns the active style sheet for this element. This may be nullptr.
- const SharedPtr<StyleSheet>& Element::GetStyleSheet() const
- {
- if (ElementDocument * document = GetOwnerDocument())
- return document->GetStyleSheet();
- static SharedPtr<StyleSheet> null_style_sheet;
- return null_style_sheet;
- }
- // Returns the element's definition.
- const ElementDefinition* Element::GetDefinition()
- {
- return meta->style.GetDefinition();
- }
- // Fills an String with the full address of this element.
- String Element::GetAddress(bool include_pseudo_classes, bool include_parents) const
- {
- // Add the tag name onto the address.
- String address(tag);
- // Add the ID if we have one.
- if (!id.empty())
- {
- address += "#";
- address += id;
- }
- String classes = meta->style.GetClassNames();
- if (!classes.empty())
- {
- classes = StringUtilities::Replace(classes, ' ', '.');
- address += ".";
- address += classes;
- }
- if (include_pseudo_classes)
- {
- const PseudoClassList& pseudo_classes = meta->style.GetActivePseudoClasses();
- for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
- {
- address += ":";
- address += (*i);
- }
- }
- if (include_parents && parent)
- {
- address += " < ";
- return address + parent->GetAddress(include_pseudo_classes, true);
- }
- else
- return address;
- }
- // Sets the position of this element, as a two-dimensional offset from another element.
- void Element::SetOffset(const Vector2f& offset, Element* _offset_parent, bool _offset_fixed)
- {
- _offset_fixed |= GetPosition() == Style::Position::Fixed;
- // If our offset has definitely changed, or any of our parenting has, then these are set and
- // updated based on our left / right / top / bottom properties.
- if (relative_offset_base != offset ||
- offset_parent != _offset_parent ||
- offset_fixed != _offset_fixed)
- {
- relative_offset_base = offset;
- offset_fixed = _offset_fixed;
- offset_parent = _offset_parent;
- UpdateOffset();
- DirtyOffset();
- }
- // Otherwise, our offset is updated in case left / right / top / bottom will have an impact on
- // our final position, and our children are dirtied if they do.
- else
- {
- Vector2f& old_base = relative_offset_base;
- Vector2f& old_position = relative_offset_position;
- UpdateOffset();
- if (old_base != relative_offset_base ||
- old_position != relative_offset_position)
- DirtyOffset();
- }
- }
- // Returns the position of the top-left corner of one of the areas of this element's primary box.
- Vector2f Element::GetRelativeOffset(Box::Area area)
- {
- return relative_offset_base + relative_offset_position + GetBox().GetPosition(area);
- }
- // Returns the position of the top-left corner of one of the areas of this element's primary box.
- Vector2f Element::GetAbsoluteOffset(Box::Area area)
- {
- if (offset_dirty)
- {
- offset_dirty = false;
- if (offset_parent != nullptr)
- absolute_offset = offset_parent->GetAbsoluteOffset(Box::BORDER) + relative_offset_base + relative_offset_position;
- else
- absolute_offset = relative_offset_base + relative_offset_position;
- // Add any parent scrolling onto our position as well. Could cache this if required.
- if (!offset_fixed)
- {
- Element* scroll_parent = parent;
- while (scroll_parent != nullptr)
- {
- absolute_offset -= (scroll_parent->scroll_offset + scroll_parent->content_offset);
- if (scroll_parent == offset_parent)
- break;
- else
- scroll_parent = scroll_parent->parent;
- }
- }
- }
- return absolute_offset + GetBox().GetPosition(area);
- }
- // Sets an alternate area to use as the client area.
- void Element::SetClientArea(Box::Area _client_area)
- {
- client_area = _client_area;
- }
- // Returns the area the element uses as its client area.
- Box::Area Element::GetClientArea() const
- {
- return client_area;
- }
- // Sets the dimensions of the element's internal content.
- void Element::SetContentBox(const Vector2f& _content_offset, const Vector2f& _content_box)
- {
- if (content_offset != _content_offset ||
- content_box != _content_box)
- {
- // Seems to be jittering a wee bit; might need to be looked at.
- scroll_offset.x += (content_offset.x - _content_offset.x);
- scroll_offset.y += (content_offset.y - _content_offset.y);
- content_offset = _content_offset;
- content_box = _content_box;
- scroll_offset.x = Math::Min(scroll_offset.x, GetScrollWidth() - GetClientWidth());
- scroll_offset.y = Math::Min(scroll_offset.y, GetScrollHeight() - GetClientHeight());
- DirtyOffset();
- }
- }
- // Sets the box describing the size of the element.
- void Element::SetBox(const Box& box)
- {
- if (box != main_box || additional_boxes.size() > 0)
- {
- main_box = box;
- additional_boxes.clear();
- OnResize();
- meta->background.DirtyBackground();
- meta->border.DirtyBorder();
- meta->decoration.DirtyDecorators();
- }
- }
- // Adds a box to the end of the list describing this element's geometry.
- void Element::AddBox(const Box& box)
- {
- additional_boxes.push_back(box);
- OnResize();
- meta->background.DirtyBackground();
- meta->border.DirtyBorder();
- meta->decoration.DirtyDecorators();
- }
- // Returns one of the boxes describing the size of the element.
- const Box& Element::GetBox()
- {
- return main_box;
- }
- // Returns one of the boxes describing the size of the element.
- const Box& Element::GetBox(int index)
- {
- if (index < 1)
- return main_box;
-
- int additional_box_index = index - 1;
- if (additional_box_index >= (int)additional_boxes.size())
- return main_box;
- return additional_boxes[additional_box_index];
- }
- // Returns the number of boxes making up this element's geometry.
- int Element::GetNumBoxes()
- {
- return 1 + (int)additional_boxes.size();
- }
- // Returns the baseline of the element, in pixels offset from the bottom of the element's content area.
- float Element::GetBaseline() const
- {
- return 0;
- }
- // Gets the intrinsic dimensions of this element, if it is of a type that has an inherent size.
- bool Element::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions))
- {
- RMLUI_UNUSED(dimensions);
- return false;
- }
- // Checks if a given point in screen coordinates lies within the bordered area of this element.
- bool Element::IsPointWithinElement(const Vector2f& point)
- {
- Vector2f position = GetAbsoluteOffset(Box::BORDER);
- for (int i = 0; i < GetNumBoxes(); ++i)
- {
- const Box& box = GetBox(i);
- Vector2f box_position = position + box.GetOffset();
- Vector2f box_dimensions = box.GetSize(Box::BORDER);
- if (point.x >= box_position.x &&
- point.x <= (box_position.x + box_dimensions.x) &&
- point.y >= box_position.y &&
- point.y <= (box_position.y + box_dimensions.y))
- {
- return true;
- }
- }
- return false;
- }
- // Returns the visibility of the element.
- bool Element::IsVisible() const
- {
- return visible;
- }
- // Returns the z-index of the element.
- float Element::GetZIndex() const
- {
- return z_index;
- }
- // Returns the element's font face handle.
- FontFaceHandle Element::GetFontFaceHandle() const
- {
- return meta->computed_values.font_face_handle;
- }
- // Sets a local property override on the element.
- bool Element::SetProperty(const String& name, const String& value)
- {
- // The name may be a shorthand giving us multiple underlying properties
- PropertyDictionary properties;
- if (!StyleSheetSpecification::ParsePropertyDeclaration(properties, name, value))
- {
- Log::Message(Log::LT_WARNING, "Syntax error parsing inline property declaration '%s: %s;'.", name.c_str(), value.c_str());
- return false;
- }
- for (auto& property : properties.GetProperties())
- {
- if (!meta->style.SetProperty(property.first, property.second))
- return false;
- }
- return true;
- }
- // Sets a local property override on the element to a pre-parsed value.
- bool Element::SetProperty(PropertyId id, const Property& property)
- {
- return meta->style.SetProperty(id, property);
- }
- // Removes a local property override on the element.
- void Element::RemoveProperty(const String& name)
- {
- meta->style.RemoveProperty(StyleSheetSpecification::GetPropertyId(name));
- }
- // Removes a local property override on the element.
- void Element::RemoveProperty(PropertyId id)
- {
- meta->style.RemoveProperty(id);
- }
- // Returns one of this element's properties.
- const Property* Element::GetProperty(const String& name)
- {
- return meta->style.GetProperty(StyleSheetSpecification::GetPropertyId(name));
- }
- // Returns one of this element's properties.
- const Property* Element::GetProperty(PropertyId id)
- {
- return meta->style.GetProperty(id);
- }
- // Returns one of this element's properties.
- const Property* Element::GetLocalProperty(const String& name)
- {
- return meta->style.GetLocalProperty(StyleSheetSpecification::GetPropertyId(name));
- }
- const Property* Element::GetLocalProperty(PropertyId id)
- {
- return meta->style.GetLocalProperty(id);
- }
- const PropertyMap& Element::GetLocalStyleProperties()
- {
- return meta->style.GetLocalStyleProperties();
- }
- float Element::ResolveNumericProperty(const Property *property, float base_value)
- {
- return meta->style.ResolveNumericProperty(property, base_value);
- }
- float Element::ResolveNumericProperty(const String& property_name)
- {
- auto property = meta->style.GetProperty(StyleSheetSpecification::GetPropertyId(property_name));
- if (!property)
- return 0.0f;
- if (property->unit & Property::ANGLE)
- return ComputeAngle(*property);
- RelativeTarget relative_target = RelativeTarget::None;
- if (property->definition)
- relative_target = property->definition->GetRelativeTarget();
- float result = meta->style.ResolveLength(property, relative_target);
-
- return result;
- }
- Vector2f Element::GetContainingBlock()
- {
- Vector2f containing_block(0, 0);
- if (offset_parent != nullptr)
- {
- using namespace Style;
- Position position_property = GetPosition();
- const Box& parent_box = offset_parent->GetBox();
- if (position_property == Position::Static || position_property == Position::Relative)
- {
- containing_block = parent_box.GetSize();
- }
- else if(position_property == Position::Absolute || position_property == Position::Fixed)
- {
- containing_block = parent_box.GetSize(Box::PADDING);
- }
- }
-
- return containing_block;
- }
- Style::Position Element::GetPosition()
- {
- return meta->computed_values.position;
- }
- Style::Float Element::GetFloat()
- {
- return meta->computed_values.float_;
- }
- Style::Display Element::GetDisplay()
- {
- return meta->computed_values.display;
- }
- float Element::GetLineHeight()
- {
- return meta->computed_values.line_height.value;
- }
- // Returns this element's TransformState
- const TransformState *Element::GetTransformState() const noexcept
- {
- return transform_state.get();
- }
- // Project a 2D point in pixel coordinates onto the element's plane.
- bool Element::Project(Vector2f& point) const noexcept
- {
- if(!transform_state || !transform_state->GetTransform())
- return true;
- // The input point is in window coordinates. Need to find the projection of the point onto the current element plane,
- // taking into account the full transform applied to the element.
- if (const Matrix4f* inv_transform = transform_state->GetInverseTransform())
- {
- // Pick two points forming a line segment perpendicular to the window.
- Vector4f window_points[2] = {{ point.x, point.y, -10, 1}, { point.x, point.y, 10, 1 }};
- // Project them into the local element space.
- window_points[0] = *inv_transform * window_points[0];
- window_points[1] = *inv_transform * window_points[1];
- Vector3f local_points[2] = {
- window_points[0].PerspectiveDivide(),
- window_points[1].PerspectiveDivide()
- };
- // Construct a ray from the two projected points in the local space of the current element.
- // Find the intersection with the z=0 plane to produce our destination point.
- Vector3f ray = local_points[1] - local_points[0];
- // Only continue if we are not close to parallel with the plane.
- if(std::abs(ray.z) > 1.0f)
- {
- // Solving the line equation p = p0 + t*ray for t, knowing that p.z = 0, produces the following.
- float t = -local_points[0].z / ray.z;
- Vector3f p = local_points[0] + ray * t;
- point = Vector2f(p.x, p.y);
- return true;
- }
- }
- // The transformation matrix is either singular, or the ray is parallel to the element's plane.
- return false;
- }
- PropertiesIteratorView Element::IterateLocalProperties() const
- {
- return PropertiesIteratorView(std::make_unique<PropertiesIterator>(meta->style.Iterate()));
- }
- // Sets or removes a pseudo-class on the element.
- void Element::SetPseudoClass(const String& pseudo_class, bool activate)
- {
- meta->style.SetPseudoClass(pseudo_class, activate);
- }
- // Checks if a specific pseudo-class has been set on the element.
- bool Element::IsPseudoClassSet(const String& pseudo_class) const
- {
- return meta->style.IsPseudoClassSet(pseudo_class);
- }
- // Checks if a complete set of pseudo-classes are set on the element.
- bool Element::ArePseudoClassesSet(const PseudoClassList& pseudo_classes) const
- {
- for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
- {
- if (!IsPseudoClassSet(*i))
- return false;
- }
- return true;
- }
- // Gets a list of the current active pseudo classes
- const PseudoClassList& Element::GetActivePseudoClasses() const
- {
- return meta->style.GetActivePseudoClasses();
- }
- /// Get the named attribute
- Variant* Element::GetAttribute(const String& name)
- {
- return GetIf(attributes, name);
- }
- // Checks if the element has a certain attribute.
- bool Element::HasAttribute(const String& name) const
- {
- return attributes.find(name) != attributes.end();
- }
- // Removes an attribute from the element
- void Element::RemoveAttribute(const String& name)
- {
- auto it = attributes.find(name);
- if (it != attributes.end())
- {
- attributes.erase(it);
- ElementAttributes changed_attributes;
- changed_attributes.emplace(name, Variant());
- OnAttributeChange(changed_attributes);
- }
- }
- // Gets the outer most focus element down the tree from this node
- Element* Element::GetFocusLeafNode()
- {
- // If there isn't a focus, then we are the leaf.
- if (!focus)
- {
- return this;
- }
- // Recurse down the tree until we found the leaf focus element
- Element* focus_element = focus;
- while (focus_element->focus)
- focus_element = focus_element->focus;
- return focus_element;
- }
- // Returns the element's context.
- Context* Element::GetContext() const
- {
- ElementDocument* document = GetOwnerDocument();
- if (document != nullptr)
- return document->GetContext();
- return nullptr;
- }
- // Set a group of attributes
- void Element::SetAttributes(const ElementAttributes& _attributes)
- {
- attributes.reserve(attributes.size() + _attributes.size());
- for (auto& pair : _attributes)
- attributes[pair.first] = pair.second;
- OnAttributeChange(_attributes);
- }
- // Returns the number of attributes on the element.
- int Element::GetNumAttributes() const
- {
- return (int)attributes.size();
- }
- // Gets the name of the element.
- const String& Element::GetTagName() const
- {
- return tag;
- }
- // Gets the ID of the element.
- const String& Element::GetId() const
- {
- return id;
- }
- // Sets the ID of the element.
- void Element::SetId(const String& _id)
- {
- SetAttribute("id", _id);
- }
- // Gets the horizontal offset from the context's left edge to element's left border edge.
- float Element::GetAbsoluteLeft()
- {
- return GetAbsoluteOffset(Box::BORDER).x;
- }
- // Gets the vertical offset from the context's top edge to element's top border edge.
- float Element::GetAbsoluteTop()
- {
- return GetAbsoluteOffset(Box::BORDER).y;
- }
- // Gets the width of the left border of an element.
- float Element::GetClientLeft()
- {
- return GetBox().GetPosition(client_area).x;
- }
- // Gets the height of the top border of an element.
- float Element::GetClientTop()
- {
- return GetBox().GetPosition(client_area).y;
- }
- // Gets the inner width of the element.
- float Element::GetClientWidth()
- {
- return GetBox().GetSize(client_area).x - meta->scroll.GetScrollbarSize(ElementScroll::VERTICAL);
- }
- // Gets the inner height of the element.
- float Element::GetClientHeight()
- {
- return GetBox().GetSize(client_area).y - meta->scroll.GetScrollbarSize(ElementScroll::HORIZONTAL);
- }
- // Returns the element from which all offset calculations are currently computed.
- Element* Element::GetOffsetParent()
- {
- return offset_parent;
- }
- // Gets the distance from this element's left border to its offset parent's left border.
- float Element::GetOffsetLeft()
- {
- return relative_offset_base.x + relative_offset_position.x;
- }
- // Gets the distance from this element's top border to its offset parent's top border.
- float Element::GetOffsetTop()
- {
- return relative_offset_base.y + relative_offset_position.y;
- }
- // Gets the width of the element, including the client area, padding, borders and scrollbars, but not margins.
- float Element::GetOffsetWidth()
- {
- return GetBox().GetSize(Box::BORDER).x;
- }
- // Gets the height of the element, including the client area, padding, borders and scrollbars, but not margins.
- float Element::GetOffsetHeight()
- {
- return GetBox().GetSize(Box::BORDER).y;
- }
- // Gets the left scroll offset of the element.
- float Element::GetScrollLeft()
- {
- return scroll_offset.x;
- }
- // Sets the left scroll offset of the element.
- void Element::SetScrollLeft(float scroll_left)
- {
- const float new_offset = Math::Clamp(Math::RoundFloat(scroll_left), 0.0f, GetScrollWidth() - GetClientWidth());
- if (new_offset != scroll_offset.x)
- {
- scroll_offset.x = new_offset;
- meta->scroll.UpdateScrollbar(ElementScroll::HORIZONTAL);
- DirtyOffset();
- DispatchEvent(EventId::Scroll, Dictionary());
- }
- }
- // Gets the top scroll offset of the element.
- float Element::GetScrollTop()
- {
- return scroll_offset.y;
- }
- // Sets the top scroll offset of the element.
- void Element::SetScrollTop(float scroll_top)
- {
- const float new_offset = Math::Clamp(Math::RoundFloat(scroll_top), 0.0f, GetScrollHeight() - GetClientHeight());
- if(new_offset != scroll_offset.y)
- {
- scroll_offset.y = new_offset;
- meta->scroll.UpdateScrollbar(ElementScroll::VERTICAL);
- DirtyOffset();
- DispatchEvent(EventId::Scroll, Dictionary());
- }
- }
- // Gets the width of the scrollable content of the element; it includes the element padding but not its margin.
- float Element::GetScrollWidth()
- {
- return Math::Max(content_box.x, GetClientWidth());
- }
- // Gets the height of the scrollable content of the element; it includes the element padding but not its margin.
- float Element::GetScrollHeight()
- {
- return Math::Max(content_box.y, GetClientHeight());
- }
- // Gets the object representing the declarations of an element's style attributes.
- ElementStyle* Element::GetStyle() const
- {
- return &meta->style;
- }
- // Gets the document this element belongs to.
- ElementDocument* Element::GetOwnerDocument() const
- {
- #ifdef RMLUI_DEBUG
- if (parent && !owner_document)
- {
- // Since we have a parent but no owner_document, then we must be a 'loose' element -- that is, constructed
- // outside of a document and not attached to a child of any element in the hierarchy of a document.
- // This check ensures that we didn't just forget to set the owner document.
- RMLUI_ASSERT(!parent->GetOwnerDocument());
- }
- #endif
- return owner_document;
- }
- // Gets this element's parent node.
- Element* Element::GetParentNode() const
- {
- return parent;
- }
- // Gets the element immediately following this one in the tree.
- Element* Element::GetNextSibling() const
- {
- if (parent == nullptr)
- return nullptr;
- for (size_t i = 0; i < parent->children.size() - (parent->num_non_dom_children + 1); i++)
- {
- if (parent->children[i].get() == this)
- return parent->children[i + 1].get();
- }
- return nullptr;
- }
- // Gets the element immediately preceding this one in the tree.
- Element* Element::GetPreviousSibling() const
- {
- if (parent == nullptr)
- return nullptr;
- for (size_t i = 1; i < parent->children.size() - parent->num_non_dom_children; i++)
- {
- if (parent->children[i].get() == this)
- return parent->children[i - 1].get();
- }
- return nullptr;
- }
- // Returns the first child of this element.
- Element* Element::GetFirstChild() const
- {
- if (GetNumChildren() > 0)
- return children[0].get();
- return nullptr;
- }
- // Gets the last child of this element.
- Element* Element::GetLastChild() const
- {
- if (GetNumChildren() > 0)
- return (children.end() - (num_non_dom_children + 1))->get();
- return nullptr;
- }
- Element* Element::GetChild(int index) const
- {
- if (index < 0 || index >= (int) children.size())
- return nullptr;
- return children[index].get();
- }
- int Element::GetNumChildren(bool include_non_dom_elements) const
- {
- return (int) children.size() - (include_non_dom_elements ? 0 : num_non_dom_children);
- }
- // Gets the markup and content of the element.
- void Element::GetInnerRML(String& content) const
- {
- for (int i = 0; i < GetNumChildren(); i++)
- {
- children[i]->GetRML(content);
- }
- }
- // Gets the markup and content of the element.
- String Element::GetInnerRML() const {
- String result;
- GetInnerRML(result);
- return result;
- }
- // Sets the markup and content of the element. All existing children will be replaced.
- void Element::SetInnerRML(const String& rml)
- {
- RMLUI_ZoneScopedC(0x6495ED);
- // Remove all DOM children.
- while ((int) children.size() > num_non_dom_children)
- RemoveChild(children.front().get());
- if(!rml.empty())
- Factory::InstanceElementText(this, rml);
- }
- // Sets the current element as the focus object.
- bool Element::Focus()
- {
- // Are we allowed focus?
- Style::Focus focus_property = meta->computed_values.focus;
- if (focus_property == Style::Focus::None)
- return false;
- // Ask our context if we can switch focus.
- Context* context = GetContext();
- if (context == nullptr)
- return false;
- if (!context->OnFocusChange(this))
- return false;
- // Set this as the end of the focus chain.
- focus = nullptr;
- // Update the focus chain up the hierarchy.
- Element* element = this;
- while (Element* parent = element->GetParentNode())
- {
- parent->focus = element;
- element = parent;
- }
- return true;
- }
- // Removes focus from from this element.
- void Element::Blur()
- {
- if (parent)
- {
- Context* context = GetContext();
- if (context == nullptr)
- return;
- if (context->GetFocusElement() == this)
- {
- parent->Focus();
- }
- else if (parent->focus == this)
- {
- parent->focus = nullptr;
- }
- }
- }
- // Fakes a mouse click on this element.
- void Element::Click()
- {
- Context* context = GetContext();
- if (context == nullptr)
- return;
- context->GenerateClickEvent(this);
- }
- // Adds an event listener
- void Element::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
- {
- EventId id = EventSpecificationInterface::GetIdOrInsert(event);
- meta->event_dispatcher.AttachEvent(id, listener, in_capture_phase);
- }
- // Adds an event listener
- void Element::AddEventListener(EventId id, EventListener* listener, bool in_capture_phase)
- {
- meta->event_dispatcher.AttachEvent(id, listener, in_capture_phase);
- }
- // Removes an event listener from this element.
- void Element::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
- {
- EventId id = EventSpecificationInterface::GetIdOrInsert(event);
- meta->event_dispatcher.DetachEvent(id, listener, in_capture_phase);
- }
- // Removes an event listener from this element.
- void Element::RemoveEventListener(EventId id, EventListener* listener, bool in_capture_phase)
- {
- meta->event_dispatcher.DetachEvent(id, listener, in_capture_phase);
- }
- // Dispatches the specified event
- bool Element::DispatchEvent(const String& type, const Dictionary& parameters)
- {
- const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
- return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
- }
- // Dispatches the specified event
- bool Element::DispatchEvent(const String& type, const Dictionary& parameters, bool interruptible, bool bubbles)
- {
- const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
- return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, interruptible, bubbles, specification.default_action_phase);
- }
- // Dispatches the specified event
- bool Element::DispatchEvent(EventId id, const Dictionary& parameters)
- {
- const EventSpecification& specification = EventSpecificationInterface::Get(id);
- return EventDispatcher::DispatchEvent(this, specification.id, specification.type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
- }
- // Scrolls the parent element's contents so that this element is visible.
- void Element::ScrollIntoView(bool align_with_top)
- {
- Vector2f size(0, 0);
- if (!align_with_top)
- {
- size.y = main_box.GetOffset().y +
- main_box.GetSize(Box::BORDER).y;
- }
- Element* scroll_parent = parent;
- while (scroll_parent != nullptr)
- {
- Style::Overflow overflow_x_property = scroll_parent->GetComputedValues().overflow_x;
- Style::Overflow overflow_y_property = scroll_parent->GetComputedValues().overflow_y;
- if ((overflow_x_property != Style::Overflow::Visible &&
- scroll_parent->GetScrollWidth() > scroll_parent->GetClientWidth()) ||
- (overflow_y_property != Style::Overflow::Visible &&
- scroll_parent->GetScrollHeight() > scroll_parent->GetClientHeight()))
- {
- Vector2f offset = scroll_parent->GetAbsoluteOffset(Box::BORDER) - GetAbsoluteOffset(Box::BORDER);
- Vector2f scroll_offset(scroll_parent->GetScrollLeft(), scroll_parent->GetScrollTop());
- scroll_offset -= offset;
- scroll_offset.x += scroll_parent->GetClientLeft();
- scroll_offset.y += scroll_parent->GetClientTop();
- if (!align_with_top)
- scroll_offset.y -= (scroll_parent->GetClientHeight() - size.y);
- if (overflow_x_property != Style::Overflow::Visible)
- scroll_parent->SetScrollLeft(scroll_offset.x);
- if (overflow_y_property != Style::Overflow::Visible)
- scroll_parent->SetScrollTop(scroll_offset.y);
- }
- scroll_parent = scroll_parent->GetParentNode();
- }
- }
- // Appends a child to this element
- Element* Element::AppendChild(ElementPtr child, bool dom_element)
- {
- RMLUI_ASSERT(child);
- Element* child_ptr = child.get();
- child_ptr->SetParent(this);
- if (dom_element)
- children.insert(children.end() - num_non_dom_children, std::move(child));
- else
- {
- children.push_back(std::move(child));
- num_non_dom_children++;
- }
- Element* ancestor = child_ptr;
- for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
- ancestor->OnChildAdd(child_ptr);
- DirtyStackingContext();
- DirtyStructure();
- if (dom_element)
- DirtyLayout();
- return child_ptr;
- }
- // Adds a child to this element, directly after the adjacent element. Inherits
- // the dom/non-dom status from the adjacent element.
- Element* Element::InsertBefore(ElementPtr child, Element* adjacent_element)
- {
- RMLUI_ASSERT(child);
- // Find the position in the list of children of the adjacent element. If
- // it's nullptr or we can't find it, then we insert it at the end of the dom
- // children, as a dom element.
- size_t child_index = 0;
- bool found_child = false;
- if (adjacent_element)
- {
- for (child_index = 0; child_index < children.size(); child_index++)
- {
- if (children[child_index].get() == adjacent_element)
- {
- found_child = true;
- break;
- }
- }
- }
- Element* child_ptr = nullptr;
- if (found_child)
- {
- child_ptr = child.get();
- child_ptr->SetParent(this);
- if ((int) child_index >= GetNumChildren())
- num_non_dom_children++;
- else
- DirtyLayout();
- children.insert(children.begin() + child_index, std::move(child));
- Element* ancestor = child_ptr;
- for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
- ancestor->OnChildAdd(child_ptr);
- DirtyStackingContext();
- DirtyStructure();
- }
- else
- {
- child_ptr = AppendChild(std::move(child));
- }
- return child_ptr;
- }
- // Replaces the second node with the first node.
- ElementPtr Element::ReplaceChild(ElementPtr inserted_element, Element* replaced_element)
- {
- RMLUI_ASSERT(inserted_element);
- auto insertion_point = children.begin();
- while (insertion_point != children.end() && insertion_point->get() != replaced_element)
- {
- ++insertion_point;
- }
- Element* inserted_element_ptr = inserted_element.get();
- if (insertion_point == children.end())
- {
- AppendChild(std::move(inserted_element));
- return nullptr;
- }
- inserted_element_ptr->SetParent(this);
- children.insert(insertion_point, std::move(inserted_element));
- ElementPtr result = RemoveChild(replaced_element);
- Element* ancestor = inserted_element_ptr;
- for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
- ancestor->OnChildAdd(inserted_element_ptr);
- return result;
- }
- // Removes the specified child
- ElementPtr Element::RemoveChild(Element* child)
- {
- size_t child_index = 0;
- for (auto itr = children.begin(); itr != children.end(); ++itr)
- {
- // Add the element to the delete list
- if (itr->get() == child)
- {
- Element* ancestor = child;
- for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
- ancestor->OnChildRemove(child);
- if (child_index >= children.size() - num_non_dom_children)
- num_non_dom_children--;
- ElementPtr detached_child = std::move(*itr);
- children.erase(itr);
- // Remove the child element as the focused child of this element.
- if (child == focus)
- {
- focus = nullptr;
- // If this child (or a descendant of this child) is the context's currently
- // focused element, set the focus to us instead.
- if (Context * context = GetContext())
- {
- Element* focus_element = context->GetFocusElement();
- while (focus_element)
- {
- if (focus_element == child)
- {
- Focus();
- break;
- }
- focus_element = focus_element->GetParentNode();
- }
- }
- }
- detached_child->SetParent(nullptr);
- DirtyLayout();
- DirtyStackingContext();
- DirtyStructure();
- return detached_child;
- }
- child_index++;
- }
- return nullptr;
- }
- bool Element::HasChildNodes() const
- {
- return (int) children.size() > num_non_dom_children;
- }
- Element* Element::GetElementById(const String& id)
- {
- // Check for special-case tokens.
- if (id == "#self")
- return this;
- else if (id == "#document")
- return GetOwnerDocument();
- else if (id == "#parent")
- return this->parent;
- else
- {
- Element* search_root = GetOwnerDocument();
- if (search_root == nullptr)
- search_root = this;
- return ElementUtilities::GetElementById(search_root, id);
- }
- }
- // Get all elements with the given tag.
- void Element::GetElementsByTagName(ElementList& elements, const String& tag)
- {
- return ElementUtilities::GetElementsByTagName(elements, this, tag);
- }
- // Get all elements with the given class set on them.
- void Element::GetElementsByClassName(ElementList& elements, const String& class_name)
- {
- return ElementUtilities::GetElementsByClassName(elements, this, class_name);
- }
- // Access the event dispatcher
- EventDispatcher* Element::GetEventDispatcher() const
- {
- return &meta->event_dispatcher;
- }
- String Element::GetEventDispatcherSummary() const
- {
- return meta->event_dispatcher.ToString();
- }
- // Access the element background.
- ElementBackground* Element::GetElementBackground() const
- {
- return &meta->background;
- }
- // Access the element border.
- ElementBorder* Element::GetElementBorder() const
- {
- return &meta->border;
- }
- // Access the element decorators
- ElementDecoration* Element::GetElementDecoration() const
- {
- return &meta->decoration;
- }
- // Returns the element's scrollbar functionality.
- ElementScroll* Element::GetElementScroll() const
- {
- return &meta->scroll;
- }
-
- int Element::GetClippingIgnoreDepth()
- {
- if (clipping_state_dirty)
- {
- IsClippingEnabled();
- }
-
- return clipping_ignore_depth;
- }
-
- bool Element::IsClippingEnabled()
- {
- if (clipping_state_dirty)
- {
- const auto& computed = GetComputedValues();
- // Is clipping enabled for this element, yes unless both overlow properties are set to visible
- clipping_enabled = computed.overflow_x != Style::Overflow::Visible
- || computed.overflow_y != Style::Overflow::Visible;
-
- // Get the clipping ignore depth from the clip property
- clipping_ignore_depth = computed.clip.number;
- clipping_state_dirty = false;
- }
-
- return clipping_enabled;
- }
- // Gets the render interface owned by this element's context.
- RenderInterface* Element::GetRenderInterface()
- {
- if (Context* context = GetContext())
- return context->GetRenderInterface();
- return Rml::Core::GetRenderInterface();
- }
- void Element::SetInstancer(ElementInstancer* _instancer)
- {
- // Only record the first instancer being set as some instancers call other instancers to do their dirty work, in
- // which case we don't want to update the lowest level instancer.
- if (!instancer)
- {
- instancer = _instancer;
- }
- }
- // Forces the element to generate a local stacking context, regardless of the value of its z-index property.
- void Element::ForceLocalStackingContext()
- {
- local_stacking_context_forced = true;
- local_stacking_context = true;
- DirtyStackingContext();
- }
- // Called during the update loop after children are rendered.
- void Element::OnUpdate()
- {
- }
- // Called during render after backgrounds, borders, decorators, but before children, are rendered.
- void Element::OnRender()
- {
- }
- void Element::OnResize()
- {
- }
- // Called during a layout operation, when the element is being positioned and sized.
- void Element::OnLayout()
- {
- }
- // Called when attributes on the element are changed.
- void Element::OnAttributeChange(const ElementAttributes& changed_attributes)
- {
- auto it = changed_attributes.find("id");
- if (it != changed_attributes.end())
- {
- id = it->second.Get<String>();
- meta->style.DirtyDefinition();
- }
- it = changed_attributes.find("class");
- if (it != changed_attributes.end())
- {
- meta->style.SetClassNames(it->second.Get<String>());
- }
- // Add any inline style declarations.
- it = changed_attributes.find("style");
- if (it != changed_attributes.end())
- {
- PropertyDictionary properties;
- StyleSheetParser parser;
- parser.ParseProperties(properties, it->second.Get<String>());
- Rml::Core::PropertyMap property_map = properties.GetProperties();
- for (Rml::Core::PropertyMap::iterator i = property_map.begin(); i != property_map.end(); ++i)
- {
- meta->style.SetProperty((*i).first, (*i).second);
- }
- }
- }
- // Called when properties on the element are changed.
- void Element::OnPropertyChange(const PropertyIdSet& changed_properties)
- {
- RMLUI_ZoneScoped;
- if (!IsLayoutDirty())
- {
- // Force a relayout if any of the changed properties require it.
- const PropertyIdSet changed_properties_forcing_layout = (changed_properties & StyleSheetSpecification::GetRegisteredPropertiesForcingLayout());
-
- if(!changed_properties_forcing_layout.Empty())
- DirtyLayout();
- }
- // Update the visibility.
- if (changed_properties.Contains(PropertyId::Visibility) ||
- changed_properties.Contains(PropertyId::Display))
- {
- bool new_visibility = (meta->computed_values.display != Style::Display::None && meta->computed_values.visibility == Style::Visibility::Visible);
-
- if (visible != new_visibility)
- {
- visible = new_visibility;
- if (parent != nullptr)
- parent->DirtyStackingContext();
- if (!visible)
- Blur();
- }
- if (changed_properties.Contains(PropertyId::Display))
- {
- // Due to structural pseudo-classes, this may change the element definition in siblings and parent.
- // However, the definitions will only be changed on the next update loop which may result in jarring behavior for one @frame.
- // A possible workaround is to add the parent to a list of elements that need to be updated again.
- if (parent != nullptr)
- parent->DirtyStructure();
- }
- }
- // Update the position.
- if (changed_properties.Contains(PropertyId::Left) ||
- changed_properties.Contains(PropertyId::Right) ||
- changed_properties.Contains(PropertyId::Top) ||
- changed_properties.Contains(PropertyId::Bottom))
- {
- // TODO: This should happen during/after layout, as the containing box is not properly defined yet. Off-by-one @frame issue.
- UpdateOffset();
- DirtyOffset();
- }
- // Update the z-index.
- if (changed_properties.Contains(PropertyId::ZIndex))
- {
- Style::ZIndex z_index_property = meta->computed_values.z_index;
- if (z_index_property.type == Style::ZIndex::Auto)
- {
- if (local_stacking_context &&
- !local_stacking_context_forced)
- {
- // We're no longer acting as a stacking context.
- local_stacking_context = false;
- stacking_context_dirty = false;
- stacking_context.clear();
- }
- // If our old z-index was not zero, then we must dirty our stacking context so we'll be re-indexed.
- if (z_index != 0)
- {
- z_index = 0;
- DirtyStackingContext();
- }
- }
- else
- {
- float new_z_index = z_index_property.value;
- if (new_z_index != z_index)
- {
- z_index = new_z_index;
- if (parent != nullptr)
- parent->DirtyStackingContext();
- }
- if (!local_stacking_context)
- {
- local_stacking_context = true;
- stacking_context_dirty = true;
- }
- }
- }
- // Dirty the background if it's changed.
- if (changed_properties.Contains(PropertyId::BackgroundColor) ||
- changed_properties.Contains(PropertyId::Opacity) ||
- changed_properties.Contains(PropertyId::ImageColor)) {
- meta->background.DirtyBackground();
- }
-
- // Dirty the decoration if it's changed.
- if (changed_properties.Contains(PropertyId::Decorator) ||
- changed_properties.Contains(PropertyId::Opacity) ||
- changed_properties.Contains(PropertyId::ImageColor)) {
- meta->decoration.DirtyDecorators();
- }
- // Dirty the border if it's changed.
- if (changed_properties.Contains(PropertyId::BorderTopWidth) ||
- changed_properties.Contains(PropertyId::BorderRightWidth) ||
- changed_properties.Contains(PropertyId::BorderBottomWidth) ||
- changed_properties.Contains(PropertyId::BorderLeftWidth) ||
- changed_properties.Contains(PropertyId::BorderTopColor) ||
- changed_properties.Contains(PropertyId::BorderRightColor) ||
- changed_properties.Contains(PropertyId::BorderBottomColor) ||
- changed_properties.Contains(PropertyId::BorderLeftColor) ||
- changed_properties.Contains(PropertyId::Opacity))
- meta->border.DirtyBorder();
-
- // Check for clipping state changes
- if (changed_properties.Contains(PropertyId::Clip) ||
- changed_properties.Contains(PropertyId::OverflowX) ||
- changed_properties.Contains(PropertyId::OverflowY))
- {
- clipping_state_dirty = true;
- }
- // Check for `perspective' and `perspective-origin' changes
- if (changed_properties.Contains(PropertyId::Perspective) ||
- changed_properties.Contains(PropertyId::PerspectiveOriginX) ||
- changed_properties.Contains(PropertyId::PerspectiveOriginY))
- {
- DirtyTransformState(true, false);
- }
- // Check for `transform' and `transform-origin' changes
- if (changed_properties.Contains(PropertyId::Transform) ||
- changed_properties.Contains(PropertyId::TransformOriginX) ||
- changed_properties.Contains(PropertyId::TransformOriginY) ||
- changed_properties.Contains(PropertyId::TransformOriginZ))
- {
- DirtyTransformState(false, true);
- }
- // Check for `animation' changes
- if (changed_properties.Contains(PropertyId::Animation))
- {
- dirty_animation = true;
- }
- // Check for `transition' changes
- if (changed_properties.Contains(PropertyId::Transition))
- {
- dirty_transition = true;
- }
- }
- // Called when a child node has been added somewhere in the hierarchy
- void Element::OnChildAdd(Element* child)
- {
- }
- // Called when a child node has been removed somewhere in the hierarchy
- void Element::OnChildRemove(Element* child)
- {
- }
- // Forces a re-layout of this element, and any other children required.
- void Element::DirtyLayout()
- {
- Element* document = GetOwnerDocument();
- if (document != nullptr)
- document->DirtyLayout();
- }
- // Forces a re-layout of this element, and any other children required.
- bool Element::IsLayoutDirty()
- {
- Element* document = GetOwnerDocument();
- if (document != nullptr)
- return document->IsLayoutDirty();
- return false;
- }
- void Element::ProcessDefaultAction(Event& event)
- {
- if (event == EventId::Mousedown && IsPointWithinElement(Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0))) &&
- event.GetParameter< int >("button", 0) == 0)
- SetPseudoClass("active", true);
- if (event == EventId::Mousescroll)
- {
- if (GetScrollHeight() > GetClientHeight())
- {
- Style::Overflow overflow_property = meta->computed_values.overflow_y;
- if (overflow_property == Style::Overflow::Auto ||
- overflow_property == Style::Overflow::Scroll)
- {
- // Stop the propagation if the current element has scrollbars.
- // This prevents scrolling in parent elements, which is often unintended. If instead desired behavior is
- // to scroll in parent elements when reaching top/bottom, move StopPropagation inside the next if statement.
- event.StopPropagation();
- const float wheel_delta = event.GetParameter< float >("wheel_delta", 0.f);
- if ((wheel_delta < 0 && GetScrollTop() > 0) ||
- (wheel_delta > 0 && GetScrollHeight() > GetScrollTop() + GetClientHeight()))
- {
- // Defined as three times the default line-height, multiplied by the dp ratio.
- float default_scroll_length = 3.f * DefaultComputedValues.line_height.value;
- if (const Context* context = GetContext())
- default_scroll_length *= context->GetDensityIndependentPixelRatio();
- SetScrollTop(GetScrollTop() + wheel_delta * default_scroll_length);
- }
- }
- }
- return;
- }
- if (event.GetPhase() == EventPhase::Target)
- {
- switch (event.GetId())
- {
- case EventId::Mouseover:
- SetPseudoClass("hover", true);
- break;
- case EventId::Mouseout:
- SetPseudoClass("hover", false);
- break;
- case EventId::Focus:
- SetPseudoClass(FOCUS, true);
- break;
- case EventId::Blur:
- SetPseudoClass(FOCUS, false);
- break;
- default:
- break;
- }
- }
- }
- const Style::ComputedValues& Element::GetComputedValues() const
- {
- return meta->computed_values;
- }
- void Element::GetRML(String& content)
- {
- // First we start the open tag, add the attributes then close the open tag.
- // Then comes the children in order, then we add our close tag.
- content += "<";
- content += tag;
- for (auto& pair : attributes)
- {
- auto& name = pair.first;
- auto& variant = pair.second;
- String value;
- if (variant.GetInto(value))
- content += " " + name + "=\"" + value + "\"";
- }
- if (HasChildNodes())
- {
- content += ">";
- GetInnerRML(content);
- content += "</";
- content += tag;
- content += ">";
- }
- else
- {
- content += " />";
- }
- }
- void Element::SetOwnerDocument(ElementDocument* document)
- {
- // If this element is a document, then never change owner_document.
- if (owner_document != this)
- {
- if (owner_document && !document)
- {
- // We are detaching from the document and thereby also the context.
- if (Context * context = owner_document->GetContext())
- context->OnElementDetach(this);
- }
- if (owner_document != document)
- {
- owner_document = document;
- for (ElementPtr& child : children)
- child->SetOwnerDocument(document);
- }
- }
- }
- void Element::Release()
- {
- if (instancer)
- instancer->ReleaseElement(this);
- else
- Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via RmlUi Factory. Unable to release.", GetAddress().c_str());
- }
- void Element::SetParent(Element* _parent)
- {
- // Assumes we are already detached from the hierarchy or we are detaching now.
- RMLUI_ASSERT(!parent || !_parent);
- parent = _parent;
- if (parent)
- {
- // We need to update our definition and make sure we inherit the properties of our new parent.
- meta->style.DirtyDefinition();
- meta->style.DirtyInheritedProperties();
- }
- // The transform state may require recalculation.
- if (transform_state || (parent && parent->transform_state))
- DirtyTransformState(true, true);
- SetOwnerDocument(parent ? parent->GetOwnerDocument() : nullptr);
- }
- void Element::DirtyOffset()
- {
- if(!offset_dirty)
- {
- offset_dirty = true;
- if(transform_state)
- DirtyTransformState(true, true);
- // Not strictly true ... ?
- for (size_t i = 0; i < children.size(); i++)
- children[i]->DirtyOffset();
- }
- }
- void Element::UpdateOffset()
- {
- using namespace Style;
- const auto& computed = meta->computed_values;
- Position position_property = computed.position;
- if (position_property == Position::Absolute ||
- position_property == Position::Fixed)
- {
- if (offset_parent != nullptr)
- {
- const Box& parent_box = offset_parent->GetBox();
- Vector2f containing_block = parent_box.GetSize(Box::PADDING);
- // If the element is anchored left, then the position is offset by that resolved value.
- if (computed.left.type != Left::Auto)
- relative_offset_base.x = parent_box.GetEdge(Box::BORDER, Box::LEFT) + (ResolveValue(computed.left, containing_block.x) + GetBox().GetEdge(Box::MARGIN, Box::LEFT));
- // If the element is anchored right, then the position is set first so the element's right-most edge
- // (including margins) will render up against the containing box's right-most content edge, and then
- // offset by the resolved value.
- else if (computed.right.type != Right::Auto)
- 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));
- // If the element is anchored top, then the position is offset by that resolved value.
- if (computed.top.type != Top::Auto)
- relative_offset_base.y = parent_box.GetEdge(Box::BORDER, Box::TOP) + (ResolveValue(computed.top, containing_block.y) + GetBox().GetEdge(Box::MARGIN, Box::TOP));
- // If the element is anchored bottom, then the position is set first so the element's right-most edge
- // (including margins) will render up against the containing box's right-most content edge, and then
- // offset by the resolved value.
- else if (computed.bottom.type != Bottom::Auto)
- 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));
- }
- }
- else if (position_property == Position::Relative)
- {
- if (offset_parent != nullptr)
- {
- const Box& parent_box = offset_parent->GetBox();
- Vector2f containing_block = parent_box.GetSize();
- if (computed.left.type != Left::Auto)
- relative_offset_position.x = ResolveValue(computed.left, containing_block.x);
- else if (computed.right.type != Right::Auto)
- relative_offset_position.x = -1 * ResolveValue(computed.right, containing_block.x);
- else
- relative_offset_position.x = 0;
- if (computed.top.type != Top::Auto)
- relative_offset_position.y = ResolveValue(computed.top, containing_block.y);
- else if (computed.bottom.type != Bottom::Auto)
- relative_offset_position.y = -1 * ResolveValue(computed.bottom, containing_block.y);
- else
- relative_offset_position.y = 0;
- }
- }
- else
- {
- relative_offset_position.x = 0;
- relative_offset_position.y = 0;
- }
- }
- void Element::BuildLocalStackingContext()
- {
- stacking_context_dirty = false;
- stacking_context.clear();
- BuildStackingContext(&stacking_context);
- std::stable_sort(stacking_context.begin(), stacking_context.end(), ElementSortZIndex());
- }
- void Element::BuildStackingContext(ElementList* new_stacking_context)
- {
- RMLUI_ZoneScoped;
- // Build the list of ordered children. Our child list is sorted within the stacking context so stacked elements
- // will render in the right order; ie, positioned elements will render on top of inline elements, which will render
- // on top of floated elements, which will render on top of block elements.
- std::vector< std::pair< Element*, float > > ordered_children;
- for (size_t i = 0; i < children.size(); ++i)
- {
- Element* child = children[i].get();
- if (!child->IsVisible())
- continue;
- std::pair< Element*, float > ordered_child;
- ordered_child.first = child;
- if (child->GetPosition() != Style::Position::Static)
- ordered_child.second = 3;
- else if (child->GetFloat() != Style::Float::None)
- ordered_child.second = 1;
- else if (child->GetDisplay() == Style::Display::Block)
- ordered_child.second = 0;
- else
- ordered_child.second = 2;
- ordered_children.push_back(ordered_child);
- }
- // Sort the list!
- std::stable_sort(ordered_children.begin(), ordered_children.end(), ElementSortZOrder());
- // Add the list of ordered children into the stacking context in order.
- for (size_t i = 0; i < ordered_children.size(); ++i)
- {
- new_stacking_context->push_back(ordered_children[i].first);
- if (!ordered_children[i].first->local_stacking_context)
- ordered_children[i].first->BuildStackingContext(new_stacking_context);
- }
- }
- void Element::DirtyStackingContext()
- {
- // The first ancestor of ours that doesn't have an automatic z-index is the ancestor that is establishing our local
- // stacking context.
- Element* stacking_context_parent = this;
- while (stacking_context_parent != nullptr &&
- !stacking_context_parent->local_stacking_context)
- stacking_context_parent = stacking_context_parent->GetParentNode();
- if (stacking_context_parent != nullptr)
- stacking_context_parent->stacking_context_dirty = true;
- }
- void Element::DirtyStructure()
- {
- structure_dirty = true;
- }
- void Element::UpdateStructure()
- {
- if (structure_dirty)
- {
- structure_dirty = false;
- // If this element or its children depend on structured selectors, they may need to be updated.
- GetStyle()->DirtyDefinition();
- }
- }
- 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)
- {
- bool result = false;
- PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
- auto it_animation = StartAnimation(property_id, start_value, num_iterations, alternate_direction, delay, false);
- if (it_animation != animations.end())
- {
- result = it_animation->AddKey(duration, target_value, *this, tween, true);
- if (!result)
- animations.erase(it_animation);
- }
- return result;
- }
- bool Element::AddAnimationKey(const String & property_name, const Property & target_value, float duration, Tween tween)
- {
- ElementAnimation* animation = nullptr;
- PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
- for (auto& existing_animation : animations) {
- if (existing_animation.GetPropertyId() == property_id) {
- animation = &existing_animation;
- break;
- }
- }
- if (!animation)
- return false;
- bool result = animation->AddKey(animation->GetDuration() + duration, target_value, *this, tween, true);
- return result;
- }
- ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, const Property* start_value, int num_iterations, bool alternate_direction, float delay, bool initiated_by_animation_property)
- {
- auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == property_id; });
- if (it != animations.end())
- {
- *it = ElementAnimation{};
- }
- else
- {
- animations.emplace_back();
- it = animations.end() - 1;
- }
- Property value;
- if (start_value)
- {
- value = *start_value;
- if (!value.definition)
- if(auto default_value = GetProperty(property_id))
- value.definition = default_value->definition;
- }
- else if (auto default_value = GetProperty(property_id))
- {
- value = *default_value;
- }
- if (value.definition)
- {
- ElementAnimationOrigin origin = (initiated_by_animation_property ? ElementAnimationOrigin::Animation : ElementAnimationOrigin::User);
- double start_time = Clock::GetElapsedTime() + (double)delay;
- *it = ElementAnimation{ property_id, origin, value, *this, start_time, 0.0f, num_iterations, alternate_direction };
- }
-
- if(!it->IsInitalized())
- {
- animations.erase(it);
- it = animations.end();
- }
- return it;
- }
- bool Element::AddAnimationKeyTime(PropertyId property_id, const Property* target_value, float time, Tween tween)
- {
- if (!target_value)
- target_value = meta->style.GetProperty(property_id);
- if (!target_value)
- return false;
- ElementAnimation* animation = nullptr;
- for (auto& existing_animation : animations) {
- if (existing_animation.GetPropertyId() == property_id) {
- animation = &existing_animation;
- break;
- }
- }
- if (!animation)
- return false;
- bool result = animation->AddKey(time, *target_value, *this, tween, true);
- return result;
- }
- bool Element::StartTransition(const Transition & transition, const Property& start_value, const Property & target_value)
- {
- auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == transition.id; });
- if (it != animations.end() && !it->IsTransition())
- return false;
- float duration = transition.duration;
- double start_time = Clock::GetElapsedTime() + (double)transition.delay;
- if (it == animations.end())
- {
- // Add transition as new animation
- animations.push_back(
- ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false }
- );
- it = (animations.end() - 1);
- }
- else
- {
- // Compress the duration based on the progress of the current animation
- float f = it->GetInterpolationFactor();
- f = 1.0f - (1.0f - f)*transition.reverse_adjustment_factor;
- duration = duration * f;
- // Replace old transition
- *it = ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false };
- }
- bool result = it->AddKey(duration, target_value, *this, transition.tween, true);
- if (result)
- SetProperty(transition.id, start_value);
- else
- animations.erase(it);
- return result;
- }
- void Element::HandleTransitionProperty()
- {
- if(dirty_transition)
- {
- dirty_transition = false;
- // Remove all transitions that are no longer in our local list
- const TransitionList& keep_transitions = GetComputedValues().transition;
- if (keep_transitions.all)
- return;
- auto it_remove = animations.end();
- if (keep_transitions.none)
- {
- // All transitions should be removed, but only touch the animations that originate from the 'transition' property.
- // Move all animations to be erased in a valid state at the end of the list, and erase later.
- it_remove = std::partition(animations.begin(), animations.end(),
- [](const ElementAnimation& animation) -> bool { return !animation.IsTransition(); }
- );
- }
- else
- {
- // Only remove the transitions that are not in our keep list.
- const auto& keep_transitions_list = keep_transitions.transitions;
- it_remove = std::partition(animations.begin(), animations.end(),
- [&keep_transitions_list](const ElementAnimation& animation) -> bool {
- if (!animation.IsTransition())
- return true;
- auto it = std::find_if(keep_transitions_list.begin(), keep_transitions_list.end(),
- [&animation](const Transition& transition) { return animation.GetPropertyId() == transition.id; }
- );
- bool keep_animation = (it != keep_transitions_list.end());
- return keep_animation;
- }
- );
- }
- // We can decide what to do with cancelled transitions here.
- for (auto it = it_remove; it != animations.end(); ++it)
- RemoveProperty(it->GetPropertyId());
- animations.erase(it_remove, animations.end());
- }
- }
- void Element::HandleAnimationProperty()
- {
- // Note: We are effectively restarting all animations whenever 'dirty_animation' is set. Use the dirty flag with care,
- // or find another approach which only updates actual "dirty" animations.
- if (dirty_animation)
- {
- dirty_animation = false;
- const AnimationList& animation_list = meta->computed_values.animation;
- bool element_has_animations = (!animation_list.empty() || !animations.empty());
- StyleSheet* stylesheet = nullptr;
- if (element_has_animations && (stylesheet = GetStyleSheet().get()))
- {
- // Remove existing animations
- {
- // We only touch the animations that originate from the 'animation' property.
- auto it_remove = std::partition(animations.begin(), animations.end(),
- [](const ElementAnimation & animation) { return animation.GetOrigin() != ElementAnimationOrigin::Animation; }
- );
- // We can decide what to do with cancelled animations here.
- for (auto it = it_remove; it != animations.end(); ++it)
- RemoveProperty(it->GetPropertyId());
- animations.erase(it_remove, animations.end());
- }
- // Start animations
- for (const auto& animation : animation_list)
- {
- const Keyframes* keyframes_ptr = stylesheet->GetKeyframes(animation.name);
- if (keyframes_ptr && keyframes_ptr->blocks.size() >= 1 && !animation.paused)
- {
- auto& property_ids = keyframes_ptr->property_ids;
- auto& blocks = keyframes_ptr->blocks;
- bool has_from_key = (blocks[0].normalized_time == 0);
- bool has_to_key = (blocks.back().normalized_time == 1);
- // If the first key defines initial conditions for a given property, use those values, else, use this element's current values.
- for (PropertyId id : property_ids)
- StartAnimation(id, (has_from_key ? blocks[0].properties.GetProperty(id) : nullptr), animation.num_iterations, animation.alternate, animation.delay, true);
- // Add middle keys: Need to skip the first and last keys if they set the initial and end conditions, respectively.
- for (int i = (has_from_key ? 1 : 0); i < (int)blocks.size() + (has_to_key ? -1 : 0); i++)
- {
- // Add properties of current key to animation
- float time = blocks[i].normalized_time * animation.duration;
- for (auto& property : blocks[i].properties.GetProperties())
- AddAnimationKeyTime(property.first, &property.second, time, animation.tween);
- }
- // If the last key defines end conditions for a given property, use those values, else, use this element's current values.
- float time = animation.duration;
- for (PropertyId id : property_ids)
- AddAnimationKeyTime(id, (has_to_key ? blocks.back().properties.GetProperty(id) : nullptr), time, animation.tween);
- }
- }
- }
- }
- }
- void Element::AdvanceAnimations()
- {
- if (!animations.empty())
- {
- double time = Clock::GetElapsedTime();
- for (auto& animation : animations)
- {
- Property property = animation.UpdateAndGetProperty(time, *this);
- if (property.unit != Property::UNKNOWN)
- SetProperty(animation.GetPropertyId(), property);
- }
- // Move all completed animations to the end of the list
- auto it_completed = std::partition(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return !animation.IsComplete(); });
- std::vector<Dictionary> dictionary_list;
- std::vector<bool> is_transition;
- dictionary_list.reserve(animations.end() - it_completed);
- is_transition.reserve(animations.end() - it_completed);
- for (auto it = it_completed; it != animations.end(); ++it)
- {
- const String& property_name = StyleSheetSpecification::GetPropertyName(it->GetPropertyId());
- dictionary_list.emplace_back();
- dictionary_list.back().emplace("property", Variant(property_name));
- is_transition.push_back(it->IsTransition());
- // Remove completed transition- and animation-initiated properties.
- // Should behave like in HandleTransitionProperty() and HandleAnimationProperty() respectively.
- if (it->GetOrigin() != ElementAnimationOrigin::User)
- RemoveProperty(it->GetPropertyId());
- }
- // Need to erase elements before submitting event, as iterators might be invalidated when calling external code.
- animations.erase(it_completed, animations.end());
- for (size_t i = 0; i < dictionary_list.size(); i++)
- DispatchEvent(is_transition[i] ? EventId::Transitionend : EventId::Animationend, dictionary_list[i]);
- }
- }
- void Element::DirtyTransformState(bool perspective_dirty, bool transform_dirty)
- {
- dirty_perspective |= perspective_dirty;
- dirty_transform |= transform_dirty;
- }
- void Element::UpdateTransformState()
- {
- if (!dirty_perspective && !dirty_transform)
- return;
- const ComputedValues& computed = meta->computed_values;
- const Vector2f pos = GetAbsoluteOffset(Box::BORDER);
- const Vector2f size = GetBox().GetSize(Box::BORDER);
-
- bool perspective_or_transform_changed = false;
- if (dirty_perspective)
- {
- // If perspective is set on this element, then it applies to our children. We just calculate it here,
- // and let the children's transform update merge it with their transform.
- bool had_perspective = (transform_state && transform_state->GetLocalPerspective());
- float distance = computed.perspective;
- Vector2f vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
- bool have_perspective = false;
- if (distance > 0.0f)
- {
- have_perspective = true;
- // Compute the vanishing point from the perspective origin
- if (computed.perspective_origin_x.type == Style::PerspectiveOrigin::Percentage)
- vanish.x = pos.x + computed.perspective_origin_x.value * 0.01f * size.x;
- else
- vanish.x = pos.x + computed.perspective_origin_x.value;
- if (computed.perspective_origin_y.type == Style::PerspectiveOrigin::Percentage)
- vanish.y = pos.y + computed.perspective_origin_y.value * 0.01f * size.y;
- else
- vanish.y = pos.y + computed.perspective_origin_y.value;
- }
- if (have_perspective)
- {
- // Equivalent to: Translate(x,y,0) * Perspective(distance) * Translate(-x,-y,0)
- Matrix4f perspective = Matrix4f::FromRows(
- { 1, 0, -vanish.x / distance, 0 },
- { 0, 1, -vanish.y / distance, 0 },
- { 0, 0, 1, 0 },
- { 0, 0, -1 / distance, 1 }
- );
- if (!transform_state)
- transform_state = std::make_unique<TransformState>();
- perspective_or_transform_changed |= transform_state->SetLocalPerspective(&perspective);
- }
- else if (transform_state)
- transform_state->SetLocalPerspective(nullptr);
- perspective_or_transform_changed |= (have_perspective != had_perspective);
- dirty_perspective = false;
- }
- if (dirty_transform)
- {
- // We want to find the accumulated transform given all our ancestors. It is assumed here that the parent transform is already updated,
- // so that we only need to consider our local transform and combine it with our parent's transform and perspective matrices.
- bool had_transform = (transform_state && transform_state->GetTransform());
- bool have_transform = false;
- Matrix4f transform = Matrix4f::Identity();
- if (computed.transform)
- {
- // First find the current element's transform
- const int n = computed.transform->GetNumPrimitives();
- for (int i = 0; i < n; ++i)
- {
- const Transforms::Primitive& primitive = computed.transform->GetPrimitive(i);
- Matrix4f matrix;
- if (primitive.ResolveTransform(matrix, *this))
- {
- transform *= matrix;
- have_transform = true;
- }
- }
- if(have_transform)
- {
- // Compute the transform origin
- Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
- if (computed.transform_origin_x.type == Style::TransformOrigin::Percentage)
- transform_origin.x = pos.x + computed.transform_origin_x.value * size.x * 0.01f;
- else
- transform_origin.x = pos.x + computed.transform_origin_x.value;
- if (computed.transform_origin_y.type == Style::TransformOrigin::Percentage)
- transform_origin.y = pos.y + computed.transform_origin_y.value * size.y * 0.01f;
- else
- transform_origin.y = pos.y + computed.transform_origin_y.value;
- transform_origin.z = computed.transform_origin_z;
- // Make the transformation apply relative to the transform origin
- transform = Matrix4f::Translate(transform_origin) * transform * Matrix4f::Translate(-transform_origin);
- }
- // We may want to include the local offsets here, as suggested by the CSS specs, so that the local transform is applied after the offset I believe
- // the motivation is. Then we would need to subtract the absolute zero-offsets during geometry submit whenever we have transforms.
- }
- if (parent && parent->transform_state)
- {
- // Apply the parent's local perspective and transform.
- // @performance: If we have no local transform and no parent perspective, we can effectively just point to the parent transform instead of copying it.
- const TransformState& parent_state = *parent->transform_state;
- if (auto parent_perspective = parent_state.GetLocalPerspective())
- {
- transform = *parent_perspective * transform;
- have_transform = true;
- }
- if (auto parent_transform = parent_state.GetTransform())
- {
- transform = *parent_transform * transform;
- have_transform = true;
- }
- }
- if (have_transform)
- {
- if (!transform_state)
- transform_state = std::make_unique<TransformState>();
- perspective_or_transform_changed |= transform_state->SetTransform(&transform);
- }
- else if (transform_state)
- transform_state->SetTransform(nullptr);
- perspective_or_transform_changed |= (had_transform != have_transform);
- }
- // A change in perspective or transform will require an update to children transforms as well.
- if (perspective_or_transform_changed)
- {
- for (size_t i = 0; i < children.size(); i++)
- children[i]->DirtyTransformState(false, true);
- }
- // No reason to keep the transform state around if transform and perspective have been removed.
- if (transform_state && !transform_state->GetTransform() && !transform_state->GetLocalPerspective())
- {
- transform_state.reset();
- }
- }
- }
- }
|