| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864 |
- /*
- * 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 "precompiled.h"
- #include "../../Include/RmlUi/Core/Element.h"
- #include "../../Include/RmlUi/Core/Dictionary.h"
- #include "../../Include/RmlUi/Core/TransformPrimitive.h"
- #include <algorithm>
- #include <limits>
- #include "Clock.h"
- #include "ComputeProperty.h"
- #include "DirtyPropertyList.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 "FontFaceHandle.h"
- #include "LayoutEngine.h"
- #include "PluginRegistry.h"
- #include "PropertiesIterator.h"
- #include "Pool.h"
- #include "StyleSheetParser.h"
- #include "XMLParseTools.h"
- #include "../../Include/RmlUi/Core/Core.h"
- 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;
- struct ElementMetaChunk;
- static Pool< ElementMetaChunk > element_meta_chunk_pool(200, true);
- // 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;
- void* operator new(size_t size)
- {
- void* memory = element_meta_chunk_pool.AllocateObject();
- return memory;
- }
- void operator delete(void* chunk)
- {
- element_meta_chunk_pool.DeallocateObject((ElementMetaChunk*)chunk);
- }
- };
- struct alignas(ElementMeta) ElementMetaChunk
- {
- ElementMetaChunk() { memset(buffer, 0, size); }
- static constexpr size_t size = sizeof(ElementMeta);
- char buffer[size];
- };
- /// 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(), transform_state_perspective_dirty(true), transform_state_transform_dirty(true), transform_state_parent_transform_dirty(true), dirty_animation(false), dirty_transition(false)
- {
- RMLUI_ASSERT(tag == ToLower(tag));
- parent = NULL;
- focus = NULL;
- instancer = NULL;
- owner_document = NULL;
- offset_fixed = false;
- offset_parent = NULL;
- 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;
- box_dirty = false;
- font_face_handle = NULL;
-
- clipping_ignore_depth = 0;
- clipping_enabled = false;
- clipping_state_dirty = true;
- element_meta = new ElementMeta(this);
- event_dispatcher = &element_meta->event_dispatcher;
- style = &element_meta->style;
- background = &element_meta->background;
- border = &element_meta->border;
- decoration = &element_meta->decoration;
- scroll = &element_meta->scroll;
- }
- Element::~Element()
- {
- RMLUI_ASSERT(parent == NULL);
- PluginRegistry::NotifyElementDestroy(this);
- // Remove scrollbar elements before we delete the children!
- 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->parent = nullptr;
- child->SetOwnerDocument(nullptr);
- }
- if (deleted_children.empty())
- {
- deleted_children = std::move(children);
- children.clear();
- }
- else
- {
- deleted_children.reserve(deleted_children.size() + children.size());
- for (auto& child : children)
- deleted_children.push_back(std::move(child));
- children.clear();
- }
-
- children.clear();
- num_non_dom_children = 0;
- // Release all deleted children.
- ReleaseElements();
- delete element_meta;
- if (font_face_handle != NULL)
- font_face_handle->RemoveReference();
- }
- void Element::Update(float dp_ratio)
- {
- ReleaseElements();
- OnUpdate();
- UpdateStructure();
- UpdateTransition();
- UpdateAnimation();
- AdvanceAnimations();
- style->UpdateDefinition();
- scroll->Update();
- if(style->AnyPropertiesDirty())
- {
- const ComputedValues* parent_values = nullptr;
- const ComputedValues* document_values = nullptr;
- if (parent)
- parent_values = &parent->GetComputedValues();
- if (auto doc = GetOwnerDocument())
- document_values = &doc->GetComputedValues();
- // Compute values and clear dirty properties
- auto dirty_properties = style->ComputeValues(element_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.
- // Enable RMLUI_DEBUG to get a warning when this happens.
- if (dirty_properties.IsAllDirty())
- OnPropertyChange(StyleSheetSpecification::GetRegisteredProperties());
- else if(!dirty_properties.Empty())
- OnPropertyChange(dirty_properties.ToPropertyList());
- #ifdef RMLUI_DEBUG
- if (style->AnyPropertiesDirty())
- 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.");
- #endif
- }
- if (box_dirty)
- {
- box_dirty = false;
- OnResize();
- }
- UpdateTransformState();
- for (size_t i = 0; i < children.size(); i++)
- children[i]->Update(dp_ratio);
- }
- void Element::Render()
- {
- // Rebuild our stacking context if necessary.
- if (stacking_context_dirty)
- BuildLocalStackingContext();
- // Apply our transform
- ElementUtilities::ApplyTransform(*this);
- // 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();
- // Set up the clipping region for this element.
- if (ElementUtilities::SetClippingRegion(this))
- {
- background->RenderBackground();
- border->RenderBorder();
- decoration->RenderDecorators();
- OnRender();
- }
- // Render the rest of the elements in the stacking context.
- for (; i < stacking_context.size(); ++i)
- stacking_context[i]->Render();
- // Unapply our transform
- ElementUtilities::UnapplyTransform(*this);
- }
- // 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 != NULL)
- {
- 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)
- {
- style->SetClass(class_name, activate);
- }
- // Checks if a class is set on the element.
- bool Element::IsClassSet(const String& class_name) const
- {
- return 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 style->GetClassNames();
- }
- // Returns the active style sheet for this element. This may be NULL.
- StyleSheet* Element::GetStyleSheet() const
- {
- return style->GetStyleSheet();
- }
- // Returns the element's definition, updating if necessary.
- const ElementDefinition* Element::GetDefinition()
- {
- return style->GetDefinition();
- }
- // Fills an String with the full address of this element.
- String Element::GetAddress(bool include_pseudo_classes) 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 = style->GetClassNames();
- if (!classes.empty())
- {
- classes = Replace(classes, '.', ' ');
- address += ".";
- address += classes;
- }
- if (include_pseudo_classes)
- {
- const PseudoClassList& pseudo_classes = style->GetActivePseudoClasses();
- for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
- {
- address += ":";
- address += (*i);
- }
- }
- if (parent)
- {
- address += " < ";
- return address + parent->GetAddress(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 != NULL)
- 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 != NULL)
- {
- 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();
- box_dirty = true;
- background->DirtyBackground();
- border->DirtyBorder();
- 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);
- box_dirty = true;
- background->DirtyBackground();
- border->DirtyBorder();
- 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 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 (!style->SetProperty(property.first, property.second))
- return false;
- }
- return true;
- }
- // Removes a local property override on the element.
- void Element::RemoveProperty(const String& name)
- {
- style->RemoveProperty(StyleSheetSpecification::GetPropertyId(name));
- }
- // Removes a local property override on the element.
- void Element::RemoveProperty(PropertyId id)
- {
- style->RemoveProperty(id);
- }
- // Sets a local property override on the element to a pre-parsed value.
- bool Element::SetProperty(PropertyId id, const Property& property)
- {
- return style->SetProperty(id, property);
- }
- // Returns one of this element's properties.
- const Property* Element::GetProperty(const String& name)
- {
- return style->GetProperty(StyleSheetSpecification::GetPropertyId(name));
- }
- // Returns one of this element's properties.
- const Property* Element::GetProperty(PropertyId id)
- {
- return style->GetProperty(id);
- }
- // Returns one of this element's properties.
- const Property* Element::GetLocalProperty(const String& name)
- {
- return style->GetLocalProperty(StyleSheetSpecification::GetPropertyId(name));
- }
- const Property* Element::GetLocalProperty(PropertyId id)
- {
- return style->GetLocalProperty(id);
- }
- const PropertyMap& Element::GetLocalStyleProperties()
- {
- return style->GetLocalStyleProperties();
- }
- // Resolves one of this element's style.
- float Element::ResolveLengthPercentage(const Property *property, float base_value)
- {
- return style->ResolveLengthPercentage(property, base_value);
- }
- Vector2f Element::GetContainingBlock()
- {
- Vector2f containing_block(0, 0);
- if (offset_parent != NULL)
- {
- 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 element_meta->computed_values.position;
- }
- Style::Float Element::GetFloat()
- {
- return element_meta->computed_values.float_;
- }
- Style::Display Element::GetDisplay()
- {
- return element_meta->computed_values.display;
- }
- float Element::GetLineHeight()
- {
- return element_meta->computed_values.line_height.value;
- }
- // Returns this element's TransformState
- const TransformState *Element::GetTransformState() const noexcept
- {
- return transform_state.get();
- }
- // Returns the TransformStates that are effective for this element.
- void Element::GetEffectiveTransformState(
- const TransformState **local_perspective,
- const TransformState **perspective,
- const TransformState **transform
- ) const noexcept
- {
- if (local_perspective)
- {
- *local_perspective = nullptr;
- }
- if (perspective)
- {
- *perspective = nullptr;
- }
- if (transform)
- {
- *transform = nullptr;
- }
- const Element *perspective_node = nullptr, *transform_node = nullptr;
- // Find the TransformState to use for unprojecting.
- if (transform_state.get() && transform_state->GetLocalPerspective(nullptr))
- {
- if (local_perspective)
- {
- *local_perspective = transform_state.get();
- }
- }
- else
- {
- const Element *node = nullptr;
- for (node = parent; node; node = node->parent)
- {
- if (node->transform_state.get() && node->transform_state->GetPerspective(nullptr))
- {
- if (perspective)
- {
- *perspective = node->transform_state.get();
- }
- perspective_node = node;
- break;
- }
- }
- }
- // Find the TransformState to use for transforming.
- const Element *node = nullptr;
- for (node = this; node; node = node->parent)
- {
- if (node->transform_state.get() && node->transform_state->GetRecursiveTransform(nullptr))
- {
- if (transform)
- {
- *transform = node->transform_state.get();
- }
- transform_node = node;
- break;
- }
- }
- }
- // Project a 2D point in pixel coordinates onto the element's plane.
- Vector2f Element::Project(const Vector2f& point) const noexcept
- {
- const Context *context = GetContext();
- if (!context)
- {
- return point;
- }
- const TransformState *local_perspective, *perspective, *transform;
- GetEffectiveTransformState(&local_perspective, &perspective, &transform);
- Vector2i view_pos(0, 0);
- Vector2i view_size = context->GetDimensions();
- // Compute the line segment for ray picking, one point on the near and one on the far plane.
- // These need to be in clip space coordinates ([-1; 1]³) so that we an unproject them.
- Vector3f line_segment[2] =
- {
- // When unprojected, the intersection point on the near plane
- Vector3f(
- (point.x - view_pos.x) / (0.5f * view_size.x) - 1.0f,
- (view_size.y - point.y - view_pos.y) / (0.5f * view_size.y) - 1.0f,
- -1
- ),
- // When unprojected, the intersection point on the far plane
- Vector3f(
- (point.x - view_pos.x) / (0.5f * view_size.x) - 1.0f,
- (view_size.y - point.y - view_pos.y) / (0.5f * view_size.y) - 1.0f,
- 1
- )
- };
- // Find the TransformState to use for unprojecting.
- if (local_perspective)
- {
- TransformState::LocalPerspective the_local_perspective;
- local_perspective->GetLocalPerspective(&the_local_perspective);
- line_segment[0] = the_local_perspective.Unproject(line_segment[0]);
- line_segment[1] = the_local_perspective.Unproject(line_segment[1]);
- }
- else if (perspective)
- {
- TransformState::Perspective the_perspective;
- perspective->GetPerspective(&the_perspective);
- line_segment[0] = the_perspective.Unproject(line_segment[0]);
- line_segment[1] = the_perspective.Unproject(line_segment[1]);
- }
- else
- {
- line_segment[0] = context->GetViewState().Unproject(line_segment[0]);
- line_segment[1] = context->GetViewState().Unproject(line_segment[1]);
- }
- // Compute three points on the context's corners to define the element's plane.
- // It may seem elegant to base this computation on the element's size, but
- // there are elements with zero length or height.
- Vector3f element_rect[3] =
- {
- // Top-left corner
- Vector3f(0, 0, 0),
- // Top-right corner
- Vector3f((float)view_size.x, 0, 0),
- // Bottom-left corner
- Vector3f(0, (float)view_size.y, 0)
- };
- // Transform by the correct matrix
- if (transform)
- {
- element_rect[0] = transform->Transform(element_rect[0]);
- element_rect[1] = transform->Transform(element_rect[1]);
- element_rect[2] = transform->Transform(element_rect[2]);
- }
- Vector3f u = line_segment[0] - line_segment[1];
- Vector3f v = element_rect[1] - element_rect[0];
- Vector3f w = element_rect[2] - element_rect[0];
- // Now compute the intersection point of the line segment and the element's rectangle.
- // This is based on the algorithm discussed at Wikipedia
- // (http://en.wikipedia.org/wiki/Line-plane_intersection).
- Matrix4f A = Matrix4f::FromColumns(
- Vector4f(u, 0),
- Vector4f(v, 0),
- Vector4f(w, 0),
- Vector4f(0, 0, 0, 1)
- );
- if (A.Invert())
- {
- Vector3f factors = A * (line_segment[0] - element_rect[0]);
- Vector3f intersection3d = element_rect[0] + v * factors[1] + w * factors[2];
- Vector3f projected;
- if (transform)
- {
- projected = transform->Untransform(intersection3d);
- //RMLUI_ASSERT(fabs(projected.z) < 0.0001);
- }
- else
- {
- // FIXME: Is this correct?
- projected = intersection3d;
- }
- return Vector2f(projected.x, projected.y);
- }
- else
- {
- // The line segment is parallel to the element's plane.
- // Although, mathematically, it could also lie within the plane
- // (yielding infinitely many intersection points), we still
- // return a value that's pretty sure to not match anything,
- // since this case has nothing to do with the user `picking'
- // anything.
- float inf = std::numeric_limits< float >::infinity();
- return Vector2f(-inf, -inf);
- }
- }
- PropertiesIteratorView Element::IterateLocalProperties() const
- {
- return PropertiesIteratorView(std::make_unique<PropertiesIterator>(style->Iterate()));
- }
- // Sets or removes a pseudo-class on the element.
- void Element::SetPseudoClass(const String& pseudo_class, bool activate)
- {
- 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 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 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 != NULL)
- return document->GetContext();
- return NULL;
- }
- // 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 - scroll->GetScrollbarSize(ElementScroll::VERTICAL);
- }
- // Gets the inner height of the element.
- float Element::GetClientHeight()
- {
- return GetBox().GetSize(client_area).y - 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(scroll_left, 0.0f, GetScrollWidth() - GetClientWidth());
- if (new_offset != scroll_offset.x)
- {
- scroll_offset.x = new_offset;
- 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(scroll_top, 0.0f, GetScrollHeight() - GetClientHeight());
- if(new_offset != scroll_offset.y)
- {
- scroll_offset.y = new_offset;
- 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 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 == NULL)
- return NULL;
- 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 NULL;
- }
- // Gets the element immediately preceding this one in the tree.
- Element* Element::GetPreviousSibling() const
- {
- if (parent == NULL)
- return NULL;
- 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 NULL;
- }
- // Returns the first child of this element.
- Element* Element::GetFirstChild() const
- {
- if (GetNumChildren() > 0)
- return children[0].get();
- return NULL;
- }
- // Gets the last child of this element.
- Element* Element::GetLastChild() const
- {
- if (GetNumChildren() > 0)
- return (children.end() - (num_non_dom_children + 1))->get();
- return NULL;
- }
- 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)
- {
- // 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 = element_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 == NULL)
- return false;
- if (!context->OnFocusChange(this))
- return false;
- // Set this as the end of the focus chain.
- focus = NULL;
- // Update the focus chain up the hierarchy.
- Element* element = this;
- while (element->GetParentNode())
- {
- element->GetParentNode()->focus = element;
- element = element->GetParentNode();
- }
- return true;
- }
- // Removes focus from from this element.
- void Element::Blur()
- {
- if (parent)
- {
- Context* context = GetContext();
- if (context == NULL)
- return;
- if (context->GetFocusElement() == this)
- {
- parent->Focus();
- }
- else if (parent->focus == this)
- {
- parent->focus = NULL;
- }
- }
- }
- // Fakes a mouse click on this element.
- void Element::Click()
- {
- Context* context = GetContext();
- if (context == NULL)
- 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);
- event_dispatcher->AttachEvent(id, listener, in_capture_phase);
- }
- // Adds an event listener
- void Element::AddEventListener(EventId id, EventListener* listener, bool in_capture_phase)
- {
- 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);
- 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)
- {
- 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 event_dispatcher->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 event_dispatcher->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 event_dispatcher->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 != NULL)
- {
- 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++;
- }
- child_ptr->GetStyle()->DirtyDefinition();
- 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 NULL 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));
- child_ptr->GetStyle()->DirtyDefinition();
- 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.
- bool 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 false;
- }
- inserted_element_ptr->SetParent(this);
- children.insert(insertion_point, std::move(inserted_element));
- RemoveChild(replaced_element);
- inserted_element_ptr->GetStyle()->DirtyDefinition();
- Element* ancestor = inserted_element_ptr;
- for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
- ancestor->OnChildAdd(inserted_element_ptr);
- return true;
- }
- bool Element::RemoveChild(Element* child)
- {
- ElementPtr released_child = ReleaseChild(child);
- if (!released_child)
- return false;
- //deleted_children.push_back(std::move(released_child));
- return true;
- }
- // Removes the specified child
- ElementPtr Element::ReleaseChild(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)
- {
- // Inform the context of the element's pending removal (if we have a valid context).
- Context* context = GetContext();
- if (context)
- context->OnElementRemove(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 result = std::move(*itr);
- // Clear parent
- result->parent = nullptr;
- result->SetOwnerDocument(nullptr);
- 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.
- Context* context = GetContext();
- if (context)
- {
- Element* focus_element = context->GetFocusElement();
- while (focus_element)
- {
- if (focus_element == child)
- {
- Focus();
- break;
- }
- focus_element = focus_element->GetParentNode();
- }
- }
- }
- DirtyLayout();
- DirtyStackingContext();
- DirtyStructure();
- return result;
- }
- 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 == NULL)
- 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 event_dispatcher;
- }
- String Element::GetEventDispatcherSummary() const
- {
- return event_dispatcher->ToString();
- }
- // Access the element background.
- ElementBackground* Element::GetElementBackground() const
- {
- return background;
- }
- // Access the element border.
- ElementBorder* Element::GetElementBorder() const
- {
- return border;
- }
- // Access the element decorators
- ElementDecoration* Element::GetElementDecoration() const
- {
- return decoration;
- }
- // Returns the element's scrollbar functionality.
- ElementScroll* Element::GetElementScroll() const
- {
- return 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()
- {
- Context* context = GetContext();
- if (context)
- return context->GetRenderInterface();
- return Rml::Core::GetRenderInterface();
- }
- void Element::SetInstancer(const ElementInstancerPtr& _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>();
- style->DirtyDefinition();
- }
- it = changed_attributes.find("class");
- if (it != changed_attributes.end())
- {
- 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)
- {
- style->SetProperty((*i).first, (*i).second);
- }
- }
- }
- // Called when properties on the element are changed.
- void Element::OnPropertyChange(const PropertyNameList& changed_properties)
- {
- bool all_dirty = false;
- {
- auto& registered_properties = StyleSheetSpecification::GetRegisteredProperties();
- if (®istered_properties == &changed_properties || registered_properties == changed_properties)
- all_dirty = true;
- }
- if (!IsLayoutDirty())
- {
- if (all_dirty)
- {
- DirtyLayout();
- }
- else
- {
- // Force a relayout if any of the changed properties require it.
- for (PropertyNameList::const_iterator i = changed_properties.begin(); i != changed_properties.end(); ++i)
- {
- const PropertyDefinition* property_definition = StyleSheetSpecification::GetProperty(*i);
- if (property_definition)
- {
- if (property_definition->IsLayoutForced())
- {
- DirtyLayout();
- break;
- }
- }
- }
- }
- }
- // Update the visibility.
- if (all_dirty || changed_properties.find(PropertyId::Visibility) != changed_properties.end() ||
- changed_properties.find(PropertyId::Display) != changed_properties.end())
- {
- bool new_visibility = (element_meta->computed_values.display != Style::Display::None && element_meta->computed_values.visibility == Style::Visibility::Visible);
-
- if (visible != new_visibility)
- {
- visible = new_visibility;
- if (parent != NULL)
- parent->DirtyStackingContext();
- }
- if (all_dirty ||
- changed_properties.find(PropertyId::Display) != changed_properties.end())
- {
- // 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 != NULL)
- parent->DirtyStructure();
- }
- }
- // Fetch a new font face if it has been changed.
- if (all_dirty ||
- changed_properties.find(PropertyId::FontFamily) != changed_properties.end() ||
- changed_properties.find(PropertyId::FontCharset) != changed_properties.end() ||
- changed_properties.find(PropertyId::FontWeight) != changed_properties.end() ||
- changed_properties.find(PropertyId::FontStyle) != changed_properties.end() ||
- changed_properties.find(PropertyId::FontSize) != changed_properties.end())
- {
- // Fetch the new font face.
- FontFaceHandle* new_font_face_handle = ElementUtilities::GetFontFaceHandle(element_meta->computed_values);
- // If this is different from our current font face, then we've got to nuke
- // all our characters and tell our parent that we have to be re-laid out.
- if (new_font_face_handle != font_face_handle)
- {
- if (font_face_handle)
- font_face_handle->RemoveReference();
- font_face_handle = new_font_face_handle;
- }
- else if (new_font_face_handle != NULL)
- new_font_face_handle->RemoveReference();
- }
- // Update the position.
- if (all_dirty ||
- changed_properties.find(PropertyId::Left) != changed_properties.end() ||
- changed_properties.find(PropertyId::Right) != changed_properties.end() ||
- changed_properties.find(PropertyId::Top) != changed_properties.end() ||
- changed_properties.find(PropertyId::Bottom) != changed_properties.end())
- {
- // 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 (all_dirty ||
- changed_properties.find(PropertyId::ZIndex) != changed_properties.end())
- {
- Style::ZIndex z_index_property = element_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 != NULL)
- parent->DirtyStackingContext();
- }
- if (!local_stacking_context)
- {
- local_stacking_context = true;
- stacking_context_dirty = true;
- }
- }
- }
- // Dirty the background if it's changed.
- if (all_dirty ||
- changed_properties.find(PropertyId::BackgroundColor) != changed_properties.end() ||
- changed_properties.find(PropertyId::Opacity) != changed_properties.end() ||
- changed_properties.find(PropertyId::ImageColor) != changed_properties.end()) {
- background->DirtyBackground();
- }
-
- // Dirty the decoration if it's changed.
- if (all_dirty ||
- changed_properties.find(PropertyId::Decorator) != changed_properties.end() ||
- changed_properties.find(PropertyId::Opacity) != changed_properties.end() ||
- changed_properties.find(PropertyId::ImageColor) != changed_properties.end()) {
- decoration->DirtyDecorators();
- }
- // Dirty the border if it's changed.
- if (all_dirty ||
- changed_properties.find(PropertyId::BorderTopWidth) != changed_properties.end() ||
- changed_properties.find(PropertyId::BorderRightWidth) != changed_properties.end() ||
- changed_properties.find(PropertyId::BorderBottomWidth) != changed_properties.end() ||
- changed_properties.find(PropertyId::BorderLeftWidth) != changed_properties.end() ||
- changed_properties.find(PropertyId::BorderTopColor) != changed_properties.end() ||
- changed_properties.find(PropertyId::BorderRightColor) != changed_properties.end() ||
- changed_properties.find(PropertyId::BorderBottomColor) != changed_properties.end() ||
- changed_properties.find(PropertyId::BorderLeftColor) != changed_properties.end() ||
- changed_properties.find(PropertyId::Opacity) != changed_properties.end())
- border->DirtyBorder();
-
- // Check for clipping state changes
- if (all_dirty ||
- changed_properties.find(PropertyId::Clip) != changed_properties.end() ||
- changed_properties.find(PropertyId::OverflowX) != changed_properties.end() ||
- changed_properties.find(PropertyId::OverflowY) != changed_properties.end())
- {
- clipping_state_dirty = true;
- }
- // Check for `perspective' and `perspective-origin' changes
- if (all_dirty ||
- changed_properties.find(PropertyId::Perspective) != changed_properties.end() ||
- changed_properties.find(PropertyId::PerspectiveOriginX) != changed_properties.end() ||
- changed_properties.find(PropertyId::PerspectiveOriginY) != changed_properties.end())
- {
- DirtyTransformState(true, false, false);
- }
- // Check for `transform' and `transform-origin' changes
- if (all_dirty ||
- changed_properties.find(PropertyId::Transform) != changed_properties.end() ||
- changed_properties.find(PropertyId::TransformOriginX) != changed_properties.end() ||
- changed_properties.find(PropertyId::TransformOriginY) != changed_properties.end() ||
- changed_properties.find(PropertyId::TransformOriginZ) != changed_properties.end())
- {
- DirtyTransformState(false, true, false);
- }
- // Check for `animation' changes
- if (all_dirty || changed_properties.find(PropertyId::Animation) != changed_properties.end())
- {
- dirty_animation = true;
- }
- // Check for `transition' changes
- if (all_dirty || changed_properties.find(PropertyId::Transition) != changed_properties.end())
- {
- 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 != NULL)
- document->DirtyLayout();
- }
- // Forces a re-layout of this element, and any other children required.
- bool Element::IsLayoutDirty()
- {
- Element* document = GetOwnerDocument();
- if (document != NULL)
- return document->IsLayoutDirty();
- return false;
- }
- // Forces a reevaluation of applicable font effects.
- void Element::DirtyFont()
- {
- for (size_t i = 0; i < children.size(); ++i)
- children[i]->DirtyFont();
- }
- 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 = element_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() + Math::RoundFloat(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 element_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. Otherwise, this can happen when attaching to the root element.
- if(owner_document != document && owner_document != this)
- {
- owner_document = document;
- for (ElementPtr& child : children)
- child->SetOwnerDocument(document);
- }
- }
- void Element::SetParent(Element* _parent)
- {
- // If there's an old parent, detach from it first.
- if (parent &&
- parent != _parent)
- parent->RemoveChild(this);
- parent = _parent;
- SetOwnerDocument(parent ? parent->GetOwnerDocument() : nullptr);
- }
- void Element::ReleaseElements()
- {
- //for (auto& element : deleted_children)
- //{
- // // Set the parent to NULL unless it's been reparented already.
- // if (element->GetParentNode() == this)
- // {
- // element->parent = nullptr;
- // element->SetOwnerDocument(nullptr);
- // }
- //}
-
- deleted_children.clear();
- // Todo: See if some of the old functionality is required after change to unique pointers:
- //// Remove deleted children from this element.
- //while (!deleted_children.empty())
- //{
- // ElementPtr element = std::move(deleted_children.back());
- // deleted_children.pop_back();
- // // If this element has been added back into our list, then we remove our previous oustanding reference on it
- // // and continue.
- // if (std::find(children.begin(), children.end(), element) != children.end())
- // {
- // element->RemoveReference();
- // continue;
- // }
- // // Set the parent to NULL unless it's been reparented already.
- // if (element->GetParentNode() == this)
- // {
- // element->parent = nullptr;
- // element->SetOwnerDocument(nullptr);
- // }
- // element->RemoveReference();
- //}
- }
- void Element::DirtyOffset()
- {
- if(!offset_dirty)
- {
- offset_dirty = true;
- if(transform_state)
- DirtyTransformState(true, true, false);
- // Not strictly true ... ?
- for (size_t i = 0; i < children.size(); i++)
- children[i]->DirtyOffset();
- }
- }
- void Element::UpdateOffset()
- {
- using namespace Style;
- const auto& computed = element_meta->computed_values;
- Position position_property = computed.position;
- if (position_property == Position::Absolute ||
- position_property == Position::Fixed)
- {
- if (offset_parent != NULL)
- {
- 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 != NULL)
- {
- 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)
- {
- // 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 != NULL &&
- !stacking_context_parent->local_stacking_context)
- stacking_context_parent = stacking_context_parent->GetParentNode();
- if (stacking_context_parent != NULL)
- 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 origin_is_animation_property)
- {
- auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == property_id; });
- if (it == animations.end())
- {
- 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 = (origin_is_animation_property ? ElementAnimationOrigin::Animation : ElementAnimationOrigin::User);
- double start_time = Clock::GetElapsedTime() + (double)delay;
- *it = ElementAnimation{ property_id, origin, value, start_time, 0.0f, num_iterations, alternate_direction };
- }
- else
- {
- 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 = 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, 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, 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::UpdateTransition()
- {
- 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 ended animations here, just removing them seems to be the CSS approach.
- for (auto it = it_remove; it != animations.end(); ++it)
- RemoveProperty(it->GetPropertyId());
- animations.erase(it_remove, animations.end());
- }
- }
- void Element::UpdateAnimation()
- {
- if (dirty_animation)
- {
- dirty_animation = false;
- const AnimationList& animation_list = element_meta->computed_values.animation;
- bool element_has_animations = (!animation_list.empty() || !animations.empty());
- StyleSheet* stylesheet = nullptr;
- if (element_has_animations && (stylesheet = GetStyleSheet()))
- {
- // Remove existing animations
- // Note: We are effectively restarting all animations whenever 'drty_animation' is set. Use the dirty flag with care,
- // or find another approach which only updates actual "dirty" 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 ended animations here, should be consistent with removal of transitions.
- 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);
- // 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)
- {
- dictionary_list.emplace_back();
- dictionary_list.back().emplace("property", StyleSheetSpecification::GetPropertyName(it->GetPropertyId()));
- is_transition.push_back(it->IsTransition());
- }
- // 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_changed, bool transform_changed, bool parent_transform_changed)
- {
- for (size_t i = 0; i < children.size(); ++i)
- {
- children[i]->DirtyTransformState(false, false, transform_changed || parent_transform_changed);
- }
- if (perspective_changed)
- {
- this->transform_state_perspective_dirty = true;
- }
- if (transform_changed)
- {
- this->transform_state_transform_dirty = true;
- }
- if (parent_transform_changed)
- {
- this->transform_state_parent_transform_dirty = true;
- }
- }
- void Element::UpdateTransformState()
- {
- if (!(transform_state_perspective_dirty || transform_state_transform_dirty || transform_state_parent_transform_dirty))
- {
- return;
- }
- const ComputedValues& computed = element_meta->computed_values;
- if (!computed.transform && computed.perspective <= 0)
- {
- transform_state.reset();
- transform_state_perspective_dirty = false;
- transform_state_transform_dirty = false;
- transform_state_parent_transform_dirty = false;
- return;
- }
- if(transform_state_perspective_dirty || transform_state_transform_dirty)
- {
- Context *context = GetContext();
- Vector2f pos = GetAbsoluteOffset(Box::BORDER);
- Vector2f size = GetBox().GetSize(Box::BORDER);
- if (transform_state_perspective_dirty)
- {
- bool have_perspective = false;
- TransformState::Perspective perspective_value;
- perspective_value.vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
- if (computed.perspective > 0.0f)
- {
- have_perspective = true;
- // Compute the perspective value
- perspective_value.distance = computed.perspective;
- // Compute the perspective origin, if necessary
- if (computed.perspective_origin_x.type == Style::PerspectiveOrigin::Percentage)
- perspective_value.vanish.x = pos.x + computed.perspective_origin_x.value * 0.01f * size.x;
- else
- perspective_value.vanish.x = pos.x + computed.perspective_origin_x.value;
- if (computed.perspective_origin_y.type == Style::PerspectiveOrigin::Percentage)
- perspective_value.vanish.y = pos.y + computed.perspective_origin_y.value * 0.01f * size.y;
- else
- perspective_value.vanish.y = pos.y + computed.perspective_origin_y.value;
- }
- if (have_perspective && context)
- {
- if (!transform_state)
- transform_state.reset(new TransformState);
- perspective_value.view_size = context->GetDimensions();
- transform_state->SetPerspective(&perspective_value);
- }
- else if (transform_state)
- {
- transform_state->SetPerspective(nullptr);
- }
- transform_state_perspective_dirty = false;
- }
- if (transform_state_transform_dirty)
- {
- bool have_local_perspective = false;
- TransformState::LocalPerspective local_perspective;
- bool have_transform = false;
- Matrix4f transform_value = Matrix4f::Identity();
- Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
- if (computed.transform)
- {
- int n = computed.transform->GetNumPrimitives();
- for (int i = 0; i < n; ++i)
- {
- const Transforms::Primitive &primitive = computed.transform->GetPrimitive(i);
- if (primitive.ResolvePerspective(local_perspective.distance, *this))
- {
- have_local_perspective = true;
- }
- Matrix4f matrix;
- if (primitive.ResolveTransform(matrix, *this))
- {
- transform_value *= matrix;
- have_transform = true;
- }
- }
- // Compute the transform origin
- 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;
- }
- if (have_local_perspective && context)
- {
- if (!transform_state)
- transform_state.reset(new TransformState);
- local_perspective.view_size = context->GetDimensions();
- transform_state->SetLocalPerspective(&local_perspective);
- }
- else if(transform_state)
- {
- transform_state->SetLocalPerspective(nullptr);
- }
- if (have_transform)
- {
- // TODO: If we're using the global projection matrix
- // (perspective < 0), then scale the coordinates from
- // pixel space to 3D unit space.
- // Transform the RmlUi context so that the computed `transform_origin'
- // lies at the coordinate system origin.
- transform_value =
- Matrix4f::Translate(transform_origin)
- * transform_value
- * Matrix4f::Translate(-transform_origin);
- if (!transform_state)
- transform_state.reset(new TransformState);
- transform_state->SetTransform(&transform_value);
- }
- else if (transform_state)
- {
- transform_state->SetTransform(nullptr);
- }
- transform_state_transform_dirty = false;
- }
- }
- if (transform_state_parent_transform_dirty)
- {
- // We need to clean up from the top-most to the bottom-most dirt.
- if (parent)
- {
- parent->UpdateTransformState();
- }
- if (transform_state)
- {
- // Store the parent's new full transform as our parent transform
- Element *node = nullptr;
- Matrix4f parent_transform;
- for (node = parent; node; node = node->parent)
- {
- if (node->GetTransformState() && node->GetTransformState()->GetRecursiveTransform(&parent_transform))
- {
- transform_state->SetParentRecursiveTransform(&parent_transform);
- break;
- }
- }
- if (!node)
- {
- transform_state->SetParentRecursiveTransform(nullptr);
- }
- }
- transform_state_parent_transform_dirty = false;
- }
- // If we neither have a local perspective, nor a perspective nor a
- // transform, we don't need to keep the large TransformState object
- // around. GetEffectiveTransformState() will then recursively visit
- // parents in order to find a non-trivial TransformState.
- if (transform_state && !transform_state->GetLocalPerspective(nullptr) && !transform_state->GetPerspective(nullptr) && !transform_state->GetTransform(nullptr))
- {
- transform_state.reset();
- }
- }
- void ElementDeleter::operator()(Element* element) const
- {
- ElementInstancerPtr& instancer = element->instancer;
- if (instancer)
- instancer->ReleaseElement(element);
- else
- Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via RmlUi Factory. Unable to release.", element->GetAddress().c_str());
- };
- }
- }
|