UIElement.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Container/HashSet.h"
  26. #include "../Container/Sort.h"
  27. #include "../IO/Log.h"
  28. #include "../Resource/ResourceCache.h"
  29. #include "../Scene/ObjectAnimation.h"
  30. #include "../UI/Cursor.h"
  31. #include "../UI/UI.h"
  32. #include "../UI/UIElement.h"
  33. #include "../UI/UIEvents.h"
  34. #include "../DebugNew.h"
  35. namespace Urho3D
  36. {
  37. const char* horizontalAlignments[] =
  38. {
  39. "Left",
  40. "Center",
  41. "Right",
  42. "Custom",
  43. nullptr
  44. };
  45. const char* verticalAlignments[] =
  46. {
  47. "Top",
  48. "Center",
  49. "Bottom",
  50. "Custom",
  51. nullptr
  52. };
  53. static const char* focusModes[] =
  54. {
  55. "NotFocusable",
  56. "ResetFocus",
  57. "Focusable",
  58. "FocusableDefocusable",
  59. nullptr
  60. };
  61. static const char* dragDropModes[] =
  62. {
  63. "Disabled",
  64. "Source",
  65. "Target",
  66. "SourceAndTarget",
  67. nullptr
  68. };
  69. static const char* layoutModes[] =
  70. {
  71. "Free",
  72. "Horizontal",
  73. "Vertical",
  74. nullptr
  75. };
  76. extern const char* UI_CATEGORY;
  77. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  78. {
  79. return lhs->GetPriority() < rhs->GetPriority();
  80. }
  81. XPathQuery UIElement::styleXPathQuery_("/elements/element[@type=$typeName]", "typeName:String");
  82. UIElement::UIElement(Context* context) :
  83. Animatable(context),
  84. pivot_(std::numeric_limits<float>::max(), std::numeric_limits<float>::max())
  85. {
  86. SetEnabled(false);
  87. }
  88. UIElement::~UIElement()
  89. {
  90. // If child elements have outside references, detach them
  91. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  92. {
  93. if (i->Refs() > 1)
  94. (*i)->Detach();
  95. }
  96. }
  97. void UIElement::RegisterObject(Context* context)
  98. {
  99. context->RegisterFactory<UIElement>(UI_CATEGORY);
  100. URHO3D_ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_FILE);
  101. URHO3D_ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  102. URHO3D_ACCESSOR_ATTRIBUTE("Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  103. URHO3D_ACCESSOR_ATTRIBUTE("Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  104. URHO3D_ACCESSOR_ATTRIBUTE("Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2(M_MAX_INT, M_MAX_INT), AM_FILE);
  105. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment,
  106. horizontalAlignments, HA_LEFT, AM_FILEREADONLY);
  107. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments,
  108. VA_TOP, AM_FILEREADONLY);
  109. URHO3D_ACCESSOR_ATTRIBUTE("Min Anchor", GetMinAnchor, SetMinAnchor, Vector2, Vector2::ZERO, AM_FILE);
  110. URHO3D_ACCESSOR_ATTRIBUTE("Max Anchor", GetMaxAnchor, SetMaxAnchor, Vector2, Vector2::ZERO, AM_FILE);
  111. URHO3D_ACCESSOR_ATTRIBUTE("Min Offset", GetMinOffset, SetMinOffset, IntVector2, IntVector2::ZERO, AM_FILE);
  112. URHO3D_ACCESSOR_ATTRIBUTE("Max Offset", GetMaxOffset, SetMaxOffset, IntVector2, IntVector2::ZERO, AM_FILE);
  113. URHO3D_ACCESSOR_ATTRIBUTE("Pivot", GetPivot, SetPivot, Vector2, Vector2(std::numeric_limits<float>::max(), std::numeric_limits<float>::max()), AM_FILE);
  114. URHO3D_ACCESSOR_ATTRIBUTE("Enable Anchor", GetEnableAnchor, SetEnableAnchor, bool, false, AM_FILE);
  115. URHO3D_ACCESSOR_ATTRIBUTE("Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  116. URHO3D_ACCESSOR_ATTRIBUTE("Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  117. URHO3D_ACCESSOR_ATTRIBUTE("Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  118. URHO3D_ACCESSOR_ATTRIBUTE("Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  119. URHO3D_ATTRIBUTE("Top Left Color", Color, colors_[0], Color::WHITE, AM_FILE);
  120. URHO3D_ATTRIBUTE("Top Right Color", Color, colors_[1], Color::WHITE, AM_FILE);
  121. URHO3D_ATTRIBUTE("Bottom Left Color", Color, colors_[2], Color::WHITE, AM_FILE);
  122. URHO3D_ATTRIBUTE("Bottom Right Color", Color, colors_[3], Color::WHITE, AM_FILE);
  123. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, false, AM_FILE);
  124. URHO3D_ACCESSOR_ATTRIBUTE("Is Editable", IsEditable, SetEditable, bool, true, AM_FILE);
  125. URHO3D_ACCESSOR_ATTRIBUTE("Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  126. URHO3D_ACCESSOR_ATTRIBUTE("Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  127. URHO3D_ACCESSOR_ATTRIBUTE("Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  128. URHO3D_ACCESSOR_ATTRIBUTE("Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  129. URHO3D_ACCESSOR_ATTRIBUTE("Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  130. URHO3D_ACCESSOR_ATTRIBUTE("Use Derived Opacity", GetUseDerivedOpacity, SetUseDerivedOpacity, bool, true, AM_FILE);
  131. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  132. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Drag And Drop Mode", GetDragDropMode, SetDragDropMode, DragAndDropModeFlags, dragDropModes, DD_DISABLED, AM_FILE);
  133. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  134. URHO3D_ACCESSOR_ATTRIBUTE("Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  135. URHO3D_ACCESSOR_ATTRIBUTE("Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  136. URHO3D_ACCESSOR_ATTRIBUTE("Layout Flex Scale", GetLayoutFlexScale, SetLayoutFlexScale, Vector2, Vector2::ONE, AM_FILE);
  137. URHO3D_ACCESSOR_ATTRIBUTE("Indent", GetIndent, SetIndent, int, 0, AM_FILE);
  138. URHO3D_ACCESSOR_ATTRIBUTE("Indent Spacing", GetIndentSpacing, SetIndentSpacing, int, 16, AM_FILE);
  139. URHO3D_ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE);
  140. URHO3D_ATTRIBUTE("Tags", StringVector, tags_, Variant::emptyStringVector, AM_FILE);
  141. }
  142. void UIElement::ApplyAttributes()
  143. {
  144. colorGradient_ = false;
  145. derivedColorDirty_ = true;
  146. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  147. {
  148. if (colors_[i] != colors_[0])
  149. colorGradient_ = true;
  150. }
  151. }
  152. bool UIElement::LoadXML(const XMLElement& source)
  153. {
  154. return LoadXML(source, nullptr);
  155. }
  156. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile)
  157. {
  158. // Get style override if defined
  159. String styleName = source.GetAttribute("style");
  160. // Apply the style first, if the style file is available
  161. if (styleFile)
  162. {
  163. // If not defined, use type name
  164. if (styleName.Empty())
  165. styleName = GetTypeName();
  166. SetStyle(styleName, styleFile);
  167. }
  168. // The 'style' attribute value in the style file cannot be equals to original's applied style to prevent infinite loop
  169. else if (!styleName.Empty() && styleName != appliedStyle_)
  170. {
  171. // Attempt to use the default style file
  172. styleFile = GetDefaultStyle();
  173. if (styleFile)
  174. {
  175. // Remember the original applied style
  176. String appliedStyle(appliedStyle_);
  177. SetStyle(styleName, styleFile);
  178. appliedStyle_ = appliedStyle;
  179. }
  180. }
  181. // Prevent updates while loading attributes
  182. DisableLayoutUpdate();
  183. // Then load rest of the attributes from the source
  184. if (!Animatable::LoadXML(source))
  185. return false;
  186. unsigned nextInternalChild = 0;
  187. // Load child elements. Internal elements are not to be created as they already exist
  188. XMLElement childElem = source.GetChild("element");
  189. while (childElem)
  190. {
  191. bool internalElem = childElem.GetBool("internal");
  192. String typeName = childElem.GetAttribute("type");
  193. if (typeName.Empty())
  194. typeName = "UIElement";
  195. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  196. UIElement* child = nullptr;
  197. if (!internalElem)
  198. child = CreateChild(typeName, String::EMPTY, index);
  199. else
  200. {
  201. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  202. {
  203. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  204. {
  205. child = children_[i];
  206. nextInternalChild = i + 1;
  207. break;
  208. }
  209. }
  210. if (!child)
  211. URHO3D_LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  212. }
  213. if (child)
  214. {
  215. if (!styleFile)
  216. styleFile = GetDefaultStyle();
  217. if (!child->LoadXML(childElem, styleFile))
  218. return false;
  219. }
  220. childElem = childElem.GetNext("element");
  221. }
  222. ApplyAttributes();
  223. EnableLayoutUpdate();
  224. UpdateLayout();
  225. return true;
  226. }
  227. UIElement* UIElement::LoadChildXML(const XMLElement& childElem, XMLFile* styleFile)
  228. {
  229. bool internalElem = childElem.GetBool("internal");
  230. if (internalElem)
  231. {
  232. URHO3D_LOGERROR("Loading internal child element is not supported");
  233. return nullptr;
  234. }
  235. String typeName = childElem.GetAttribute("type");
  236. if (typeName.Empty())
  237. typeName = "UIElement";
  238. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  239. UIElement* child = CreateChild(typeName, String::EMPTY, index);
  240. if (child)
  241. {
  242. if (!styleFile)
  243. styleFile = GetDefaultStyle();
  244. if (!child->LoadXML(childElem, styleFile))
  245. {
  246. RemoveChild(child, index);
  247. return nullptr;
  248. }
  249. }
  250. return child;
  251. }
  252. bool UIElement::SaveXML(XMLElement& dest) const
  253. {
  254. // Write type
  255. if (GetTypeName() != "UIElement")
  256. {
  257. if (!dest.SetString("type", GetTypeName()))
  258. return false;
  259. }
  260. // Write internal flag
  261. if (internal_)
  262. {
  263. if (!dest.SetBool("internal", internal_))
  264. return false;
  265. }
  266. // Write style
  267. if (!appliedStyle_.Empty() && appliedStyle_ != "UIElement")
  268. {
  269. if (!dest.SetAttribute("style", appliedStyle_))
  270. return false;
  271. }
  272. else if (internal_)
  273. {
  274. if (!dest.SetAttribute("style", "none"))
  275. return false;
  276. }
  277. // Write attributes
  278. if (!Animatable::SaveXML(dest))
  279. return false;
  280. // Write child elements
  281. for (unsigned i = 0; i < children_.Size(); ++i)
  282. {
  283. UIElement* element = children_[i];
  284. if (element->IsTemporary())
  285. continue;
  286. XMLElement childElem = dest.CreateChild("element");
  287. if (!element->SaveXML(childElem))
  288. return false;
  289. }
  290. // Filter UI-style and implicit attributes
  291. return FilterAttributes(dest);
  292. }
  293. void UIElement::Update(float timeStep)
  294. {
  295. }
  296. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  297. {
  298. // Reset hovering for next frame
  299. hovering_ = false;
  300. }
  301. void UIElement::GetDebugDrawBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  302. {
  303. UIBatch batch(this, BLEND_ALPHA, currentScissor, nullptr, &vertexData);
  304. int horizontalThickness = 1;
  305. int verticalThickness = 1;
  306. if (parent_)
  307. {
  308. switch (parent_->layoutMode_)
  309. {
  310. case LM_HORIZONTAL:
  311. verticalThickness += 2;
  312. break;
  313. case LM_VERTICAL:
  314. horizontalThickness += 2;
  315. break;
  316. default:
  317. break;
  318. }
  319. }
  320. batch.SetColor(Color::BLUE, true);
  321. // Left
  322. batch.AddQuad(0, 0, horizontalThickness, size_.y_, 0, 0);
  323. // Top
  324. batch.AddQuad(0, 0, size_.x_, verticalThickness, 0, 0);
  325. // Right
  326. batch.AddQuad(size_.x_ - horizontalThickness, 0, horizontalThickness, size_.y_, 0, 0);
  327. // Bottom
  328. batch.AddQuad(0, size_.y_ - verticalThickness, size_.x_, verticalThickness, 0, 0);
  329. UIBatch::AddOrMerge(batch, batches);
  330. }
  331. bool UIElement::IsWithinScissor(const IntRect& currentScissor)
  332. {
  333. if (!visible_)
  334. return false;
  335. const IntVector2& screenPos = GetScreenPosition();
  336. return screenPos.x_ < currentScissor.right_ && screenPos.x_ + GetWidth() > currentScissor.left_ &&
  337. screenPos.y_ < currentScissor.bottom_ && screenPos.y_ + GetHeight() > currentScissor.top_;
  338. }
  339. const IntVector2& UIElement::GetScreenPosition() const
  340. {
  341. if (positionDirty_)
  342. {
  343. IntVector2 pos = position_;
  344. const UIElement* parent = parent_;
  345. if (parent)
  346. {
  347. const IntVector2& parentScreenPos = parent->GetScreenPosition();
  348. pos.x_ += parentScreenPos.x_ + (int)Lerp(0.0f, (float)parent->size_.x_, anchorMin_.x_);
  349. pos.y_ += parentScreenPos.y_ + (int)Lerp(0.0f, (float)parent->size_.y_, anchorMin_.y_);
  350. pos.x_ -= (int)(size_.x_ * pivot_.x_);
  351. pos.y_ -= (int)(size_.y_ * pivot_.y_);
  352. pos += parent_->childOffset_;
  353. }
  354. screenPosition_ = pos;
  355. positionDirty_ = false;
  356. }
  357. return screenPosition_;
  358. }
  359. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor)
  360. {
  361. hovering_ = true;
  362. }
  363. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags buttons, QualifierFlags qualifiers,
  364. Cursor* cursor)
  365. {
  366. dragButtonCombo_ = buttons;
  367. dragButtonCount_ = CountSetBits((unsigned)dragButtonCombo_);
  368. }
  369. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, const IntVector2& deltaPos, MouseButtonFlags buttons,
  370. QualifierFlags qualifiers, Cursor* cursor)
  371. {
  372. }
  373. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags /*dragButtons*/, MouseButtonFlags /*releaseButtons*/,
  374. Cursor* /*cursor*/)
  375. {
  376. dragButtonCombo_ = MOUSEB_NONE;
  377. dragButtonCount_ = 0;
  378. }
  379. void UIElement::OnDragCancel(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags /*dragButtons*/, MouseButtonFlags /*cancelButtons*/,
  380. Cursor* /*cursor*/)
  381. {
  382. dragButtonCombo_ = MOUSEB_NONE;
  383. dragButtonCount_ = 0;
  384. }
  385. bool UIElement::OnDragDropTest(UIElement* source)
  386. {
  387. return true;
  388. }
  389. bool UIElement::OnDragDropFinish(UIElement* source)
  390. {
  391. return true;
  392. }
  393. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  394. {
  395. return screenPosition - GetScreenPosition();
  396. }
  397. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  398. {
  399. return position + GetScreenPosition();
  400. }
  401. bool UIElement::LoadXML(Deserializer& source)
  402. {
  403. SharedPtr<XMLFile> xml(new XMLFile(context_));
  404. return xml->Load(source) && LoadXML(xml->GetRoot());
  405. }
  406. bool UIElement::SaveXML(Serializer& dest, const String& indentation) const
  407. {
  408. SharedPtr<XMLFile> xml(new XMLFile(context_));
  409. XMLElement rootElem = xml->CreateRoot("element");
  410. return SaveXML(rootElem) && xml->Save(dest, indentation);
  411. }
  412. bool UIElement::FilterAttributes(XMLElement& dest) const
  413. {
  414. // Filter UI styling attributes
  415. XMLFile* styleFile = GetDefaultStyle();
  416. if (styleFile)
  417. {
  418. String style = dest.GetAttribute("style");
  419. if (!style.Empty() && style != "none")
  420. {
  421. if (styleXPathQuery_.SetVariable("typeName", style))
  422. {
  423. XMLElement styleElem = GetDefaultStyle()->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  424. if (styleElem && !FilterUIStyleAttributes(dest, styleElem))
  425. return false;
  426. }
  427. }
  428. }
  429. // Filter implicit attributes
  430. if (!FilterImplicitAttributes(dest))
  431. {
  432. URHO3D_LOGERROR("Could not remove implicit attributes");
  433. return false;
  434. }
  435. return true;
  436. }
  437. void UIElement::SetName(const String& name)
  438. {
  439. name_ = name;
  440. using namespace NameChanged;
  441. VariantMap& eventData = GetEventDataMap();
  442. eventData[P_ELEMENT] = this;
  443. SendEvent(E_NAMECHANGED, eventData);
  444. }
  445. void UIElement::SetPosition(const IntVector2& position)
  446. {
  447. if (position != position_)
  448. {
  449. position_ = position;
  450. OnPositionSet(position);
  451. MarkDirty();
  452. using namespace Positioned;
  453. VariantMap& eventData = GetEventDataMap();
  454. eventData[P_ELEMENT] = this;
  455. eventData[P_X] = position.x_;
  456. eventData[P_Y] = position.y_;
  457. SendEvent(E_POSITIONED, eventData);
  458. }
  459. }
  460. void UIElement::SetPosition(int x, int y)
  461. {
  462. SetPosition(IntVector2(x, y));
  463. }
  464. void UIElement::SetSize(const IntVector2& size)
  465. {
  466. ++resizeNestingLevel_;
  467. IntVector2 oldSize = size_;
  468. IntVector2 validatedSize;
  469. IntVector2 effectiveMinSize = GetEffectiveMinSize();
  470. validatedSize.x_ = Clamp(size.x_, effectiveMinSize.x_, maxSize_.x_);
  471. validatedSize.y_ = Clamp(size.y_, effectiveMinSize.y_, maxSize_.y_);
  472. if (validatedSize != size_)
  473. {
  474. size_ = validatedSize;
  475. if (resizeNestingLevel_ == 1)
  476. {
  477. // Check if parent element's layout needs to be updated first
  478. if (parent_)
  479. parent_->UpdateLayout();
  480. IntVector2 delta = size_ - oldSize;
  481. MarkDirty();
  482. OnResize(size_, delta);
  483. UpdateLayout();
  484. using namespace Resized;
  485. VariantMap& eventData = GetEventDataMap();
  486. eventData[P_ELEMENT] = this;
  487. eventData[P_WIDTH] = size_.x_;
  488. eventData[P_HEIGHT] = size_.y_;
  489. eventData[P_DX] = delta.x_;
  490. eventData[P_DY] = delta.y_;
  491. SendEvent(E_RESIZED, eventData);
  492. }
  493. }
  494. --resizeNestingLevel_;
  495. }
  496. void UIElement::SetSize(int width, int height)
  497. {
  498. SetSize(IntVector2(width, height));
  499. }
  500. void UIElement::SetWidth(int width)
  501. {
  502. SetSize(IntVector2(width, size_.y_));
  503. }
  504. void UIElement::SetHeight(int height)
  505. {
  506. SetSize(IntVector2(size_.x_, height));
  507. }
  508. void UIElement::SetMinSize(const IntVector2& minSize)
  509. {
  510. minSize_.x_ = Max(minSize.x_, 0);
  511. minSize_.y_ = Max(minSize.y_, 0);
  512. SetSize(size_);
  513. }
  514. void UIElement::SetMinSize(int width, int height)
  515. {
  516. SetMinSize(IntVector2(width, height));
  517. }
  518. void UIElement::SetMinWidth(int width)
  519. {
  520. SetMinSize(IntVector2(width, minSize_.y_));
  521. }
  522. void UIElement::SetMinHeight(int height)
  523. {
  524. SetMinSize(IntVector2(minSize_.x_, height));
  525. }
  526. void UIElement::SetMaxSize(const IntVector2& maxSize)
  527. {
  528. maxSize_.x_ = Max(maxSize.x_, 0);
  529. maxSize_.y_ = Max(maxSize.y_, 0);
  530. SetSize(size_);
  531. }
  532. void UIElement::SetMaxSize(int width, int height)
  533. {
  534. SetMaxSize(IntVector2(width, height));
  535. }
  536. void UIElement::SetMaxWidth(int width)
  537. {
  538. SetMaxSize(IntVector2(width, maxSize_.y_));
  539. }
  540. void UIElement::SetMaxHeight(int height)
  541. {
  542. SetMaxSize(IntVector2(maxSize_.x_, height));
  543. }
  544. void UIElement::SetFixedSize(const IntVector2& size)
  545. {
  546. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  547. SetSize(size);
  548. }
  549. void UIElement::SetFixedSize(int width, int height)
  550. {
  551. SetFixedSize(IntVector2(width, height));
  552. }
  553. void UIElement::SetFixedWidth(int width)
  554. {
  555. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  556. SetWidth(width);
  557. }
  558. void UIElement::SetFixedHeight(int height)
  559. {
  560. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  561. SetHeight(height);
  562. }
  563. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  564. {
  565. SetHorizontalAlignment(hAlign);
  566. SetVerticalAlignment(vAlign);
  567. }
  568. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  569. {
  570. if (align != HA_LEFT && parent_ && parent_->GetLayoutMode() == LM_HORIZONTAL)
  571. {
  572. URHO3D_LOGWARNING("Forcing left alignment because parent element has horizontal layout");
  573. align = HA_LEFT;
  574. }
  575. Vector2 min = anchorMin_;
  576. Vector2 max = anchorMax_;
  577. float pivot = pivot_.x_;
  578. float anchorSize = max.x_ - min.x_;
  579. if (align == HA_CENTER)
  580. min.x_ = pivot = 0.5f;
  581. else if (align == HA_LEFT)
  582. min.x_ = pivot = 0.0f;
  583. else if (align == HA_RIGHT)
  584. min.x_ = pivot = 1.0f;
  585. max.x_ = enableAnchor_ ? (min.x_ + anchorSize) : min.x_;
  586. if (min.x_ != anchorMin_.x_ || max.x_ != anchorMax_.x_ || pivot != pivot_.x_)
  587. {
  588. anchorMin_.x_ = min.x_;
  589. anchorMax_.x_ = max.x_;
  590. pivot_.x_ = pivot;
  591. if (enableAnchor_)
  592. UpdateAnchoring();
  593. MarkDirty();
  594. }
  595. }
  596. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  597. {
  598. if (align != VA_TOP && parent_ && parent_->GetLayoutMode() == LM_VERTICAL)
  599. {
  600. URHO3D_LOGWARNING("Forcing top alignment because parent element has vertical layout");
  601. align = VA_TOP;
  602. }
  603. Vector2 min = anchorMin_;
  604. Vector2 max = anchorMax_;
  605. float pivot = pivot_.y_;
  606. float anchorSize = max.y_ - min.y_;
  607. if (align == VA_CENTER)
  608. min.y_ = pivot = 0.5f;
  609. else if (align == VA_TOP)
  610. min.y_ = pivot = 0.0f;
  611. else if (align == VA_BOTTOM)
  612. min.y_ = pivot = 1.0f;
  613. max.y_ = enableAnchor_ ? (min.y_ + anchorSize) : min.y_;
  614. if (min.y_ != anchorMin_.y_ || max.y_ != anchorMax_.y_ || pivot != pivot_.y_)
  615. {
  616. anchorMin_.y_ = min.y_;
  617. anchorMax_.y_ = max.y_;
  618. pivot_.y_ = pivot;
  619. if (enableAnchor_)
  620. UpdateAnchoring();
  621. MarkDirty();
  622. }
  623. }
  624. void UIElement::SetEnableAnchor(bool enable)
  625. {
  626. enableAnchor_ = enable;
  627. if (enableAnchor_)
  628. UpdateAnchoring();
  629. }
  630. void UIElement::SetMinOffset(const IntVector2& offset)
  631. {
  632. if (offset != minOffset_)
  633. {
  634. minOffset_ = offset;
  635. if (enableAnchor_)
  636. UpdateAnchoring();
  637. }
  638. }
  639. void UIElement::SetMaxOffset(const IntVector2& offset)
  640. {
  641. if (offset != maxOffset_)
  642. {
  643. maxOffset_ = offset;
  644. if (enableAnchor_)
  645. UpdateAnchoring();
  646. }
  647. }
  648. void UIElement::SetMinAnchor(const Vector2& anchor)
  649. {
  650. if (anchor != anchorMin_)
  651. {
  652. anchorMin_ = anchor;
  653. if (enableAnchor_)
  654. UpdateAnchoring();
  655. }
  656. }
  657. void UIElement::SetMinAnchor(float x, float y)
  658. {
  659. SetMinAnchor(Vector2(x, y));
  660. }
  661. void UIElement::SetMaxAnchor(const Vector2& anchor)
  662. {
  663. if (anchor != anchorMax_)
  664. {
  665. anchorMax_ = anchor;
  666. if (enableAnchor_)
  667. UpdateAnchoring();
  668. }
  669. }
  670. void UIElement::SetMaxAnchor(float x, float y)
  671. {
  672. SetMaxAnchor(Vector2(x, y));
  673. }
  674. void UIElement::SetPivot(const Vector2& pivot)
  675. {
  676. if (pivot != pivot_)
  677. {
  678. pivotSet_ = true;
  679. pivot_ = pivot;
  680. MarkDirty();
  681. }
  682. }
  683. void UIElement::SetPivot(float x, float y)
  684. {
  685. SetPivot(Vector2(x, y));
  686. }
  687. void UIElement::SetClipBorder(const IntRect& rect)
  688. {
  689. clipBorder_.left_ = Max(rect.left_, 0);
  690. clipBorder_.top_ = Max(rect.top_, 0);
  691. clipBorder_.right_ = Max(rect.right_, 0);
  692. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  693. }
  694. void UIElement::SetColor(const Color& color)
  695. {
  696. for (auto& cornerColor : colors_)
  697. cornerColor = color;
  698. colorGradient_ = false;
  699. derivedColorDirty_ = true;
  700. }
  701. void UIElement::SetColor(Corner corner, const Color& color)
  702. {
  703. colors_[corner] = color;
  704. colorGradient_ = false;
  705. derivedColorDirty_ = true;
  706. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  707. {
  708. if (i != corner && colors_[i] != colors_[corner])
  709. colorGradient_ = true;
  710. }
  711. }
  712. void UIElement::SetPriority(int priority)
  713. {
  714. if (priority_ == priority)
  715. return;
  716. priority_ = priority;
  717. if (parent_)
  718. parent_->sortOrderDirty_ = true;
  719. }
  720. void UIElement::SetOpacity(float opacity)
  721. {
  722. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  723. MarkDirty();
  724. }
  725. void UIElement::SetBringToFront(bool enable)
  726. {
  727. bringToFront_ = enable;
  728. }
  729. void UIElement::SetBringToBack(bool enable)
  730. {
  731. bringToBack_ = enable;
  732. }
  733. void UIElement::SetClipChildren(bool enable)
  734. {
  735. clipChildren_ = enable;
  736. }
  737. void UIElement::SetSortChildren(bool enable)
  738. {
  739. if (!sortChildren_ && enable)
  740. sortOrderDirty_ = true;
  741. sortChildren_ = enable;
  742. }
  743. void UIElement::SetUseDerivedOpacity(bool enable)
  744. {
  745. useDerivedOpacity_ = enable;
  746. }
  747. void UIElement::SetEnabled(bool enable)
  748. {
  749. enabled_ = enable;
  750. enabledPrev_ = enable;
  751. }
  752. void UIElement::SetDeepEnabled(bool enable)
  753. {
  754. enabled_ = enable;
  755. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  756. (*i)->SetDeepEnabled(enable);
  757. }
  758. void UIElement::ResetDeepEnabled()
  759. {
  760. enabled_ = enabledPrev_;
  761. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  762. (*i)->ResetDeepEnabled();
  763. }
  764. void UIElement::SetEnabledRecursive(bool enable)
  765. {
  766. enabled_ = enable;
  767. enabledPrev_ = enable;
  768. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  769. (*i)->SetEnabledRecursive(enable);
  770. }
  771. void UIElement::SetEditable(bool enable)
  772. {
  773. editable_ = enable;
  774. OnSetEditable();
  775. }
  776. void UIElement::SetFocusMode(FocusMode mode)
  777. {
  778. focusMode_ = mode;
  779. }
  780. void UIElement::SetFocus(bool enable)
  781. {
  782. // Invisible elements should not receive focus
  783. if (focusMode_ < FM_FOCUSABLE || !IsVisibleEffective())
  784. enable = false;
  785. auto* ui = GetSubsystem<UI>();
  786. // Can be null at exit time; no-op in that case
  787. if (!ui)
  788. return;
  789. if (enable)
  790. {
  791. if (ui->GetFocusElement() != this)
  792. ui->SetFocusElement(this);
  793. }
  794. else
  795. {
  796. if (ui->GetFocusElement() == this)
  797. ui->SetFocusElement(nullptr);
  798. }
  799. }
  800. void UIElement::SetSelected(bool enable)
  801. {
  802. selected_ = enable;
  803. }
  804. void UIElement::SetVisible(bool enable)
  805. {
  806. auto* ui = GetSubsystem<UI>();
  807. // Can be null at exit time; no-op in that case
  808. if (!ui)
  809. return;
  810. if (enable != visible_)
  811. {
  812. visible_ = enable;
  813. // Parent's layout may change as a result of visibility change
  814. if (parent_)
  815. parent_->UpdateLayout();
  816. using namespace VisibleChanged;
  817. VariantMap& eventData = GetEventDataMap();
  818. eventData[P_ELEMENT] = this;
  819. eventData[P_VISIBLE] = visible_;
  820. SendEvent(E_VISIBLECHANGED, eventData);
  821. // If the focus element becomes effectively hidden, clear focus
  822. if (!enable)
  823. {
  824. UIElement* focusElement = ui->GetFocusElement();
  825. if (focusElement && !focusElement->IsVisibleEffective())
  826. focusElement->SetFocus(false);
  827. }
  828. }
  829. }
  830. void UIElement::SetDragDropMode(DragAndDropModeFlags mode)
  831. {
  832. dragDropMode_ = mode;
  833. }
  834. bool UIElement::SetStyle(const String& styleName, XMLFile* file)
  835. {
  836. // If empty style was requested, replace with type name
  837. String actualStyleName = !styleName.Empty() ? styleName : GetTypeName();
  838. appliedStyle_ = actualStyleName;
  839. if (styleName == "none")
  840. return true;
  841. if (!file)
  842. {
  843. file = GetDefaultStyle();
  844. if (!file)
  845. return false;
  846. }
  847. else
  848. {
  849. // If a custom style file specified, remember it
  850. defaultStyle_ = file;
  851. }
  852. // Remember the effectively applied style file, either custom or default
  853. appliedStyleFile_ = file;
  854. styleXPathQuery_.SetVariable("typeName", actualStyleName);
  855. XMLElement styleElem = file->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  856. return styleElem && SetStyle(styleElem);
  857. }
  858. bool UIElement::SetStyle(const XMLElement& element)
  859. {
  860. appliedStyle_ = element.GetAttribute("type");
  861. // Consider style attribute values as instance-level attribute default values
  862. SetInstanceDefault(true);
  863. bool success = LoadXML(element);
  864. SetInstanceDefault(false);
  865. return success;
  866. }
  867. bool UIElement::SetStyleAuto(XMLFile* file)
  868. {
  869. return SetStyle(String::EMPTY, file);
  870. }
  871. void UIElement::SetDefaultStyle(XMLFile* style)
  872. {
  873. defaultStyle_ = style;
  874. }
  875. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  876. {
  877. layoutMode_ = mode;
  878. layoutSpacing_ = Max(spacing, 0);
  879. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  880. VerifyChildAlignment();
  881. UpdateLayout();
  882. }
  883. void UIElement::SetLayoutMode(LayoutMode mode)
  884. {
  885. layoutMode_ = mode;
  886. VerifyChildAlignment();
  887. UpdateLayout();
  888. }
  889. void UIElement::SetLayoutSpacing(int spacing)
  890. {
  891. layoutSpacing_ = Max(spacing, 0);
  892. UpdateLayout();
  893. }
  894. void UIElement::SetLayoutBorder(const IntRect& border)
  895. {
  896. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  897. UpdateLayout();
  898. }
  899. void UIElement::SetLayoutFlexScale(const Vector2& scale)
  900. {
  901. layoutFlexScale_ = Vector2(Max(scale.x_, 0.0f), Max(scale.y_, 0.0f));
  902. }
  903. void UIElement::SetIndent(int indent)
  904. {
  905. indent_ = indent;
  906. if (parent_)
  907. parent_->UpdateLayout();
  908. UpdateLayout();
  909. OnIndentSet();
  910. }
  911. void UIElement::SetIndentSpacing(int indentSpacing)
  912. {
  913. indentSpacing_ = Max(indentSpacing, 0);
  914. if (parent_)
  915. parent_->UpdateLayout();
  916. UpdateLayout();
  917. OnIndentSet();
  918. }
  919. void UIElement::UpdateLayout()
  920. {
  921. if (layoutNestingLevel_)
  922. return;
  923. // Prevent further updates while this update happens
  924. DisableLayoutUpdate();
  925. PODVector<int> positions;
  926. PODVector<int> sizes;
  927. PODVector<int> minSizes;
  928. PODVector<int> maxSizes;
  929. PODVector<float> flexScales;
  930. int baseIndentWidth = GetIndentWidth();
  931. if (layoutMode_ == LM_HORIZONTAL)
  932. {
  933. int minChildHeight = 0;
  934. for (unsigned i = 0; i < children_.Size(); ++i)
  935. {
  936. if (!children_[i]->IsVisible())
  937. continue;
  938. positions.Push(baseIndentWidth);
  939. auto indent = (unsigned)children_[i]->GetIndentWidth();
  940. sizes.Push(children_[i]->GetWidth() + indent);
  941. minSizes.Push(children_[i]->GetEffectiveMinSize().x_ + indent);
  942. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  943. flexScales.Push(children_[i]->GetLayoutFlexScale().x_);
  944. minChildHeight = Max(minChildHeight, children_[i]->GetEffectiveMinSize().y_);
  945. }
  946. CalculateLayout(positions, sizes, minSizes, maxSizes, flexScales, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  947. layoutSpacing_);
  948. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  949. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  950. int minWidth = CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  951. int minHeight = minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_;
  952. layoutMinSize_ = IntVector2(minWidth, minHeight);
  953. SetSize(width, height);
  954. // Validate the size before resizing child elements, in case of min/max limits
  955. width = size_.x_;
  956. height = size_.y_;
  957. unsigned j = 0;
  958. for (unsigned i = 0; i < children_.Size(); ++i)
  959. {
  960. if (!children_[i]->IsVisible())
  961. continue;
  962. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  963. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  964. ++j;
  965. }
  966. }
  967. else if (layoutMode_ == LM_VERTICAL)
  968. {
  969. int minChildWidth = 0;
  970. for (unsigned i = 0; i < children_.Size(); ++i)
  971. {
  972. if (!children_[i]->IsVisible())
  973. continue;
  974. positions.Push(0);
  975. sizes.Push(children_[i]->GetHeight());
  976. minSizes.Push(children_[i]->GetEffectiveMinSize().y_);
  977. maxSizes.Push(children_[i]->GetMaxHeight());
  978. flexScales.Push(children_[i]->GetLayoutFlexScale().y_);
  979. minChildWidth = Max(minChildWidth, children_[i]->GetEffectiveMinSize().x_ + children_[i]->GetIndentWidth());
  980. }
  981. CalculateLayout(positions, sizes, minSizes, maxSizes, flexScales, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  982. layoutSpacing_);
  983. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  984. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  985. int minHeight = CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  986. int minWidth = minChildWidth + layoutBorder_.left_ + layoutBorder_.right_;
  987. layoutMinSize_ = IntVector2(minWidth, minHeight);
  988. SetSize(width, height);
  989. width = size_.x_;
  990. height = size_.y_;
  991. unsigned j = 0;
  992. for (unsigned i = 0; i < children_.Size(); ++i)
  993. {
  994. if (!children_[i]->IsVisible())
  995. continue;
  996. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_ + baseIndentWidth, positions[j]);
  997. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  998. ++j;
  999. }
  1000. }
  1001. else
  1002. {
  1003. for (unsigned i = 0; i < children_.Size(); ++i)
  1004. {
  1005. if (children_[i]->GetEnableAnchor())
  1006. children_[i]->UpdateAnchoring();
  1007. }
  1008. }
  1009. using namespace LayoutUpdated;
  1010. VariantMap& eventData = GetEventDataMap();
  1011. eventData[P_ELEMENT] = this;
  1012. SendEvent(E_LAYOUTUPDATED, eventData);
  1013. EnableLayoutUpdate();
  1014. }
  1015. void UIElement::DisableLayoutUpdate()
  1016. {
  1017. ++layoutNestingLevel_;
  1018. }
  1019. void UIElement::EnableLayoutUpdate()
  1020. {
  1021. --layoutNestingLevel_;
  1022. }
  1023. void UIElement::BringToFront()
  1024. {
  1025. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  1026. UIElement* root = GetRoot();
  1027. // If element is detached from hierarchy, this must be a no-op
  1028. if (!root)
  1029. return;
  1030. UIElement* ptr = this;
  1031. while (ptr && ptr->GetParent() != root)
  1032. ptr = ptr->GetParent();
  1033. if (!ptr || !ptr->GetBringToFront())
  1034. return;
  1035. // Get the highest priority used by all other top level elements, assign that to the new front element
  1036. // and decrease others' priority where necessary. However, take into account only input-enabled
  1037. // elements and those which have the BringToBack flag set
  1038. HashSet<int> usedPriorities;
  1039. int maxPriority = M_MIN_INT;
  1040. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  1041. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  1042. {
  1043. UIElement* other = *i;
  1044. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  1045. {
  1046. int priority = other->GetPriority();
  1047. // M_MAX_INT is used by popups and tooltips. Disregard these to avoid an "arms race" with the priorities
  1048. if (priority == M_MAX_INT)
  1049. continue;
  1050. usedPriorities.Insert(priority);
  1051. maxPriority = Max(priority, maxPriority);
  1052. }
  1053. }
  1054. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  1055. {
  1056. ptr->SetPriority(maxPriority);
  1057. int minPriority = maxPriority;
  1058. while (usedPriorities.Contains(minPriority))
  1059. --minPriority;
  1060. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  1061. {
  1062. UIElement* other = *i;
  1063. int priority = other->GetPriority();
  1064. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  1065. other->SetPriority(priority - 1);
  1066. }
  1067. }
  1068. }
  1069. UIElement* UIElement::CreateChild(StringHash type, const String& name, unsigned index)
  1070. {
  1071. // Check that creation succeeds and that the object in fact is a UI element
  1072. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  1073. if (!newElement)
  1074. {
  1075. URHO3D_LOGERROR("Could not create unknown UI element type " + type.ToString());
  1076. return nullptr;
  1077. }
  1078. if (!name.Empty())
  1079. newElement->SetName(name);
  1080. InsertChild(index, newElement);
  1081. return newElement;
  1082. }
  1083. void UIElement::AddChild(UIElement* element)
  1084. {
  1085. InsertChild(M_MAX_UNSIGNED, element);
  1086. }
  1087. void UIElement::InsertChild(unsigned index, UIElement* element)
  1088. {
  1089. // Check for illegal or redundant parent assignment
  1090. if (!element || element == this || element->parent_ == this)
  1091. return;
  1092. // Check for possible cyclic parent assignment
  1093. UIElement* parent = parent_;
  1094. while (parent)
  1095. {
  1096. if (parent == element)
  1097. return;
  1098. parent = parent->parent_;
  1099. }
  1100. // Add first, then remove from old parent, to ensure the element does not get deleted
  1101. if (index >= children_.Size())
  1102. children_.Push(SharedPtr<UIElement>(element));
  1103. else
  1104. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  1105. element->Remove();
  1106. if (sortChildren_)
  1107. sortOrderDirty_ = true;
  1108. element->parent_ = this;
  1109. element->MarkDirty();
  1110. // Apply style now if child element (and its children) has it defined
  1111. ApplyStyleRecursive(element);
  1112. VerifyChildAlignment();
  1113. UpdateLayout();
  1114. // Send change event
  1115. UIElement* root = GetRoot();
  1116. UIElement* sender = GetElementEventSender();
  1117. if (sender)
  1118. {
  1119. using namespace ElementAdded;
  1120. VariantMap& eventData = GetEventDataMap();
  1121. eventData[P_ROOT] = root;
  1122. eventData[P_PARENT] = this;
  1123. eventData[P_ELEMENT] = element;
  1124. sender->SendEvent(E_ELEMENTADDED, eventData);
  1125. }
  1126. }
  1127. void UIElement::RemoveChild(UIElement* element, unsigned index)
  1128. {
  1129. for (unsigned i = index; i < children_.Size(); ++i)
  1130. {
  1131. if (children_[i] == element)
  1132. {
  1133. // Send change event if not already being destroyed
  1134. UIElement* sender = Refs() > 0 ? GetElementEventSender() : nullptr;
  1135. if (sender)
  1136. {
  1137. using namespace ElementRemoved;
  1138. VariantMap& eventData = GetEventDataMap();
  1139. eventData[P_ROOT] = GetRoot();
  1140. eventData[P_PARENT] = this;
  1141. eventData[P_ELEMENT] = element;
  1142. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1143. }
  1144. element->Detach();
  1145. children_.Erase(i);
  1146. UpdateLayout();
  1147. return;
  1148. }
  1149. }
  1150. }
  1151. void UIElement::RemoveChildAtIndex(unsigned index)
  1152. {
  1153. if (index >= children_.Size())
  1154. return;
  1155. // Send change event if not already being destroyed
  1156. UIElement* sender = Refs() > 0 ? GetElementEventSender() : nullptr;
  1157. if (sender)
  1158. {
  1159. using namespace ElementRemoved;
  1160. VariantMap& eventData = GetEventDataMap();
  1161. eventData[P_ROOT] = GetRoot();
  1162. eventData[P_PARENT] = this;
  1163. eventData[P_ELEMENT] = children_[index];
  1164. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1165. }
  1166. children_[index]->Detach();
  1167. children_.Erase(index);
  1168. UpdateLayout();
  1169. }
  1170. void UIElement::RemoveAllChildren()
  1171. {
  1172. UIElement* root = GetRoot();
  1173. UIElement* sender = Refs() > 0 ? GetElementEventSender() : nullptr;
  1174. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End();)
  1175. {
  1176. // Send change event if not already being destroyed
  1177. if (sender)
  1178. {
  1179. using namespace ElementRemoved;
  1180. VariantMap& eventData = GetEventDataMap();
  1181. eventData[P_ROOT] = root;
  1182. eventData[P_PARENT] = this;
  1183. eventData[P_ELEMENT] = (*i).Get();
  1184. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1185. }
  1186. (*i++)->Detach();
  1187. }
  1188. children_.Clear();
  1189. UpdateLayout();
  1190. }
  1191. void UIElement::Remove()
  1192. {
  1193. if (parent_)
  1194. parent_->RemoveChild(this);
  1195. }
  1196. unsigned UIElement::FindChild(UIElement* element) const
  1197. {
  1198. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  1199. return i != children_.End() ? (unsigned)(i - children_.Begin()) : M_MAX_UNSIGNED;
  1200. }
  1201. void UIElement::SetParent(UIElement* parent, unsigned index)
  1202. {
  1203. if (parent)
  1204. parent->InsertChild(index, this);
  1205. }
  1206. void UIElement::SetVar(StringHash key, const Variant& value)
  1207. {
  1208. vars_[key] = value;
  1209. }
  1210. void UIElement::SetInternal(bool enable)
  1211. {
  1212. internal_ = enable;
  1213. }
  1214. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  1215. {
  1216. traversalMode_ = traversalMode;
  1217. }
  1218. void UIElement::SetElementEventSender(bool flag)
  1219. {
  1220. elementEventSender_ = flag;
  1221. }
  1222. void UIElement::SetTags(const StringVector& tags)
  1223. {
  1224. RemoveAllTags();
  1225. AddTags(tags);
  1226. }
  1227. void UIElement::AddTag(const String& tag)
  1228. {
  1229. if (tag.Empty() || HasTag(tag))
  1230. return;
  1231. tags_.Push(tag);
  1232. }
  1233. void UIElement::AddTags(const String& tags, char separator)
  1234. {
  1235. StringVector tagVector = tags.Split(separator);
  1236. AddTags(tagVector);
  1237. }
  1238. void UIElement::AddTags(const StringVector& tags)
  1239. {
  1240. for (unsigned i = 0; i < tags.Size(); ++i)
  1241. AddTag(tags[i]);
  1242. }
  1243. bool UIElement::RemoveTag(const String& tag)
  1244. {
  1245. return tags_.Remove(tag);
  1246. }
  1247. void UIElement::RemoveAllTags()
  1248. {
  1249. tags_.Clear();
  1250. }
  1251. HorizontalAlignment UIElement::GetHorizontalAlignment() const
  1252. {
  1253. if (anchorMin_.x_ == 0.0f && anchorMax_.x_ == 0.0f && (!pivotSet_ || pivot_.x_ == 0.0f))
  1254. return HA_LEFT;
  1255. else if (anchorMin_.x_ == 0.5f && anchorMax_.x_ == 0.5f && (!pivotSet_ || pivot_.x_ == 0.5f))
  1256. return HA_CENTER;
  1257. else if (anchorMin_.x_ == 1.0f && anchorMax_.x_ == 1.0f && (!pivotSet_ || pivot_.x_ == 1.0f))
  1258. return HA_RIGHT;
  1259. return HA_CUSTOM;
  1260. }
  1261. VerticalAlignment UIElement::GetVerticalAlignment() const
  1262. {
  1263. if (anchorMin_.y_ == 0.0f && anchorMax_.y_ == 0.0f && (!pivotSet_ || pivot_.y_ == 0.0f))
  1264. return VA_TOP;
  1265. else if (anchorMin_.y_ == 0.5f && anchorMax_.y_ == 0.5f && (!pivotSet_ || pivot_.y_ == 0.5f))
  1266. return VA_CENTER;
  1267. else if (anchorMin_.y_ == 1.0f && anchorMax_.y_ == 1.0f && (!pivotSet_ || pivot_.y_ == 1.0f))
  1268. return VA_BOTTOM;
  1269. return VA_CUSTOM;
  1270. }
  1271. float UIElement::GetDerivedOpacity() const
  1272. {
  1273. if (!useDerivedOpacity_)
  1274. return opacity_;
  1275. if (opacityDirty_)
  1276. {
  1277. derivedOpacity_ = opacity_;
  1278. const UIElement* parent = parent_;
  1279. while (parent)
  1280. {
  1281. derivedOpacity_ *= parent->opacity_;
  1282. parent = parent->parent_;
  1283. }
  1284. opacityDirty_ = false;
  1285. }
  1286. return derivedOpacity_;
  1287. }
  1288. bool UIElement::HasFocus() const
  1289. {
  1290. auto* ui = GetSubsystem<UI>();
  1291. return ui ? ui->GetFocusElement() == this : false;
  1292. }
  1293. bool UIElement::IsChildOf(UIElement* element) const
  1294. {
  1295. UIElement* parent = parent_;
  1296. while (parent)
  1297. {
  1298. if (parent == element)
  1299. return true;
  1300. parent = parent->parent_;
  1301. }
  1302. return false;
  1303. }
  1304. bool UIElement::IsVisibleEffective() const
  1305. {
  1306. bool visible = visible_;
  1307. const UIElement* element = parent_;
  1308. // Traverse the parent chain
  1309. while (visible && element)
  1310. {
  1311. visible &= element->visible_;
  1312. element = element->parent_;
  1313. }
  1314. return visible;
  1315. }
  1316. const String& UIElement::GetAppliedStyle() const
  1317. {
  1318. return appliedStyle_ == GetTypeName() ? String::EMPTY : appliedStyle_;
  1319. }
  1320. XMLFile* UIElement::GetDefaultStyle(bool recursiveUp) const
  1321. {
  1322. if (recursiveUp)
  1323. {
  1324. const UIElement* element = this;
  1325. while (element)
  1326. {
  1327. if (element->defaultStyle_)
  1328. return element->defaultStyle_;
  1329. element = element->parent_;
  1330. }
  1331. return nullptr;
  1332. }
  1333. else
  1334. return defaultStyle_;
  1335. }
  1336. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  1337. {
  1338. dest.Clear();
  1339. if (!recursive)
  1340. {
  1341. dest.Reserve(children_.Size());
  1342. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1343. dest.Push(*i);
  1344. }
  1345. else
  1346. GetChildrenRecursive(dest);
  1347. }
  1348. unsigned UIElement::GetNumChildren(bool recursive) const
  1349. {
  1350. if (!recursive)
  1351. return children_.Size();
  1352. else
  1353. {
  1354. unsigned allChildren = children_.Size();
  1355. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1356. allChildren += (*i)->GetNumChildren(true);
  1357. return allChildren;
  1358. }
  1359. }
  1360. UIElement* UIElement::GetChild(unsigned index) const
  1361. {
  1362. return index < children_.Size() ? children_[index] : nullptr;
  1363. }
  1364. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  1365. {
  1366. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1367. {
  1368. if ((*i)->name_ == name)
  1369. return *i;
  1370. if (recursive)
  1371. {
  1372. UIElement* element = (*i)->GetChild(name, true);
  1373. if (element)
  1374. return element;
  1375. }
  1376. }
  1377. return nullptr;
  1378. }
  1379. UIElement* UIElement::GetChild(const StringHash& key, const Variant& value, bool recursive) const
  1380. {
  1381. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1382. {
  1383. const Variant& varValue = (*i)->GetVar(key);
  1384. if (value != Variant::EMPTY ? varValue == value : varValue != Variant::EMPTY)
  1385. return *i;
  1386. if (recursive)
  1387. {
  1388. UIElement* element = (*i)->GetChild(key, value, true);
  1389. if (element)
  1390. return element;
  1391. }
  1392. }
  1393. return nullptr;
  1394. }
  1395. UIElement* UIElement::GetRoot() const
  1396. {
  1397. UIElement* root = parent_;
  1398. if (!root)
  1399. return nullptr;
  1400. while (root->GetParent())
  1401. root = root->GetParent();
  1402. return root;
  1403. }
  1404. const Color& UIElement::GetDerivedColor() const
  1405. {
  1406. if (derivedColorDirty_)
  1407. {
  1408. derivedColor_ = colors_[C_TOPLEFT];
  1409. derivedColor_.a_ *= GetDerivedOpacity();
  1410. derivedColorDirty_ = false;
  1411. }
  1412. return derivedColor_;
  1413. }
  1414. const Variant& UIElement::GetVar(const StringHash& key) const
  1415. {
  1416. VariantMap::ConstIterator i = vars_.Find(key);
  1417. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1418. }
  1419. bool UIElement::HasTag(const String& tag) const
  1420. {
  1421. return tags_.Contains(tag);
  1422. }
  1423. void UIElement::GetChildrenWithTag(PODVector<UIElement*>& dest, const String& tag, bool recursive) const
  1424. {
  1425. dest.Clear();
  1426. if (!recursive)
  1427. {
  1428. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1429. {
  1430. UIElement* element = *i;
  1431. if (element->HasTag(tag))
  1432. dest.Push(element);
  1433. }
  1434. }
  1435. else
  1436. GetChildrenWithTagRecursive(dest, tag);
  1437. }
  1438. PODVector<UIElement*> UIElement::GetChildrenWithTag(const String& tag, bool recursive) const
  1439. {
  1440. PODVector<UIElement*> dest;
  1441. GetChildrenWithTag(dest, tag, recursive);
  1442. return dest;
  1443. }
  1444. void UIElement::GetChildrenWithTagRecursive(PODVector<UIElement*>& dest, const String& tag) const
  1445. {
  1446. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1447. {
  1448. UIElement* element = *i;
  1449. if (element->HasTag(tag))
  1450. dest.Push(element);
  1451. if (!element->children_.Empty())
  1452. element->GetChildrenWithTagRecursive(dest, tag);
  1453. }
  1454. }
  1455. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  1456. {
  1457. if (isScreen)
  1458. position = ScreenToElement(position);
  1459. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  1460. }
  1461. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  1462. {
  1463. // If child elements are clipped, no need to expand the rect
  1464. if (clipChildren_)
  1465. return IsInside(position, isScreen);
  1466. if (!isScreen)
  1467. position = ElementToScreen(position);
  1468. IntRect combined = GetCombinedScreenRect();
  1469. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  1470. position.y_ < combined.bottom_;
  1471. }
  1472. IntRect UIElement::GetCombinedScreenRect()
  1473. {
  1474. IntVector2 screenPosition(GetScreenPosition());
  1475. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  1476. if (!clipChildren_)
  1477. {
  1478. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1479. {
  1480. IntRect childCombined((*i)->GetCombinedScreenRect());
  1481. if (childCombined.left_ < combined.left_)
  1482. combined.left_ = childCombined.left_;
  1483. if (childCombined.right_ > combined.right_)
  1484. combined.right_ = childCombined.right_;
  1485. if (childCombined.top_ < combined.top_)
  1486. combined.top_ = childCombined.top_;
  1487. if (childCombined.bottom_ > combined.bottom_)
  1488. combined.bottom_ = childCombined.bottom_;
  1489. }
  1490. }
  1491. return combined;
  1492. }
  1493. void UIElement::SortChildren()
  1494. {
  1495. if (sortChildren_ && sortOrderDirty_)
  1496. {
  1497. // Only sort when there is no layout
  1498. /// \todo Order is not stable when children have same priorities
  1499. if (layoutMode_ == LM_FREE)
  1500. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1501. sortOrderDirty_ = false;
  1502. }
  1503. }
  1504. void UIElement::SetChildOffset(const IntVector2& offset)
  1505. {
  1506. if (offset != childOffset_)
  1507. {
  1508. childOffset_ = offset;
  1509. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1510. (*i)->MarkDirty();
  1511. }
  1512. }
  1513. void UIElement::SetHovering(bool enable)
  1514. {
  1515. hovering_ = enable;
  1516. }
  1517. void UIElement::AdjustScissor(IntRect& currentScissor)
  1518. {
  1519. if (clipChildren_)
  1520. {
  1521. IntVector2 screenPos = GetScreenPosition();
  1522. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1523. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1524. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1525. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1526. if (currentScissor.right_ < currentScissor.left_)
  1527. currentScissor.right_ = currentScissor.left_;
  1528. if (currentScissor.bottom_ < currentScissor.top_)
  1529. currentScissor.bottom_ = currentScissor.top_;
  1530. }
  1531. }
  1532. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData,
  1533. IntRect currentScissor)
  1534. {
  1535. Vector2 floatOffset((float)offset.x_, (float)offset.y_);
  1536. unsigned initialSize = vertexData.Size();
  1537. GetBatches(batches, vertexData, currentScissor);
  1538. for (unsigned i = initialSize; i < vertexData.Size(); i += 6)
  1539. {
  1540. vertexData[i] += floatOffset.x_;
  1541. vertexData[i + 1] += floatOffset.y_;
  1542. }
  1543. AdjustScissor(currentScissor);
  1544. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1545. {
  1546. if ((*i)->IsVisible())
  1547. (*i)->GetBatchesWithOffset(offset, batches, vertexData, currentScissor);
  1548. }
  1549. }
  1550. UIElement* UIElement::GetElementEventSender() const
  1551. {
  1552. auto* element = const_cast<UIElement*>(this);
  1553. if (elementEventSender_)
  1554. return element;
  1555. while (element->parent_)
  1556. {
  1557. element = element->parent_;
  1558. if (element->elementEventSender_)
  1559. return element;
  1560. }
  1561. // If no predefined element event sender in the parental chain, return ultimate root element
  1562. return element;
  1563. }
  1564. IntVector2 UIElement::GetEffectiveMinSize() const
  1565. {
  1566. if (IsFixedSize() || layoutMode_ == LM_FREE || layoutMinSize_ == IntVector2::ZERO)
  1567. return minSize_;
  1568. else
  1569. return IntVector2(Max(minSize_.x_, layoutMinSize_.x_), Max(minSize_.y_, layoutMinSize_.y_));
  1570. }
  1571. void UIElement::OnAttributeAnimationAdded()
  1572. {
  1573. if (attributeAnimationInfos_.Size() == 1)
  1574. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UIElement, HandlePostUpdate));
  1575. }
  1576. void UIElement::OnAttributeAnimationRemoved()
  1577. {
  1578. if (attributeAnimationInfos_.Empty())
  1579. UnsubscribeFromEvent(E_POSTUPDATE);
  1580. }
  1581. Animatable* UIElement::FindAttributeAnimationTarget(const String& name, String& outName)
  1582. {
  1583. Vector<String> names = name.Split('/');
  1584. // Only attribute name
  1585. if (names.Size() == 1)
  1586. {
  1587. outName = name;
  1588. return this;
  1589. }
  1590. else
  1591. {
  1592. // Name must in following format: "#0/#1/attribute"
  1593. UIElement* element = this;
  1594. for (unsigned i = 0; i < names.Size() - 1; ++i)
  1595. {
  1596. if (names[i].Front() != '#')
  1597. {
  1598. URHO3D_LOGERROR("Invalid name " + name);
  1599. return nullptr;
  1600. }
  1601. String name = names[i].Substring(1, names[i].Length() - 1);
  1602. char s = name.Front();
  1603. if (s >= '0' && s <= '9')
  1604. {
  1605. unsigned index = ToUInt(name);
  1606. element = element->GetChild(index);
  1607. }
  1608. else
  1609. {
  1610. element = element->GetChild(name, true);
  1611. }
  1612. if (!element)
  1613. {
  1614. URHO3D_LOGERROR("Could not find element by name " + name);
  1615. return nullptr;
  1616. }
  1617. }
  1618. outName = names.Back();
  1619. return element;
  1620. }
  1621. }
  1622. void UIElement::MarkDirty()
  1623. {
  1624. positionDirty_ = true;
  1625. opacityDirty_ = true;
  1626. derivedColorDirty_ = true;
  1627. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1628. (*i)->MarkDirty();
  1629. }
  1630. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name) const
  1631. {
  1632. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName]", "attributeName:String");
  1633. if (!matchXPathQuery.SetVariable("attributeName", name))
  1634. return false;
  1635. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1636. return !removeElem || parent.RemoveChild(removeElem);
  1637. }
  1638. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name, const String& value) const
  1639. {
  1640. static XPathQuery matchXPathQuery
  1641. ("./attribute[@name=$attributeName and @value=$attributeValue]", "attributeName:String, attributeValue:String");
  1642. if (!matchXPathQuery.SetVariable("attributeName", name))
  1643. return false;
  1644. if (!matchXPathQuery.SetVariable("attributeValue", value))
  1645. return false;
  1646. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1647. return !removeElem || parent.RemoveChild(removeElem);
  1648. }
  1649. bool UIElement::FilterUIStyleAttributes(XMLElement& dest, const XMLElement& styleElem) const
  1650. {
  1651. // Remove style attribute only when its value is identical to the value stored in style file
  1652. String style = styleElem.GetAttribute("style");
  1653. if (!style.Empty())
  1654. {
  1655. if (style == dest.GetAttribute("style"))
  1656. {
  1657. if (!dest.RemoveAttribute("style"))
  1658. {
  1659. URHO3D_LOGWARNING("Could not remove style attribute");
  1660. return false;
  1661. }
  1662. }
  1663. }
  1664. // Perform the same action recursively for internal child elements stored in style file
  1665. XMLElement childDest = dest.GetChild("element");
  1666. XMLElement childElem = styleElem.GetChild("element");
  1667. while (childDest && childElem)
  1668. {
  1669. if (!childElem.GetBool("internal"))
  1670. {
  1671. URHO3D_LOGERROR("Invalid style file, style element can only contain internal child elements");
  1672. return false;
  1673. }
  1674. if (!FilterUIStyleAttributes(childDest, childElem))
  1675. return false;
  1676. childDest = childDest.GetNext("element");
  1677. childElem = childElem.GetNext("element");
  1678. }
  1679. // Remove style attribute when it is the same as its type, however, if it is an internal element then replace it to "none" instead
  1680. if (!dest.GetAttribute("style").Empty() && dest.GetAttribute("style") == dest.GetAttribute("type"))
  1681. {
  1682. if (internal_)
  1683. {
  1684. if (!dest.SetAttribute("style", "none"))
  1685. return false;
  1686. }
  1687. else
  1688. {
  1689. if (!dest.RemoveAttribute("style"))
  1690. return false;
  1691. }
  1692. }
  1693. return true;
  1694. }
  1695. bool UIElement::FilterImplicitAttributes(XMLElement& dest) const
  1696. {
  1697. // Remove positioning and sizing attributes when they are under the influence of layout mode
  1698. if (layoutMode_ != LM_FREE && !IsFixedWidth() && !IsFixedHeight())
  1699. {
  1700. if (!RemoveChildXML(dest, "Min Size"))
  1701. return false;
  1702. }
  1703. if (parent_ && parent_->layoutMode_ != LM_FREE)
  1704. {
  1705. if (!RemoveChildXML(dest, "Position"))
  1706. return false;
  1707. if (!RemoveChildXML(dest, "Size"))
  1708. return false;
  1709. }
  1710. return true;
  1711. }
  1712. void UIElement::UpdateAnchoring()
  1713. {
  1714. if (parent_ && enableAnchor_)
  1715. {
  1716. IntVector2 newSize;
  1717. newSize.x_ = (int)(parent_->size_.x_ * Clamp(anchorMax_.x_ - anchorMin_.x_, 0.0f, 1.0f)) + maxOffset_.x_ - minOffset_.x_;
  1718. newSize.y_ = (int)(parent_->size_.y_ * Clamp(anchorMax_.y_ - anchorMin_.y_, 0.0f, 1.0f)) + maxOffset_.y_ - minOffset_.y_;
  1719. if (position_ != minOffset_)
  1720. SetPosition(minOffset_);
  1721. if (size_ != newSize)
  1722. SetSize(newSize);
  1723. }
  1724. }
  1725. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1726. {
  1727. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1728. {
  1729. UIElement* element = *i;
  1730. dest.Push(element);
  1731. if (!element->children_.Empty())
  1732. element->GetChildrenRecursive(dest);
  1733. }
  1734. }
  1735. void UIElement::ApplyStyleRecursive(UIElement* element)
  1736. {
  1737. // If child element style file changes as result of being (re)parented and it has a defined style, apply it now
  1738. if (!element->appliedStyle_.Empty() && element->appliedStyleFile_.Get() != element->GetDefaultStyle())
  1739. {
  1740. element->SetStyle(element->appliedStyle_);
  1741. for (Vector<SharedPtr<UIElement> >::ConstIterator i = element->children_.Begin(); i != element->children_.End(); ++i)
  1742. element->ApplyStyleRecursive(*i);
  1743. }
  1744. }
  1745. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1746. {
  1747. int width = begin + end;
  1748. if (sizes.Empty())
  1749. return width;
  1750. for (unsigned i = 0; i < sizes.Size(); ++i)
  1751. {
  1752. // If calculating maximum size, and the default is specified, do not overflow it
  1753. if (sizes[i] == M_MAX_INT)
  1754. return M_MAX_INT;
  1755. width += sizes[i] + spacing;
  1756. }
  1757. // The last spacing is not needed
  1758. return width - spacing;
  1759. }
  1760. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1761. const PODVector<int>& maxSizes, const PODVector<float>& flexScales, int targetSize, int begin, int end, int spacing)
  1762. {
  1763. unsigned numChildren = sizes.Size();
  1764. if (!numChildren)
  1765. return;
  1766. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1767. if (targetTotalSize < 0)
  1768. targetTotalSize = 0;
  1769. int targetChildSize = targetTotalSize / numChildren;
  1770. int remainder = targetTotalSize % numChildren;
  1771. float add = (float)remainder / numChildren;
  1772. float acc = 0.0f;
  1773. // Initial pass
  1774. for (unsigned i = 0; i < numChildren; ++i)
  1775. {
  1776. auto targetSize = (int)(targetChildSize * flexScales[i]);
  1777. if (remainder)
  1778. {
  1779. acc += add;
  1780. if (acc >= 0.5f)
  1781. {
  1782. acc -= 1.0f;
  1783. ++targetSize;
  1784. --remainder;
  1785. }
  1786. }
  1787. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1788. }
  1789. // Error correction passes
  1790. for (;;)
  1791. {
  1792. int actualTotalSize = 0;
  1793. for (unsigned i = 0; i < numChildren; ++i)
  1794. actualTotalSize += sizes[i];
  1795. int error = targetTotalSize - actualTotalSize;
  1796. // Break if no error
  1797. if (!error)
  1798. break;
  1799. // Check which of the children can be resized to correct the error. If none, must break
  1800. PODVector<unsigned> resizable;
  1801. for (unsigned i = 0; i < numChildren; ++i)
  1802. {
  1803. if (error < 0 && sizes[i] > minSizes[i])
  1804. resizable.Push(i);
  1805. else if (error > 0 && sizes[i] < maxSizes[i])
  1806. resizable.Push(i);
  1807. }
  1808. if (resizable.Empty())
  1809. break;
  1810. int numResizable = resizable.Size();
  1811. int errorPerChild = error / numResizable;
  1812. remainder = (abs(error)) % numResizable;
  1813. add = (float)remainder / numResizable;
  1814. acc = 0.0f;
  1815. for (int i = 0; i < numResizable; ++i)
  1816. {
  1817. unsigned index = resizable[i];
  1818. int targetSize = sizes[index] + errorPerChild;
  1819. if (remainder)
  1820. {
  1821. acc += add;
  1822. if (acc >= 0.5f)
  1823. {
  1824. acc -= 1.0f;
  1825. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1826. --remainder;
  1827. }
  1828. }
  1829. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1830. }
  1831. }
  1832. // Calculate final positions and store the maximum child element size for optimizations
  1833. layoutElementMaxSize_ = 0;
  1834. int position = begin;
  1835. for (unsigned i = 0; i < numChildren; ++i)
  1836. {
  1837. positions[i] = position;
  1838. position += sizes[i] + spacing;
  1839. if (sizes[i] > layoutElementMaxSize_)
  1840. layoutElementMaxSize_ = sizes[i];
  1841. }
  1842. }
  1843. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1844. {
  1845. IntVector2 ret(IntVector2::ZERO);
  1846. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1847. switch (ha)
  1848. {
  1849. case HA_LEFT:
  1850. ret.x_ = layoutBorder_.left_;
  1851. break;
  1852. case HA_RIGHT:
  1853. ret.x_ = -layoutBorder_.right_;
  1854. break;
  1855. default:
  1856. break;
  1857. }
  1858. VerticalAlignment va = child->GetVerticalAlignment();
  1859. switch (va)
  1860. {
  1861. case VA_TOP:
  1862. ret.y_ = layoutBorder_.top_;
  1863. break;
  1864. case VA_BOTTOM:
  1865. ret.y_ = -layoutBorder_.bottom_;
  1866. break;
  1867. default:
  1868. break;
  1869. }
  1870. return ret;
  1871. }
  1872. void UIElement::Detach()
  1873. {
  1874. parent_ = nullptr;
  1875. MarkDirty();
  1876. }
  1877. void UIElement::VerifyChildAlignment()
  1878. {
  1879. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1880. {
  1881. // Reapply child alignments. If they are illegal compared to layout, they will be set left/top as neded
  1882. (*i)->SetHorizontalAlignment((*i)->GetHorizontalAlignment());
  1883. (*i)->SetVerticalAlignment((*i)->GetVerticalAlignment());
  1884. }
  1885. }
  1886. void UIElement::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1887. {
  1888. using namespace PostUpdate;
  1889. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1890. }
  1891. void UIElement::SetRenderTexture(Texture2D* texture)
  1892. {
  1893. if (auto* ui = GetSubsystem<UI>())
  1894. ui->SetElementRenderTexture(this, texture);
  1895. }
  1896. }