| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123 |
- //
- // Copyright (c) 2008-2017 the Urho3D project.
- //
- // 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 "../Core/Context.h"
- #include "../Core/CoreEvents.h"
- #include "../Core/Profiler.h"
- #include "../Container/Sort.h"
- #include "../Graphics/Graphics.h"
- #include "../Graphics/GraphicsEvents.h"
- #include "../Graphics/Shader.h"
- #include "../Graphics/ShaderVariation.h"
- #include "../Graphics/Texture2D.h"
- #include "../Graphics/VertexBuffer.h"
- #include "../Graphics/Octree.h"
- #include "../Graphics/Viewport.h"
- #include "../Graphics/Camera.h"
- #include "../Scene/Scene.h"
- #include "../Input/Input.h"
- #include "../Input/InputEvents.h"
- #include "../IO/Log.h"
- #include "../Math/Matrix3x4.h"
- #include "../Resource/ResourceCache.h"
- #include "../UI/CheckBox.h"
- #include "../UI/Cursor.h"
- #include "../UI/DropDownList.h"
- #include "../UI/FileSelector.h"
- #include "../UI/Font.h"
- #include "../UI/LineEdit.h"
- #include "../UI/ListView.h"
- #include "../UI/MessageBox.h"
- #include "../UI/ProgressBar.h"
- #include "../UI/ScrollBar.h"
- #include "../UI/Slider.h"
- #include "../UI/Sprite.h"
- #include "../UI/Text.h"
- #include "../UI/Text3D.h"
- #include "../UI/ToolTip.h"
- #include "../UI/UI.h"
- #include "../UI/UIEvents.h"
- #include "../UI/Window.h"
- #include "../UI/View3D.h"
- #include "../UI/UIComponent.h"
- #include <assert.h>
- #include <SDL/SDL.h>
- #include "../DebugNew.h"
- #define TOUCHID_MASK(id) (1 << id)
- namespace Urho3D
- {
- StringHash VAR_ORIGIN("Origin");
- const StringHash VAR_ORIGINAL_PARENT("OriginalParent");
- const StringHash VAR_ORIGINAL_CHILD_INDEX("OriginalChildIndex");
- const StringHash VAR_PARENT_CHANGED("ParentChanged");
- const float DEFAULT_DOUBLECLICK_INTERVAL = 0.5f;
- const float DEFAULT_DRAGBEGIN_INTERVAL = 0.5f;
- const float DEFAULT_TOOLTIP_DELAY = 0.5f;
- const int DEFAULT_DRAGBEGIN_DISTANCE = 5;
- const int DEFAULT_FONT_TEXTURE_MAX_SIZE = 2048;
- const char* UI_CATEGORY = "UI";
- UI::UI(Context* context) :
- Object(context),
- rootElement_(new UIElement(context)),
- rootModalElement_(new UIElement(context)),
- doubleClickInterval_(DEFAULT_DOUBLECLICK_INTERVAL),
- dragBeginInterval_(DEFAULT_DRAGBEGIN_INTERVAL),
- defaultToolTipDelay_(DEFAULT_TOOLTIP_DELAY),
- dragBeginDistance_(DEFAULT_DRAGBEGIN_DISTANCE),
- mouseButtons_(0),
- lastMouseButtons_(0),
- qualifiers_(0),
- maxFontTextureSize_(DEFAULT_FONT_TEXTURE_MAX_SIZE),
- initialized_(false),
- usingTouchInput_(false),
- #ifdef _WIN32
- nonFocusedMouseWheel_(false), // Default MS Windows behaviour
- #else
- nonFocusedMouseWheel_(true), // Default Mac OS X and Linux behaviour
- #endif
- useSystemClipboard_(false),
- #if defined(__ANDROID__) || defined(IOS) || defined(TVOS)
- useScreenKeyboard_(true),
- #else
- useScreenKeyboard_(false),
- #endif
- useMutableGlyphs_(false),
- forceAutoHint_(false),
- fontHintLevel_(FONT_HINT_LEVEL_NORMAL),
- fontSubpixelThreshold_(12),
- fontOversampling_(2),
- uiRendered_(false),
- nonModalBatchSize_(0),
- dragElementsCount_(0),
- dragConfirmedCount_(0),
- uiScale_(1.0f),
- customSize_(IntVector2::ZERO)
- {
- rootElement_->SetTraversalMode(TM_DEPTH_FIRST);
- rootModalElement_->SetTraversalMode(TM_DEPTH_FIRST);
- // Register UI library object factories
- RegisterUILibrary(context_);
- SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(UI, HandleScreenMode));
- SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(UI, HandleMouseButtonDown));
- SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(UI, HandleMouseButtonUp));
- SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(UI, HandleMouseMove));
- SubscribeToEvent(E_MOUSEWHEEL, URHO3D_HANDLER(UI, HandleMouseWheel));
- SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(UI, HandleTouchBegin));
- SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(UI, HandleTouchEnd));
- SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(UI, HandleTouchMove));
- SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(UI, HandleKeyDown));
- SubscribeToEvent(E_TEXTINPUT, URHO3D_HANDLER(UI, HandleTextInput));
- SubscribeToEvent(E_DROPFILE, URHO3D_HANDLER(UI, HandleDropFile));
- // Try to initialize right now, but skip if screen mode is not yet set
- Initialize();
- }
- UI::~UI()
- {
- }
- void UI::SetCursor(Cursor* cursor)
- {
- // Remove old cursor (if any) and set new
- if (cursor_)
- {
- rootElement_->RemoveChild(cursor_);
- cursor_.Reset();
- }
- if (cursor)
- {
- rootElement_->AddChild(cursor);
- cursor_ = cursor;
- IntVector2 pos = cursor_->GetPosition();
- const IntVector2& rootSize = rootElement_->GetSize();
- const IntVector2& rootPos = rootElement_->GetPosition();
- pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
- pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
- cursor_->SetPosition(pos);
- }
- }
- void UI::SetFocusElement(UIElement* element, bool byKey)
- {
- using namespace FocusChanged;
- UIElement* originalElement = element;
- if (element)
- {
- // Return if already has focus
- if (focusElement_ == element)
- return;
- // Only allow child elements of the modal element to receive focus
- if (HasModalElement())
- {
- UIElement* topLevel = element->GetParent();
- while (topLevel && topLevel->GetParent() != rootElement_)
- topLevel = topLevel->GetParent();
- if (topLevel) // If parented to non-modal root then ignore
- return;
- }
- // Search for an element in the hierarchy that can alter focus. If none found, exit
- element = GetFocusableElement(element);
- if (!element)
- return;
- }
- // Remove focus from the old element
- if (focusElement_)
- {
- UIElement* oldFocusElement = focusElement_;
- focusElement_.Reset();
- VariantMap& focusEventData = GetEventDataMap();
- focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
- oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
- }
- // Then set focus to the new
- if (element && element->GetFocusMode() >= FM_FOCUSABLE)
- {
- focusElement_ = element;
- VariantMap& focusEventData = GetEventDataMap();
- focusEventData[Focused::P_ELEMENT] = element;
- focusEventData[Focused::P_BYKEY] = byKey;
- element->SendEvent(E_FOCUSED, focusEventData);
- }
- VariantMap& eventData = GetEventDataMap();
- eventData[P_CLICKEDELEMENT] = originalElement;
- eventData[P_ELEMENT] = element;
- SendEvent(E_FOCUSCHANGED, eventData);
- }
- bool UI::SetModalElement(UIElement* modalElement, bool enable)
- {
- if (!modalElement)
- return false;
- // Currently only allow modal window
- if (modalElement->GetType() != Window::GetTypeStatic())
- return false;
- assert(rootModalElement_);
- UIElement* currParent = modalElement->GetParent();
- if (enable)
- {
- // Make sure it is not already the child of the root modal element
- if (currParent == rootModalElement_)
- return false;
- // Adopt modal root as parent
- modalElement->SetVar(VAR_ORIGINAL_PARENT, currParent);
- modalElement->SetVar(VAR_ORIGINAL_CHILD_INDEX, currParent ? currParent->FindChild(modalElement) : M_MAX_UNSIGNED);
- modalElement->SetParent(rootModalElement_);
- // If it is a popup element, bring along its top-level parent
- UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
- if (originElement)
- {
- UIElement* element = originElement;
- while (element && element->GetParent() != rootElement_)
- element = element->GetParent();
- if (element)
- {
- originElement->SetVar(VAR_PARENT_CHANGED, element);
- UIElement* oriParent = element->GetParent();
- element->SetVar(VAR_ORIGINAL_PARENT, oriParent);
- element->SetVar(VAR_ORIGINAL_CHILD_INDEX, oriParent ? oriParent->FindChild(element) : M_MAX_UNSIGNED);
- element->SetParent(rootModalElement_);
- }
- }
- return true;
- }
- else
- {
- // Only the modal element can disable itself
- if (currParent != rootModalElement_)
- return false;
- // Revert back to original parent
- modalElement->SetParent(static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
- modalElement->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
- VariantMap& vars = const_cast<VariantMap&>(modalElement->GetVars());
- vars.Erase(VAR_ORIGINAL_PARENT);
- vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
- // If it is a popup element, revert back its top-level parent
- UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
- if (originElement)
- {
- UIElement* element = static_cast<UIElement*>(originElement->GetVar(VAR_PARENT_CHANGED).GetPtr());
- if (element)
- {
- const_cast<VariantMap&>(originElement->GetVars()).Erase(VAR_PARENT_CHANGED);
- element->SetParent(static_cast<UIElement*>(element->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
- element->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
- vars = const_cast<VariantMap&>(element->GetVars());
- vars.Erase(VAR_ORIGINAL_PARENT);
- vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
- }
- }
- return true;
- }
- }
- void UI::Clear()
- {
- rootElement_->RemoveAllChildren();
- rootModalElement_->RemoveAllChildren();
- if (cursor_)
- rootElement_->AddChild(cursor_);
- }
- void UI::Update(float timeStep)
- {
- assert(rootElement_ && rootModalElement_);
- URHO3D_PROFILE(UpdateUI);
- // Expire hovers
- for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End(); ++i)
- i->second_ = false;
- Input* input = GetSubsystem<Input>();
- bool mouseGrabbed = input->IsMouseGrabbed();
- IntVector2 cursorPos;
- bool cursorVisible;
- GetCursorPositionAndVisible(cursorPos, cursorVisible);
- // Drag begin based on time
- if (dragElementsCount_ > 0 && !mouseGrabbed)
- {
- for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
- {
- WeakPtr<UIElement> dragElement = i->first_;
- UI::DragData* dragData = i->second_;
- if (!dragElement)
- {
- i = DragElementErase(i);
- continue;
- }
- if (!dragData->dragBeginPending)
- {
- ++i;
- continue;
- }
- if (dragData->dragBeginTimer.GetMSec(false) >= (unsigned)(dragBeginInterval_ * 1000))
- {
- dragData->dragBeginPending = false;
- IntVector2 beginSendPos = dragData->dragBeginSumPos / dragData->numDragButtons;
- dragConfirmedCount_++;
- if (!usingTouchInput_)
- dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons,
- qualifiers_, cursor_);
- else
- dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons, 0, nullptr);
- SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
- }
- ++i;
- }
- }
- // Mouse hover
- if (!mouseGrabbed && !input->GetTouchEmulation())
- {
- if (!usingTouchInput_ && cursorVisible)
- ProcessHover(cursorPos, mouseButtons_, qualifiers_, cursor_);
- }
- // Touch hover
- unsigned numTouches = input->GetNumTouches();
- for (unsigned i = 0; i < numTouches; ++i)
- {
- TouchState* touch = input->GetTouch(i);
- IntVector2 touchPos = touch->position_;
- touchPos.x_ = (int)(touchPos.x_ / uiScale_);
- touchPos.y_ = (int)(touchPos.y_ / uiScale_);
- ProcessHover(touchPos, TOUCHID_MASK(touch->touchID_), 0, nullptr);
- }
- // End hovers that expired without refreshing
- for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End();)
- {
- if (i->first_.Expired() || !i->second_)
- {
- UIElement* element = i->first_;
- if (element)
- {
- using namespace HoverEnd;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_ELEMENT] = element;
- element->SendEvent(E_HOVEREND, eventData);
- }
- i = hoveredElements_.Erase(i);
- }
- else
- ++i;
- }
- Update(timeStep, rootElement_);
- Update(timeStep, rootModalElement_);
- }
- void UI::RenderUpdate()
- {
- assert(rootElement_ && rootModalElement_ && graphics_);
- URHO3D_PROFILE(GetUIBatches);
- uiRendered_ = false;
- // If the OS cursor is visible, do not render the UI's own cursor
- bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
- // Get rendering batches from the non-modal UI elements
- batches_.Clear();
- vertexData_.Clear();
- const IntVector2& rootSize = rootElement_->GetSize();
- const IntVector2& rootPos = rootElement_->GetPosition();
- // Note: the scissors operate on unscaled coordinates. Scissor scaling is only performed during render
- IntRect currentScissor = IntRect(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_);
- if (rootElement_->IsVisible())
- GetBatches(batches_, vertexData_, rootElement_, currentScissor);
- // Save the batch size of the non-modal batches for later use
- nonModalBatchSize_ = batches_.Size();
- // Get rendering batches from the modal UI elements
- GetBatches(batches_, vertexData_, rootModalElement_, currentScissor);
- // Get batches from the cursor (and its possible children) last to draw it on top of everything
- if (cursor_ && cursor_->IsVisible() && !osCursorVisible)
- {
- currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
- cursor_->GetBatches(batches_, vertexData_, currentScissor);
- GetBatches(batches_, vertexData_, cursor_, currentScissor);
- }
- // Get batches for UI elements rendered into textures. Each element rendered into texture is treated as root element.
- for (Vector<WeakPtr<UIComponent> >::Iterator it = renderToTexture_.Begin(); it != renderToTexture_.End();)
- {
- WeakPtr<UIComponent> component = *it;
- if (component.Null() || !component->IsEnabled())
- it = renderToTexture_.Erase(it);
- else if (component->IsEnabled())
- {
- component->batches_.Clear();
- component->vertexData_.Clear();
- UIElement* element = component->GetRoot();
- const IntVector2& size = element->GetSize();
- const IntVector2& pos = element->GetPosition();
- // Note: the scissors operate on unscaled coordinates. Scissor scaling is only performed during render
- IntRect scissor = IntRect(pos.x_, pos.y_, pos.x_ + size.x_, pos.y_ + size.y_);
- GetBatches(component->batches_, component->vertexData_, element, scissor);
- // UIElement does not have anything to show. Insert dummy batch that will clear the texture.
- if (component->batches_.Empty())
- {
- UIBatch batch(element, BLEND_REPLACE, scissor, nullptr, &component->vertexData_);
- batch.SetColor(Color::BLACK);
- batch.AddQuad(scissor.left_, scissor.top_, scissor.right_, scissor.bottom_, 0, 0);
- component->batches_.Push(batch);
- }
- ++it;
- }
- }
- }
- void UI::Render(bool renderUICommand)
- {
- URHO3D_PROFILE(RenderUI);
- // If the OS cursor is visible, apply its shape now if changed
- if (!renderUICommand)
- {
- bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
- if (cursor_ && osCursorVisible)
- cursor_->ApplyOSCursorShape();
- }
- // Perform the default backbuffer render only if not rendered yet, or additional renders through RenderUI command
- if (renderUICommand || !uiRendered_)
- {
- SetVertexData(vertexBuffer_, vertexData_);
- SetVertexData(debugVertexBuffer_, debugVertexData_);
- if (!renderUICommand)
- graphics_->ResetRenderTargets();
- // Render non-modal batches
- Render(vertexBuffer_, batches_, 0, nonModalBatchSize_);
- // Render debug draw
- Render(debugVertexBuffer_, debugDrawBatches_, 0, debugDrawBatches_.Size());
- // Render modal batches
- Render(vertexBuffer_, batches_, nonModalBatchSize_, batches_.Size());
- }
-
- // Render to UIComponent textures. This is skipped when called from the RENDERUI command
- if (!renderUICommand)
- {
- for (Vector<WeakPtr<UIComponent> >::ConstIterator it = renderToTexture_.Begin(); it != renderToTexture_.End(); it++)
- {
- WeakPtr<UIComponent> component = *it;
- if (component->IsEnabled())
- {
- SetVertexData(component->vertexBuffer_, component->vertexData_);
- SetVertexData(component->debugVertexBuffer_, component->debugVertexData_);
-
- RenderSurface* surface = component->GetTexture()->GetRenderSurface();
- graphics_->SetRenderTarget(0, surface);
- graphics_->SetViewport(IntRect(0, 0, surface->GetWidth(), surface->GetHeight()));
- graphics_->Clear(Urho3D::CLEAR_COLOR);
- Render(component->vertexBuffer_, component->batches_, 0, component->batches_.Size());
- Render(component->debugVertexBuffer_, component->debugDrawBatches_, 0, component->debugDrawBatches_.Size());
- component->debugDrawBatches_.Clear();
- component->debugVertexData_.Clear();
- }
- }
- if (renderToTexture_.Size())
- graphics_->ResetRenderTargets();
- }
- // Clear the debug draw batches and data
- debugDrawBatches_.Clear();
- debugVertexData_.Clear();
- uiRendered_ = true;
- }
- void UI::DebugDraw(UIElement* element)
- {
- if (element)
- {
- UIElement* root = element->GetRoot();
- if (!root)
- root = element;
- const IntVector2& rootSize = root->GetSize();
- const IntVector2& rootPos = root->GetPosition();
- IntRect scissor(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_);
- if (root == rootElement_ || root == rootModalElement_)
- element->GetDebugDrawBatches(debugDrawBatches_, debugVertexData_, scissor);
- else
- {
- for (Vector<WeakPtr<UIComponent> >::Iterator it = renderToTexture_.Begin(); it != renderToTexture_.End(); it++)
- {
- WeakPtr<UIComponent> component = *it;
- if (component.NotNull() && component->GetRoot() == root && component->IsEnabled())
- {
- element->GetDebugDrawBatches(component->debugDrawBatches_, component->debugVertexData_, scissor);
- break;
- }
- }
- }
- }
- }
- SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
- {
- SharedPtr<XMLFile> xml(new XMLFile(context_));
- if (!xml->Load(source))
- return SharedPtr<UIElement>();
- else
- return LoadLayout(xml, styleFile);
- }
- SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
- {
- URHO3D_PROFILE(LoadUILayout);
- SharedPtr<UIElement> root;
- if (!file)
- {
- URHO3D_LOGERROR("Null UI layout XML file");
- return root;
- }
- URHO3D_LOGDEBUG("Loading UI layout " + file->GetName());
- XMLElement rootElem = file->GetRoot("element");
- if (!rootElem)
- {
- URHO3D_LOGERROR("No root UI element in " + file->GetName());
- return root;
- }
- String typeName = rootElem.GetAttribute("type");
- if (typeName.Empty())
- typeName = "UIElement";
- root = DynamicCast<UIElement>(context_->CreateObject(typeName));
- if (!root)
- {
- URHO3D_LOGERROR("Could not create unknown UI element " + typeName);
- return root;
- }
- // Use default style file of the root element if it has one
- if (!styleFile)
- styleFile = rootElement_->GetDefaultStyle(false);
- // Set it as default for later use by children elements
- if (styleFile)
- root->SetDefaultStyle(styleFile);
- root->LoadXML(rootElem, styleFile);
- return root;
- }
- bool UI::SaveLayout(Serializer& dest, UIElement* element)
- {
- URHO3D_PROFILE(SaveUILayout);
- return element && element->SaveXML(dest);
- }
- void UI::SetClipboardText(const String& text)
- {
- clipBoard_ = text;
- if (useSystemClipboard_)
- SDL_SetClipboardText(text.CString());
- }
- void UI::SetDoubleClickInterval(float interval)
- {
- doubleClickInterval_ = Max(interval, 0.0f);
- }
- void UI::SetDragBeginInterval(float interval)
- {
- dragBeginInterval_ = Max(interval, 0.0f);
- }
- void UI::SetDragBeginDistance(int pixels)
- {
- dragBeginDistance_ = Max(pixels, 0);
- }
- void UI::SetDefaultToolTipDelay(float delay)
- {
- defaultToolTipDelay_ = Max(delay, 0.0f);
- }
- void UI::SetMaxFontTextureSize(int size)
- {
- if (IsPowerOfTwo((unsigned)size) && size >= FONT_TEXTURE_MIN_SIZE)
- {
- if (size != maxFontTextureSize_)
- {
- maxFontTextureSize_ = size;
- ReleaseFontFaces();
- }
- }
- }
- void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
- {
- nonFocusedMouseWheel_ = nonFocusedMouseWheel;
- }
- void UI::SetUseSystemClipboard(bool enable)
- {
- useSystemClipboard_ = enable;
- }
- void UI::SetUseScreenKeyboard(bool enable)
- {
- useScreenKeyboard_ = enable;
- }
- void UI::SetUseMutableGlyphs(bool enable)
- {
- if (enable != useMutableGlyphs_)
- {
- useMutableGlyphs_ = enable;
- ReleaseFontFaces();
- }
- }
- void UI::SetForceAutoHint(bool enable)
- {
- if (enable != forceAutoHint_)
- {
- forceAutoHint_ = enable;
- ReleaseFontFaces();
- }
- }
- void UI::SetFontHintLevel(FontHintLevel level)
- {
- if (level != fontHintLevel_)
- {
- fontHintLevel_ = level;
- ReleaseFontFaces();
- }
- }
- void UI::SetFontSubpixelThreshold(float threshold)
- {
- assert(threshold >= 0);
- if (threshold != fontSubpixelThreshold_)
- {
- fontSubpixelThreshold_ = threshold;
- ReleaseFontFaces();
- }
- }
- void UI::SetFontOversampling(int oversampling)
- {
- assert(oversampling >= 1);
- oversampling = Clamp(oversampling, 1, 8);
- if (oversampling != fontOversampling_)
- {
- fontOversampling_ = oversampling;
- ReleaseFontFaces();
- }
- }
- void UI::SetScale(float scale)
- {
- uiScale_ = Max(scale, M_EPSILON);
- ResizeRootElement();
- }
- void UI::SetWidth(float width)
- {
- IntVector2 size = GetEffectiveRootElementSize(false);
- SetScale((float)size.x_ / width);
- }
- void UI::SetHeight(float height)
- {
- IntVector2 size = GetEffectiveRootElementSize(false);
- SetScale((float)size.y_ / height);
- }
- void UI::SetCustomSize(const IntVector2& size)
- {
- customSize_ = IntVector2(Max(0, size.x_), Max(0, size.y_));
- ResizeRootElement();
- }
- void UI::SetCustomSize(int width, int height)
- {
- customSize_ = IntVector2(Max(0, width), Max(0, height));
- ResizeRootElement();
- }
- IntVector2 UI::GetCursorPosition() const
- {
- return cursor_ ? cursor_->GetPosition() : GetSubsystem<Input>()->GetMousePosition();
- }
- UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly, IntVector2* elementScreenPosition)
- {
- UIElement* result = nullptr;
- if (HasModalElement())
- result = GetElementAt(rootModalElement_, position, enabledOnly);
- if (!result)
- result = GetElementAt(rootElement_, position, enabledOnly);
- // Mouse was not hovering UI element. Check elements rendered on 3D objects.
- if (!result && renderToTexture_.Size())
- {
- for (Vector<WeakPtr<UIComponent> >::Iterator it = renderToTexture_.Begin(); it != renderToTexture_.End(); it++)
- {
- WeakPtr<UIComponent> component = *it;
- if (component.Null() || !component->IsEnabled())
- continue;
- IntVector2 screenPosition;
- if (component->ScreenToUIPosition(position, screenPosition))
- {
- result = GetElementAt(component->GetRoot(), screenPosition, enabledOnly);
- if (result)
- {
- if (elementScreenPosition)
- *elementScreenPosition = screenPosition;
- break;
- }
- }
- }
- }
- else if (elementScreenPosition)
- *elementScreenPosition = position;
- return result;
- }
- UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly)
- {
- return GetElementAt(position, enabledOnly, nullptr);
- }
- UIElement* UI::GetElementAt(UIElement* root, const IntVector2& position, bool enabledOnly)
- {
- IntVector2 positionCopy(position);
- const IntVector2& rootSize = root->GetSize();
- const IntVector2& rootPos = root->GetPosition();
- // If position is out of bounds of root element return null.
- if (position.x_ < rootPos.x_ || position.x_ > rootPos.x_ + rootSize.x_)
- return nullptr;
- if (position.y_ < rootPos.y_ || position.y_ > rootPos.y_ + rootSize.y_)
- return nullptr;
- // If UI is smaller than the screen, wrap if necessary
- if (rootSize.x_ > 0 && rootSize.y_ > 0)
- {
- if (positionCopy.x_ >= rootPos.x_ + rootSize.x_)
- positionCopy.x_ = rootPos.x_ + ((positionCopy.x_ - rootPos.x_) % rootSize.x_);
- if (positionCopy.y_ >= rootPos.y_ + rootSize.y_)
- positionCopy.y_ = rootPos.y_ + ((positionCopy.y_ - rootPos.y_) % rootSize.y_);
- }
- UIElement* result = nullptr;
- GetElementAt(result, root, positionCopy, enabledOnly);
- return result;
- }
- UIElement* UI::GetElementAt(int x, int y, bool enabledOnly)
- {
- return GetElementAt(IntVector2(x, y), enabledOnly);
- }
- UIElement* UI::GetFrontElement() const
- {
- const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
- int maxPriority = M_MIN_INT;
- UIElement* front = nullptr;
- for (unsigned i = 0; i < rootChildren.Size(); ++i)
- {
- // Do not take into account input-disabled elements, hidden elements or those that are always in the front
- if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
- continue;
- int priority = rootChildren[i]->GetPriority();
- if (priority > maxPriority)
- {
- maxPriority = priority;
- front = rootChildren[i];
- }
- }
- return front;
- }
- const Vector<UIElement*> UI::GetDragElements()
- {
- // Do not return the element until drag begin event has actually been posted
- if (!dragElementsConfirmed_.Empty())
- return dragElementsConfirmed_;
- for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
- {
- WeakPtr<UIElement> dragElement = i->first_;
- UI::DragData* dragData = i->second_;
- if (!dragElement)
- {
- i = DragElementErase(i);
- continue;
- }
- if (!dragData->dragBeginPending)
- dragElementsConfirmed_.Push(dragElement);
- ++i;
- }
- return dragElementsConfirmed_;
- }
- UIElement* UI::GetDragElement(unsigned index)
- {
- GetDragElements();
- if (index >= dragElementsConfirmed_.Size())
- return nullptr;
- return dragElementsConfirmed_[index];
- }
- const String& UI::GetClipboardText() const
- {
- if (useSystemClipboard_)
- {
- char* text = SDL_GetClipboardText();
- clipBoard_ = String(text);
- if (text)
- SDL_free(text);
- }
- return clipBoard_;
- }
- bool UI::HasModalElement() const
- {
- return rootModalElement_->GetNumChildren() > 0;
- }
- void UI::Initialize()
- {
- Graphics* graphics = GetSubsystem<Graphics>();
- if (!graphics || !graphics->IsInitialized())
- return;
- URHO3D_PROFILE(InitUI);
- graphics_ = graphics;
- UIBatch::posAdjust = Vector3(Graphics::GetPixelUVOffset(), 0.0f);
- // Set initial root element size
- ResizeRootElement();
- vertexBuffer_ = new VertexBuffer(context_);
- debugVertexBuffer_ = new VertexBuffer(context_);
- initialized_ = true;
- SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(UI, HandleBeginFrame));
- SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UI, HandlePostUpdate));
- SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(UI, HandleRenderUpdate));
- URHO3D_LOGINFO("Initialized user interface");
- }
- void UI::Update(float timeStep, UIElement* element)
- {
- // Keep a weak pointer to the element in case it destroys itself on update
- WeakPtr<UIElement> elementWeak(element);
- element->Update(timeStep);
- if (elementWeak.Expired())
- return;
- const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
- // Update of an element may modify its child vector. Use just index-based iteration to be safe
- for (unsigned i = 0; i < children.Size(); ++i)
- Update(timeStep, children[i]);
- }
- void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
- {
- if (vertexData.Empty())
- return;
- // Update quad geometry into the vertex buffer
- // Resize the vertex buffer first if too small or much too large
- unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
- if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
- dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
- dest->SetData(&vertexData[0]);
- }
- void UI::Render(VertexBuffer* buffer, const PODVector<UIBatch>& batches, unsigned batchStart, unsigned batchEnd)
- {
- // Engine does not render when window is closed or device is lost
- assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
- if (batches.Empty())
- return;
- unsigned alphaFormat = Graphics::GetAlphaFormat();
- RenderSurface* surface = graphics_->GetRenderTarget(0);
- IntVector2 viewSize = graphics_->GetViewport().Size();
- Vector2 invScreenSize(1.0f / (float)viewSize.x_, 1.0f / (float)viewSize.y_);
- Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
- Vector2 offset(-1.0f, 1.0f);
- if (surface)
- {
- #ifdef URHO3D_OPENGL
- // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the
- // same way as a render texture produced on Direct3D.
- offset.y_ = -offset.y_;
- scale.y_ = -scale.y_;
- #endif
- }
- Matrix4 projection(Matrix4::IDENTITY);
- projection.m00_ = scale.x_ * uiScale_;
- projection.m03_ = offset.x_;
- projection.m11_ = scale.y_ * uiScale_;
- projection.m13_ = offset.y_;
- projection.m22_ = 1.0f;
- projection.m23_ = 0.0f;
- projection.m33_ = 1.0f;
- graphics_->ClearParameterSources();
- graphics_->SetColorWrite(true);
- #ifdef URHO3D_OPENGL
- // Reverse winding if rendering to texture on OpenGL
- if (surface)
- graphics_->SetCullMode(CULL_CW);
- else
- #endif
- graphics_->SetCullMode(CULL_CCW);
- graphics_->SetDepthTest(CMP_ALWAYS);
- graphics_->SetDepthWrite(false);
- graphics_->SetFillMode(FILL_SOLID);
- graphics_->SetStencilTest(false);
- graphics_->SetVertexBuffer(buffer);
- ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
- ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
- ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
- ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
- ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
- ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
- for (unsigned i = batchStart; i < batchEnd; ++i)
- {
- const UIBatch& batch = batches[i];
- if (batch.vertexStart_ == batch.vertexEnd_)
- continue;
- ShaderVariation* ps;
- ShaderVariation* vs;
- if (!batch.texture_)
- {
- ps = noTexturePS;
- vs = noTextureVS;
- }
- else
- {
- // If texture contains only an alpha channel, use alpha shader (for fonts)
- vs = diffTextureVS;
- if (batch.texture_->GetFormat() == alphaFormat)
- ps = alphaTexturePS;
- else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
- ps = diffMaskTexturePS;
- else
- ps = diffTexturePS;
- }
- graphics_->SetShaders(vs, ps);
- if (graphics_->NeedParameterUpdate(SP_OBJECT, this))
- graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
- if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
- graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
- if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
- graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
- float elapsedTime = GetSubsystem<Time>()->GetElapsedTime();
- graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
- graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
- IntRect scissor = batch.scissor_;
- scissor.left_ = (int)(scissor.left_ * uiScale_);
- scissor.top_ = (int)(scissor.top_ * uiScale_);
- scissor.right_ = (int)(scissor.right_ * uiScale_);
- scissor.bottom_ = (int)(scissor.bottom_ * uiScale_);
- // Flip scissor vertically if using OpenGL texture rendering
- #ifdef URHO3D_OPENGL
- if (surface)
- {
- int top = scissor.top_;
- int bottom = scissor.bottom_;
- scissor.top_ = viewSize.y_ - bottom;
- scissor.bottom_ = viewSize.y_ - top;
- }
- #endif
- graphics_->SetBlendMode(batch.blendMode_);
- graphics_->SetScissorTest(true, scissor);
- graphics_->SetTexture(0, batch.texture_);
- graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE,
- (batch.vertexEnd_ - batch.vertexStart_) / UI_VERTEX_SIZE);
- }
- }
- void UI::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, UIElement* element, IntRect currentScissor)
- {
- // Set clipping scissor for child elements. No need to draw if zero size
- element->AdjustScissor(currentScissor);
- if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
- return;
- element->SortChildren();
- const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
- if (children.Empty())
- return;
- // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
- // same renderstate
- Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
- if (element->GetTraversalMode() == TM_BREADTH_FIRST)
- {
- Vector<SharedPtr<UIElement> >::ConstIterator j = i;
- while (i != children.End())
- {
- int currentPriority = (*i)->GetPriority();
- while (j != children.End() && (*j)->GetPriority() == currentPriority)
- {
- if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
- (*j)->GetBatches(batches, vertexData, currentScissor);
- ++j;
- }
- // Now recurse into the children
- while (i != j)
- {
- if ((*i)->IsVisible() && (*i) != cursor_)
- GetBatches(batches, vertexData, *i, currentScissor);
- ++i;
- }
- }
- }
- // On the root level draw each element and its children immediately after to avoid artifacts
- else
- {
- while (i != children.End())
- {
- if ((*i) != cursor_)
- {
- if ((*i)->IsWithinScissor(currentScissor))
- (*i)->GetBatches(batches, vertexData, currentScissor);
- if ((*i)->IsVisible())
- GetBatches(batches, vertexData, *i, currentScissor);
- }
- ++i;
- }
- }
- }
- void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
- {
- if (!current)
- return;
- current->SortChildren();
- const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
- LayoutMode parentLayoutMode = current->GetLayoutMode();
- for (unsigned i = 0; i < children.Size(); ++i)
- {
- UIElement* element = children[i];
- bool hasChildren = element->GetNumChildren() > 0;
- if (element != cursor_.Get() && element->IsVisible())
- {
- if (element->IsInside(position, true))
- {
- // Store the current result, then recurse into its children. Because children
- // are sorted from lowest to highest priority, the topmost match should remain
- if (element->IsEnabled() || !enabledOnly)
- result = element;
- if (hasChildren)
- GetElementAt(result, element, position, enabledOnly);
- // Layout optimization: if the element has no children, can break out after the first match
- else if (parentLayoutMode != LM_FREE)
- break;
- }
- else
- {
- if (hasChildren)
- {
- if (element->IsInsideCombined(position, true))
- GetElementAt(result, element, position, enabledOnly);
- }
- // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
- // or if we already passed all visible elements
- else if (parentLayoutMode != LM_FREE)
- {
- if (!i)
- {
- int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
- element->GetScreenPosition().y_;
- int layoutMaxSize = current->GetLayoutElementMaxSize();
- if (screenPos < 0 && layoutMaxSize > 0)
- {
- unsigned toSkip = (unsigned)(-screenPos / layoutMaxSize);
- if (toSkip > 0)
- i += (toSkip - 1);
- }
- }
- // Note: we cannot check for the up / left limits of positioning, since the element may be off the visible
- // screen but some of its layouted children will yet be visible. In down & right directions we can terminate
- // the loop, since all further children will be further down or right.
- else if (parentLayoutMode == LM_HORIZONTAL)
- {
- if (element->GetScreenPosition().x_ >= rootElement_->GetPosition().x_ + rootElement_->GetSize().x_)
- break;
- }
- else if (parentLayoutMode == LM_VERTICAL)
- {
- if (element->GetScreenPosition().y_ >= rootElement_->GetPosition().y_ + rootElement_->GetSize().y_)
- break;
- }
- }
- }
- }
- }
- }
- UIElement* UI::GetFocusableElement(UIElement* element)
- {
- while (element)
- {
- if (element->GetFocusMode() != FM_NOTFOCUSABLE)
- break;
- element = element->GetParent();
- }
- return element;
- }
- void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
- {
- // Prefer software cursor then OS-specific cursor
- if (cursor_ && cursor_->IsVisible())
- {
- pos = cursor_->GetPosition();
- visible = true;
- }
- else if (GetSubsystem<Input>()->GetMouseMode() == MM_RELATIVE)
- visible = true;
- else
- {
- Input* input = GetSubsystem<Input>();
- pos = input->GetMousePosition();
- visible = input->IsMouseVisible();
- if (!visible && cursor_)
- pos = cursor_->GetPosition();
- }
- pos.x_ = (int)(pos.x_ / uiScale_);
- pos.y_ = (int)(pos.y_ / uiScale_);
- }
- void UI::SetCursorShape(CursorShape shape)
- {
- if (cursor_)
- cursor_->SetShape(shape);
- }
- void UI::ReleaseFontFaces()
- {
- URHO3D_LOGDEBUG("Reloading font faces");
- PODVector<Font*> fonts;
- GetSubsystem<ResourceCache>()->GetResources<Font>(fonts);
- for (unsigned i = 0; i < fonts.Size(); ++i)
- fonts[i]->ReleaseFaces();
- }
- void UI::ProcessHover(const IntVector2& windowCursorPos, int buttons, int qualifiers, Cursor* cursor)
- {
- IntVector2 cursorPos;
- WeakPtr<UIElement> element(GetElementAt(windowCursorPos, true, &cursorPos));
- for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
- {
- WeakPtr<UIElement> dragElement = i->first_;
- UI::DragData* dragData = i->second_;
- if (!dragElement)
- {
- i = DragElementErase(i);
- continue;
- }
- bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE) != 0;
- bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
- bool dragDropTest = dragSource && dragTarget && element != dragElement;
- // If drag start event has not been posted yet, do not do drag handling here
- if (dragData->dragBeginPending)
- dragSource = dragTarget = dragDropTest = false;
- // Hover effect
- // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
- if (element && element->IsEnabled())
- {
- if (dragElement == element || dragDropTest)
- {
- element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
- // Begin hover event
- if (!hoveredElements_.Contains(element))
- {
- SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, nullptr);
- // Exit if element is destroyed by the event handling
- if (!element)
- return;
- }
- hoveredElements_[element] = true;
- }
- }
- // Drag and drop test
- if (dragDropTest)
- {
- bool accept = element->OnDragDropTest(dragElement);
- if (accept)
- {
- using namespace DragDropTest;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SOURCE] = dragElement.Get();
- eventData[P_TARGET] = element.Get();
- eventData[P_ACCEPT] = accept;
- SendEvent(E_DRAGDROPTEST, eventData);
- accept = eventData[P_ACCEPT].GetBool();
- }
- if (cursor)
- cursor->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
- }
- else if (dragSource && cursor)
- cursor->SetShape(dragElement == element ? CS_ACCEPTDROP : CS_REJECTDROP);
- ++i;
- }
- // Hover effect
- // If no drag is going on, transmit hover event.
- if (element && element->IsEnabled())
- {
- if (dragElementsCount_ == 0)
- {
- element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
- // Begin hover event
- if (!hoveredElements_.Contains(element))
- {
- SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, nullptr);
- // Exit if element is destroyed by the event handling
- if (!element)
- return;
- }
- hoveredElements_[element] = true;
- }
- }
- }
- void UI::ProcessClickBegin(const IntVector2& windowCursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
- {
- if (cursorVisible)
- {
- IntVector2 cursorPos;
- WeakPtr<UIElement> element(GetElementAt(windowCursorPos, true, &cursorPos));
- bool newButton;
- if (usingTouchInput_)
- newButton = (button & buttons) == 0;
- else
- newButton = true;
- buttons |= button;
- if (element)
- SetFocusElement(element);
- // Focus change events may destroy the element, check again.
- if (element)
- {
- // Handle focusing & bringing to front
- element->BringToFront();
- // Handle click
- element->OnClickBegin(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
- SendClickEvent(E_UIMOUSECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
- // Fire double click event if element matches and is in time
- if (doubleClickElement_ && element == doubleClickElement_ &&
- clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons)
- {
- element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
- doubleClickElement_.Reset();
- SendClickEvent(E_UIMOUSEDOUBLECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
- }
- else
- {
- doubleClickElement_ = element;
- clickTimer_.Reset();
- }
- // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
- bool dragElementsContain = dragElements_.Contains(element);
- if (element && !dragElementsContain)
- {
- DragData* dragData = new DragData();
- dragElements_[element] = dragData;
- dragData->dragBeginPending = true;
- dragData->sumPos = cursorPos;
- dragData->dragBeginSumPos = cursorPos;
- dragData->dragBeginTimer.Reset();
- dragData->dragButtons = button;
- dragData->numDragButtons = CountSetBits((unsigned)dragData->dragButtons);
- dragElementsCount_++;
- dragElementsContain = dragElements_.Contains(element);
- }
- else if (element && dragElementsContain && newButton)
- {
- DragData* dragData = dragElements_[element];
- dragData->sumPos += cursorPos;
- dragData->dragBeginSumPos += cursorPos;
- dragData->dragButtons |= button;
- dragData->numDragButtons = CountSetBits((unsigned)dragData->dragButtons);
- }
- }
- else
- {
- // If clicked over no element, or a disabled element, lose focus (but not if there is a modal element)
- if (!HasModalElement())
- SetFocusElement(nullptr);
- SendClickEvent(E_UIMOUSECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
- if (clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons)
- SendClickEvent(E_UIMOUSEDOUBLECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
- }
- lastMouseButtons_ = buttons;
- }
- }
- void UI::ProcessClickEnd(const IntVector2& windowCursorPos, int button, int buttons, int qualifiers, Cursor* cursor, bool cursorVisible)
- {
- WeakPtr<UIElement> element;
- IntVector2 cursorPos = windowCursorPos;
- if (cursorVisible)
- element = GetElementAt(cursorPos, true, &cursorPos);
- // Handle end of drag
- for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
- {
- WeakPtr<UIElement> dragElement = i->first_;
- UI::DragData* dragData = i->second_;
- if (!dragElement || !cursorVisible)
- {
- i = DragElementErase(i);
- continue;
- }
- if (dragData->dragButtons & button)
- {
- // Handle end of click
- if (element)
- element->OnClickEnd(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor,
- dragElement);
- SendClickEvent(E_UIMOUSECLICKEND, dragElement, element, cursorPos, button, buttons, qualifiers);
- if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
- {
- dragElement->OnDragEnd(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, buttons,
- cursor);
- SendDragOrHoverEvent(E_DRAGEND, dragElement, cursorPos, IntVector2::ZERO, dragData);
- bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE) != 0;
- if (dragSource)
- {
- bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
- bool dragDropFinish = dragSource && dragTarget && element != dragElement;
- if (dragDropFinish)
- {
- bool accept = element->OnDragDropFinish(dragElement);
- // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
- if (accept && dragElement && element)
- {
- using namespace DragDropFinish;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_SOURCE] = dragElement.Get();
- eventData[P_TARGET] = element.Get();
- eventData[P_ACCEPT] = accept;
- SendEvent(E_DRAGDROPFINISH, eventData);
- }
- }
- }
- }
- i = DragElementErase(i);
- }
- else
- ++i;
- }
- }
- void UI::ProcessMove(const IntVector2& windowCursorPos, const IntVector2& cursorDeltaPos, int buttons, int qualifiers, Cursor* cursor,
- bool cursorVisible)
- {
- if (cursorVisible && dragElementsCount_ > 0 && buttons)
- {
- IntVector2 cursorPos;
- GetElementAt(windowCursorPos, true, &cursorPos);
- Input* input = GetSubsystem<Input>();
- bool mouseGrabbed = input->IsMouseGrabbed();
- for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
- {
- WeakPtr<UIElement> dragElement = i->first_;
- UI::DragData* dragData = i->second_;
- if (!dragElement)
- {
- i = DragElementErase(i);
- continue;
- }
- if (!(dragData->dragButtons & buttons))
- {
- ++i;
- continue;
- }
- // Calculate the position that we should send for this drag event.
- IntVector2 sendPos;
- if (usingTouchInput_)
- {
- dragData->sumPos += cursorDeltaPos;
- sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
- sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
- }
- else
- {
- dragData->sumPos = cursorPos;
- sendPos = cursorPos;
- }
- if (dragElement->IsEnabled() && dragElement->IsVisible())
- {
- // Signal drag begin if distance threshold was exceeded
- if (dragData->dragBeginPending && !mouseGrabbed)
- {
- IntVector2 beginSendPos;
- beginSendPos.x_ = dragData->dragBeginSumPos.x_ / dragData->numDragButtons;
- beginSendPos.y_ = dragData->dragBeginSumPos.y_ / dragData->numDragButtons;
- IntVector2 offset = cursorPos - beginSendPos;
- if (Abs(offset.x_) >= dragBeginDistance_ || Abs(offset.y_) >= dragBeginDistance_)
- {
- dragData->dragBeginPending = false;
- dragConfirmedCount_++;
- dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, buttons, qualifiers,
- cursor);
- SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
- }
- }
- if (!dragData->dragBeginPending)
- {
- dragElement->OnDragMove(dragElement->ScreenToElement(sendPos), sendPos, cursorDeltaPos, buttons, qualifiers,
- cursor);
- SendDragOrHoverEvent(E_DRAGMOVE, dragElement, sendPos, cursorDeltaPos, dragData);
- }
- }
- else
- {
- dragElement->OnDragEnd(dragElement->ScreenToElement(sendPos), sendPos, dragData->dragButtons, buttons, cursor);
- SendDragOrHoverEvent(E_DRAGEND, dragElement, sendPos, IntVector2::ZERO, dragData);
- dragElement.Reset();
- }
- ++i;
- }
- }
- }
- void UI::SendDragOrHoverEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos, const IntVector2& deltaPos,
- UI::DragData* dragData)
- {
- if (!element)
- return;
- IntVector2 relativePos = element->ScreenToElement(screenPos);
- using namespace DragMove;
- VariantMap& eventData = GetEventDataMap();
- eventData[P_ELEMENT] = element;
- eventData[P_X] = screenPos.x_;
- eventData[P_Y] = screenPos.y_;
- eventData[P_ELEMENTX] = relativePos.x_;
- eventData[P_ELEMENTY] = relativePos.y_;
- if (eventType == E_DRAGMOVE)
- {
- eventData[P_DX] = deltaPos.x_;
- eventData[P_DY] = deltaPos.y_;
- }
- if (dragData)
- {
- eventData[P_BUTTONS] = dragData->dragButtons;
- eventData[P_NUMBUTTONS] = dragData->numDragButtons;
- }
- element->SendEvent(eventType, eventData);
- }
- void UI::SendClickEvent(StringHash eventType, UIElement* beginElement, UIElement* endElement, const IntVector2& pos, int button,
- int buttons, int qualifiers)
- {
- VariantMap& eventData = GetEventDataMap();
- eventData[UIMouseClick::P_ELEMENT] = endElement;
- eventData[UIMouseClick::P_X] = pos.x_;
- eventData[UIMouseClick::P_Y] = pos.y_;
- eventData[UIMouseClick::P_BUTTON] = button;
- eventData[UIMouseClick::P_BUTTONS] = buttons;
- eventData[UIMouseClick::P_QUALIFIERS] = qualifiers;
- // For click end events, send also the element the click began on
- if (eventType == E_UIMOUSECLICKEND)
- eventData[UIMouseClickEnd::P_BEGINELEMENT] = beginElement;
- if (endElement)
- {
- // Send also element version of the event
- if (eventType == E_UIMOUSECLICK)
- endElement->SendEvent(E_CLICK, eventData);
- else if (eventType == E_UIMOUSECLICKEND)
- endElement->SendEvent(E_CLICKEND, eventData);
- else if (eventType == E_UIMOUSEDOUBLECLICK)
- endElement->SendEvent(E_DOUBLECLICK, eventData);
- }
- // Send the global event from the UI subsystem last
- SendEvent(eventType, eventData);
- }
- void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
- {
- using namespace ScreenMode;
- if (!initialized_)
- Initialize();
- else
- ResizeRootElement();
- }
- void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
- {
- using namespace MouseButtonDown;
- mouseButtons_ = eventData[P_BUTTONS].GetInt();
- qualifiers_ = eventData[P_QUALIFIERS].GetInt();
- usingTouchInput_ = false;
- IntVector2 cursorPos;
- bool cursorVisible;
- GetCursorPositionAndVisible(cursorPos, cursorVisible);
- // Handle drag cancelling
- ProcessDragCancel();
- Input* input = GetSubsystem<Input>();
- if (!input->IsMouseGrabbed())
- ProcessClickBegin(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
- }
- void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
- {
- using namespace MouseButtonUp;
- mouseButtons_ = eventData[P_BUTTONS].GetInt();
- qualifiers_ = eventData[P_QUALIFIERS].GetInt();
- IntVector2 cursorPos;
- bool cursorVisible;
- GetCursorPositionAndVisible(cursorPos, cursorVisible);
- ProcessClickEnd(cursorPos, eventData[P_BUTTON].GetInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
- }
- void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
- {
- using namespace MouseMove;
- mouseButtons_ = eventData[P_BUTTONS].GetInt();
- qualifiers_ = eventData[P_QUALIFIERS].GetInt();
- usingTouchInput_ = false;
- Input* input = GetSubsystem<Input>();
- const IntVector2& rootSize = rootElement_->GetSize();
- const IntVector2& rootPos = rootElement_->GetPosition();
- IntVector2 DeltaP = IntVector2(eventData[P_DX].GetInt(), eventData[P_DY].GetInt());
- if (cursor_)
- {
- if (!input->IsMouseVisible())
- {
- if (!input->IsMouseLocked())
- cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
- else if (cursor_->IsVisible())
- {
- // Relative mouse motion: move cursor only when visible
- IntVector2 pos = cursor_->GetPosition();
- pos.x_ += eventData[P_DX].GetInt();
- pos.y_ += eventData[P_DY].GetInt();
- pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
- pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
- cursor_->SetPosition(pos);
- }
- }
- else
- {
- // Absolute mouse motion: move always
- cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
- }
- }
- IntVector2 cursorPos;
- bool cursorVisible;
- GetCursorPositionAndVisible(cursorPos, cursorVisible);
- ProcessMove(cursorPos, DeltaP, mouseButtons_, qualifiers_, cursor_, cursorVisible);
- }
- void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
- {
- Input* input = GetSubsystem<Input>();
- if (input->IsMouseGrabbed())
- return;
- using namespace MouseWheel;
- mouseButtons_ = eventData[P_BUTTONS].GetInt();
- qualifiers_ = eventData[P_QUALIFIERS].GetInt();
- int delta = eventData[P_WHEEL].GetInt();
- usingTouchInput_ = false;
- IntVector2 cursorPos;
- bool cursorVisible;
- GetCursorPositionAndVisible(cursorPos, cursorVisible);
- UIElement* element;
- if (!nonFocusedMouseWheel_ && (element = focusElement_))
- element->OnWheel(delta, mouseButtons_, qualifiers_);
- else
- {
- // If no element has actual focus or in non-focused mode, get the element at cursor
- if (cursorVisible)
- {
- element = GetElementAt(cursorPos);
- if (nonFocusedMouseWheel_)
- {
- // Going up the hierarchy chain to find element that could handle mouse wheel
- while (element)
- {
- if (element->GetType() == ListView::GetTypeStatic() ||
- element->GetType() == ScrollView::GetTypeStatic())
- break;
- element = element->GetParent();
- }
- }
- else
- // If the element itself is not focusable, search for a focusable parent,
- // although the focusable element may not actually handle mouse wheel
- element = GetFocusableElement(element);
- if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
- element->OnWheel(delta, mouseButtons_, qualifiers_);
- }
- }
- }
- void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
- {
- Input* input = GetSubsystem<Input>();
- if (input->IsMouseGrabbed())
- return;
- using namespace TouchBegin;
- IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
- pos.x_ = int(pos.x_ / uiScale_);
- pos.y_ = int(pos.y_ / uiScale_);
- usingTouchInput_ = true;
- int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
- WeakPtr<UIElement> element(GetElementAt(pos));
- if (element)
- {
- ProcessClickBegin(pos, touchId, touchDragElements_[element], 0, nullptr, true);
- touchDragElements_[element] |= touchId;
- }
- else
- ProcessClickBegin(pos, touchId, touchId, 0, nullptr, true);
- }
- void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
- {
- using namespace TouchEnd;
- IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
- pos.x_ = int(pos.x_ / uiScale_);
- pos.y_ = int(pos.y_ / uiScale_);
- // Get the touch index
- int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
- // Transmit hover end to the position where the finger was lifted
- WeakPtr<UIElement> element(GetElementAt(pos));
- // Clear any drag events that were using the touch id
- for (HashMap<WeakPtr<UIElement>, int>::Iterator i = touchDragElements_.Begin(); i != touchDragElements_.End();)
- {
- int touches = i->second_;
- if (touches & touchId)
- i = touchDragElements_.Erase(i);
- else
- ++i;
- }
- if (element && element->IsEnabled())
- element->OnHover(element->ScreenToElement(pos), pos, 0, 0, nullptr);
- ProcessClickEnd(pos, touchId, 0, 0, nullptr, true);
- }
- void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
- {
- using namespace TouchMove;
- IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
- IntVector2 deltaPos(eventData[P_DX].GetInt(), eventData[P_DY].GetInt());
- pos.x_ = int(pos.x_ / uiScale_);
- pos.y_ = int(pos.y_ / uiScale_);
- deltaPos.x_ = int(deltaPos.x_ / uiScale_);
- deltaPos.y_ = int(deltaPos.y_ / uiScale_);
- usingTouchInput_ = true;
- int touchId = TOUCHID_MASK(eventData[P_TOUCHID].GetInt());
- ProcessMove(pos, deltaPos, touchId, 0, nullptr, true);
- }
- void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
- {
- using namespace KeyDown;
- mouseButtons_ = eventData[P_BUTTONS].GetInt();
- qualifiers_ = eventData[P_QUALIFIERS].GetInt();
- int key = eventData[P_KEY].GetInt();
- // Cancel UI dragging
- if (key == KEY_ESCAPE && dragElementsCount_ > 0)
- {
- ProcessDragCancel();
- return;
- }
- // Dismiss modal element if any when ESC key is pressed
- if (key == KEY_ESCAPE && HasModalElement())
- {
- UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
- if (element->GetVars().Contains(VAR_ORIGIN))
- // If it is a popup, dismiss by defocusing it
- SetFocusElement(nullptr);
- else
- {
- // If it is a modal window, by resetting its modal flag
- Window* window = dynamic_cast<Window*>(element);
- if (window && window->GetModalAutoDismiss())
- window->SetModal(false);
- }
- return;
- }
- UIElement* element = focusElement_;
- if (element)
- {
- // Switch focus between focusable elements in the same top level window
- if (key == KEY_TAB)
- {
- UIElement* topLevel = element->GetParent();
- while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
- topLevel = topLevel->GetParent();
- if (topLevel)
- {
- topLevel->GetChildren(tempElements_, true);
- for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
- {
- if ((*i)->GetFocusMode() < FM_FOCUSABLE)
- i = tempElements_.Erase(i);
- else
- ++i;
- }
- for (unsigned i = 0; i < tempElements_.Size(); ++i)
- {
- if (tempElements_[i] == element)
- {
- int dir = (qualifiers_ & QUAL_SHIFT) ? -1 : 1;
- unsigned nextIndex = (tempElements_.Size() + i + dir) % tempElements_.Size();
- UIElement* next = tempElements_[nextIndex];
- SetFocusElement(next, true);
- return;
- }
- }
- }
- }
- // Defocus the element
- else if (key == KEY_ESCAPE && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
- element->SetFocus(false);
- // If none of the special keys, pass the key to the focused element
- else
- element->OnKey(key, mouseButtons_, qualifiers_);
- }
- }
- void UI::HandleTextInput(StringHash eventType, VariantMap& eventData)
- {
- using namespace TextInput;
- UIElement* element = focusElement_;
- if (element)
- element->OnTextInput(eventData[P_TEXT].GetString());
- }
- void UI::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
- {
- // If have a cursor, and a drag is not going on, reset the cursor shape. Application logic that wants to apply
- // custom shapes can do it after this, but needs to do it each frame
- if (cursor_ && dragElementsCount_ == 0)
- cursor_->SetShape(CS_NORMAL);
- }
- void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
- {
- using namespace PostUpdate;
- Update(eventData[P_TIMESTEP].GetFloat());
- }
- void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
- {
- RenderUpdate();
- }
- void UI::HandleDropFile(StringHash eventType, VariantMap& eventData)
- {
- Input* input = GetSubsystem<Input>();
- // Sending the UI variant of the event only makes sense if the OS cursor is visible (not locked to window center)
- if (input->IsMouseVisible())
- {
- IntVector2 screenPos = input->GetMousePosition();
- screenPos.x_ = int(screenPos.x_ / uiScale_);
- screenPos.y_ = int(screenPos.y_ / uiScale_);
- UIElement* element = GetElementAt(screenPos);
- using namespace UIDropFile;
- VariantMap uiEventData;
- uiEventData[P_FILENAME] = eventData[P_FILENAME];
- uiEventData[P_X] = screenPos.x_;
- uiEventData[P_Y] = screenPos.y_;
- uiEventData[P_ELEMENT] = element;
- if (element)
- {
- IntVector2 relativePos = element->ScreenToElement(screenPos);
- uiEventData[P_ELEMENTX] = relativePos.x_;
- uiEventData[P_ELEMENTY] = relativePos.y_;
- }
- SendEvent(E_UIDROPFILE, uiEventData);
- }
- }
- HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator UI::DragElementErase(HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i)
- {
- // If running the engine frame in response to an event (re-entering UI frame logic) the dragElements_ may already be empty
- if (dragElements_.Empty())
- return dragElements_.End();
- dragElementsConfirmed_.Clear();
- DragData* dragData = i->second_;
- if (!dragData->dragBeginPending)
- --dragConfirmedCount_;
- i = dragElements_.Erase(i);
- --dragElementsCount_;
- delete dragData;
- return i;
- }
- void UI::ProcessDragCancel()
- {
- // How to tell difference between drag cancel and new selection on multi-touch?
- if (usingTouchInput_)
- return;
- IntVector2 cursorPos;
- bool cursorVisible;
- GetCursorPositionAndVisible(cursorPos, cursorVisible);
- for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
- {
- WeakPtr<UIElement> dragElement = i->first_;
- UI::DragData* dragData = i->second_;
- if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
- {
- dragElement->OnDragCancel(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, mouseButtons_,
- cursor_);
- SendDragOrHoverEvent(E_DRAGCANCEL, dragElement, cursorPos, IntVector2::ZERO, dragData);
- i = DragElementErase(i);
- }
- else
- ++i;
- }
- }
- IntVector2 UI::SumTouchPositions(UI::DragData* dragData, const IntVector2& oldSendPos)
- {
- IntVector2 sendPos = oldSendPos;
- if (usingTouchInput_)
- {
- int buttons = dragData->dragButtons;
- dragData->sumPos = IntVector2::ZERO;
- Input* input = GetSubsystem<Input>();
- for (int i = 0; (1 << i) <= buttons; i++)
- {
- if ((1 << i) & buttons)
- {
- TouchState* ts = input->GetTouch((unsigned)i);
- if (!ts)
- break;
- IntVector2 pos = ts->position_;
- dragData->sumPos.x_ += (int)(pos.x_ / uiScale_);
- dragData->sumPos.y_ += (int)(pos.y_ / uiScale_);
- }
- }
- sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
- sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
- }
- return sendPos;
- }
- void UI::ResizeRootElement()
- {
- IntVector2 effectiveSize = GetEffectiveRootElementSize();
- rootElement_->SetSize(effectiveSize);
- rootModalElement_->SetSize(effectiveSize);
- }
- IntVector2 UI::GetEffectiveRootElementSize(bool applyScale) const
- {
- // Use a fake size in headless mode
- IntVector2 size = graphics_ ? IntVector2(graphics_->GetWidth(), graphics_->GetHeight()) : IntVector2(1024, 768);
- if (customSize_.x_ > 0 && customSize_.y_ > 0)
- size = customSize_;
- if (applyScale)
- {
- size.x_ = (int)((float)size.x_ / uiScale_ + 0.5f);
- size.y_ = (int)((float)size.y_ / uiScale_ + 0.5f);
- }
- return size;
- }
- void UI::SetRenderToTexture(UIComponent* component, bool enable)
- {
- WeakPtr<UIComponent> weak(component);
- if (enable)
- {
- if (!renderToTexture_.Contains(weak))
- renderToTexture_.Push(weak);
- }
- else
- renderToTexture_.Remove(weak);
- }
- void RegisterUILibrary(Context* context)
- {
- Font::RegisterObject(context);
- UIElement::RegisterObject(context);
- BorderImage::RegisterObject(context);
- Sprite::RegisterObject(context);
- Button::RegisterObject(context);
- CheckBox::RegisterObject(context);
- Cursor::RegisterObject(context);
- Text::RegisterObject(context);
- Text3D::RegisterObject(context);
- Window::RegisterObject(context);
- View3D::RegisterObject(context);
- LineEdit::RegisterObject(context);
- Slider::RegisterObject(context);
- ScrollBar::RegisterObject(context);
- ScrollView::RegisterObject(context);
- ListView::RegisterObject(context);
- Menu::RegisterObject(context);
- DropDownList::RegisterObject(context);
- FileSelector::RegisterObject(context);
- MessageBox::RegisterObject(context);
- ProgressBar::RegisterObject(context);
- ToolTip::RegisterObject(context);
- UIComponent::RegisterObject(context);
- }
- }
|