UIElement.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251
  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. PODVector<UIElement*> UIElement::GetChildren(bool recursive) const
  1349. {
  1350. PODVector<UIElement*> dest;
  1351. GetChildren(dest, recursive);
  1352. return dest;
  1353. }
  1354. unsigned UIElement::GetNumChildren(bool recursive) const
  1355. {
  1356. if (!recursive)
  1357. return children_.Size();
  1358. else
  1359. {
  1360. unsigned allChildren = children_.Size();
  1361. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1362. allChildren += (*i)->GetNumChildren(true);
  1363. return allChildren;
  1364. }
  1365. }
  1366. UIElement* UIElement::GetChild(unsigned index) const
  1367. {
  1368. return index < children_.Size() ? children_[index] : nullptr;
  1369. }
  1370. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  1371. {
  1372. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1373. {
  1374. if ((*i)->name_ == name)
  1375. return *i;
  1376. if (recursive)
  1377. {
  1378. UIElement* element = (*i)->GetChild(name, true);
  1379. if (element)
  1380. return element;
  1381. }
  1382. }
  1383. return nullptr;
  1384. }
  1385. UIElement* UIElement::GetChild(const StringHash& key, const Variant& value, bool recursive) const
  1386. {
  1387. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1388. {
  1389. const Variant& varValue = (*i)->GetVar(key);
  1390. if (value != Variant::EMPTY ? varValue == value : varValue != Variant::EMPTY)
  1391. return *i;
  1392. if (recursive)
  1393. {
  1394. UIElement* element = (*i)->GetChild(key, value, true);
  1395. if (element)
  1396. return element;
  1397. }
  1398. }
  1399. return nullptr;
  1400. }
  1401. UIElement* UIElement::GetRoot() const
  1402. {
  1403. UIElement* root = parent_;
  1404. if (!root)
  1405. return nullptr;
  1406. while (root->GetParent())
  1407. root = root->GetParent();
  1408. return root;
  1409. }
  1410. const Color& UIElement::GetDerivedColor() const
  1411. {
  1412. if (derivedColorDirty_)
  1413. {
  1414. derivedColor_ = colors_[C_TOPLEFT];
  1415. derivedColor_.a_ *= GetDerivedOpacity();
  1416. derivedColorDirty_ = false;
  1417. }
  1418. return derivedColor_;
  1419. }
  1420. const Variant& UIElement::GetVar(const StringHash& key) const
  1421. {
  1422. VariantMap::ConstIterator i = vars_.Find(key);
  1423. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1424. }
  1425. bool UIElement::HasTag(const String& tag) const
  1426. {
  1427. return tags_.Contains(tag);
  1428. }
  1429. void UIElement::GetChildrenWithTag(PODVector<UIElement*>& dest, const String& tag, bool recursive) const
  1430. {
  1431. dest.Clear();
  1432. if (!recursive)
  1433. {
  1434. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1435. {
  1436. UIElement* element = *i;
  1437. if (element->HasTag(tag))
  1438. dest.Push(element);
  1439. }
  1440. }
  1441. else
  1442. GetChildrenWithTagRecursive(dest, tag);
  1443. }
  1444. PODVector<UIElement*> UIElement::GetChildrenWithTag(const String& tag, bool recursive) const
  1445. {
  1446. PODVector<UIElement*> dest;
  1447. GetChildrenWithTag(dest, tag, recursive);
  1448. return dest;
  1449. }
  1450. void UIElement::GetChildrenWithTagRecursive(PODVector<UIElement*>& dest, const String& tag) const
  1451. {
  1452. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1453. {
  1454. UIElement* element = *i;
  1455. if (element->HasTag(tag))
  1456. dest.Push(element);
  1457. if (!element->children_.Empty())
  1458. element->GetChildrenWithTagRecursive(dest, tag);
  1459. }
  1460. }
  1461. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  1462. {
  1463. if (isScreen)
  1464. position = ScreenToElement(position);
  1465. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  1466. }
  1467. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  1468. {
  1469. // If child elements are clipped, no need to expand the rect
  1470. if (clipChildren_)
  1471. return IsInside(position, isScreen);
  1472. if (!isScreen)
  1473. position = ElementToScreen(position);
  1474. IntRect combined = GetCombinedScreenRect();
  1475. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  1476. position.y_ < combined.bottom_;
  1477. }
  1478. IntRect UIElement::GetCombinedScreenRect()
  1479. {
  1480. IntVector2 screenPosition(GetScreenPosition());
  1481. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  1482. if (!clipChildren_)
  1483. {
  1484. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1485. {
  1486. IntRect childCombined((*i)->GetCombinedScreenRect());
  1487. if (childCombined.left_ < combined.left_)
  1488. combined.left_ = childCombined.left_;
  1489. if (childCombined.right_ > combined.right_)
  1490. combined.right_ = childCombined.right_;
  1491. if (childCombined.top_ < combined.top_)
  1492. combined.top_ = childCombined.top_;
  1493. if (childCombined.bottom_ > combined.bottom_)
  1494. combined.bottom_ = childCombined.bottom_;
  1495. }
  1496. }
  1497. return combined;
  1498. }
  1499. void UIElement::SortChildren()
  1500. {
  1501. if (sortChildren_ && sortOrderDirty_)
  1502. {
  1503. // Only sort when there is no layout
  1504. /// \todo Order is not stable when children have same priorities
  1505. if (layoutMode_ == LM_FREE)
  1506. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1507. sortOrderDirty_ = false;
  1508. }
  1509. }
  1510. void UIElement::SetChildOffset(const IntVector2& offset)
  1511. {
  1512. if (offset != childOffset_)
  1513. {
  1514. childOffset_ = offset;
  1515. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1516. (*i)->MarkDirty();
  1517. }
  1518. }
  1519. void UIElement::SetHovering(bool enable)
  1520. {
  1521. hovering_ = enable;
  1522. }
  1523. void UIElement::AdjustScissor(IntRect& currentScissor)
  1524. {
  1525. if (clipChildren_)
  1526. {
  1527. IntVector2 screenPos = GetScreenPosition();
  1528. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1529. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1530. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1531. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1532. if (currentScissor.right_ < currentScissor.left_)
  1533. currentScissor.right_ = currentScissor.left_;
  1534. if (currentScissor.bottom_ < currentScissor.top_)
  1535. currentScissor.bottom_ = currentScissor.top_;
  1536. }
  1537. }
  1538. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData,
  1539. IntRect currentScissor)
  1540. {
  1541. Vector2 floatOffset((float)offset.x_, (float)offset.y_);
  1542. unsigned initialSize = vertexData.Size();
  1543. GetBatches(batches, vertexData, currentScissor);
  1544. for (unsigned i = initialSize; i < vertexData.Size(); i += 6)
  1545. {
  1546. vertexData[i] += floatOffset.x_;
  1547. vertexData[i + 1] += floatOffset.y_;
  1548. }
  1549. AdjustScissor(currentScissor);
  1550. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1551. {
  1552. if ((*i)->IsVisible())
  1553. (*i)->GetBatchesWithOffset(offset, batches, vertexData, currentScissor);
  1554. }
  1555. }
  1556. UIElement* UIElement::GetElementEventSender() const
  1557. {
  1558. auto* element = const_cast<UIElement*>(this);
  1559. if (elementEventSender_)
  1560. return element;
  1561. while (element->parent_)
  1562. {
  1563. element = element->parent_;
  1564. if (element->elementEventSender_)
  1565. return element;
  1566. }
  1567. // If no predefined element event sender in the parental chain, return ultimate root element
  1568. return element;
  1569. }
  1570. IntVector2 UIElement::GetEffectiveMinSize() const
  1571. {
  1572. if (IsFixedSize() || layoutMode_ == LM_FREE || layoutMinSize_ == IntVector2::ZERO)
  1573. return minSize_;
  1574. else
  1575. return IntVector2(Max(minSize_.x_, layoutMinSize_.x_), Max(minSize_.y_, layoutMinSize_.y_));
  1576. }
  1577. void UIElement::OnAttributeAnimationAdded()
  1578. {
  1579. if (attributeAnimationInfos_.Size() == 1)
  1580. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UIElement, HandlePostUpdate));
  1581. }
  1582. void UIElement::OnAttributeAnimationRemoved()
  1583. {
  1584. if (attributeAnimationInfos_.Empty())
  1585. UnsubscribeFromEvent(E_POSTUPDATE);
  1586. }
  1587. Animatable* UIElement::FindAttributeAnimationTarget(const String& name, String& outName)
  1588. {
  1589. Vector<String> names = name.Split('/');
  1590. // Only attribute name
  1591. if (names.Size() == 1)
  1592. {
  1593. outName = name;
  1594. return this;
  1595. }
  1596. else
  1597. {
  1598. // Name must in following format: "#0/#1/attribute"
  1599. UIElement* element = this;
  1600. for (unsigned i = 0; i < names.Size() - 1; ++i)
  1601. {
  1602. if (names[i].Front() != '#')
  1603. {
  1604. URHO3D_LOGERROR("Invalid name " + name);
  1605. return nullptr;
  1606. }
  1607. String name = names[i].Substring(1, names[i].Length() - 1);
  1608. char s = name.Front();
  1609. if (s >= '0' && s <= '9')
  1610. {
  1611. unsigned index = ToUInt(name);
  1612. element = element->GetChild(index);
  1613. }
  1614. else
  1615. {
  1616. element = element->GetChild(name, true);
  1617. }
  1618. if (!element)
  1619. {
  1620. URHO3D_LOGERROR("Could not find element by name " + name);
  1621. return nullptr;
  1622. }
  1623. }
  1624. outName = names.Back();
  1625. return element;
  1626. }
  1627. }
  1628. void UIElement::MarkDirty()
  1629. {
  1630. positionDirty_ = true;
  1631. opacityDirty_ = true;
  1632. derivedColorDirty_ = true;
  1633. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1634. (*i)->MarkDirty();
  1635. }
  1636. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name) const
  1637. {
  1638. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName]", "attributeName:String");
  1639. if (!matchXPathQuery.SetVariable("attributeName", name))
  1640. return false;
  1641. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1642. return !removeElem || parent.RemoveChild(removeElem);
  1643. }
  1644. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name, const String& value) const
  1645. {
  1646. static XPathQuery matchXPathQuery
  1647. ("./attribute[@name=$attributeName and @value=$attributeValue]", "attributeName:String, attributeValue:String");
  1648. if (!matchXPathQuery.SetVariable("attributeName", name))
  1649. return false;
  1650. if (!matchXPathQuery.SetVariable("attributeValue", value))
  1651. return false;
  1652. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1653. return !removeElem || parent.RemoveChild(removeElem);
  1654. }
  1655. bool UIElement::FilterUIStyleAttributes(XMLElement& dest, const XMLElement& styleElem) const
  1656. {
  1657. // Remove style attribute only when its value is identical to the value stored in style file
  1658. String style = styleElem.GetAttribute("style");
  1659. if (!style.Empty())
  1660. {
  1661. if (style == dest.GetAttribute("style"))
  1662. {
  1663. if (!dest.RemoveAttribute("style"))
  1664. {
  1665. URHO3D_LOGWARNING("Could not remove style attribute");
  1666. return false;
  1667. }
  1668. }
  1669. }
  1670. // Perform the same action recursively for internal child elements stored in style file
  1671. XMLElement childDest = dest.GetChild("element");
  1672. XMLElement childElem = styleElem.GetChild("element");
  1673. while (childDest && childElem)
  1674. {
  1675. if (!childElem.GetBool("internal"))
  1676. {
  1677. URHO3D_LOGERROR("Invalid style file, style element can only contain internal child elements");
  1678. return false;
  1679. }
  1680. if (!FilterUIStyleAttributes(childDest, childElem))
  1681. return false;
  1682. childDest = childDest.GetNext("element");
  1683. childElem = childElem.GetNext("element");
  1684. }
  1685. // Remove style attribute when it is the same as its type, however, if it is an internal element then replace it to "none" instead
  1686. if (!dest.GetAttribute("style").Empty() && dest.GetAttribute("style") == dest.GetAttribute("type"))
  1687. {
  1688. if (internal_)
  1689. {
  1690. if (!dest.SetAttribute("style", "none"))
  1691. return false;
  1692. }
  1693. else
  1694. {
  1695. if (!dest.RemoveAttribute("style"))
  1696. return false;
  1697. }
  1698. }
  1699. return true;
  1700. }
  1701. bool UIElement::FilterImplicitAttributes(XMLElement& dest) const
  1702. {
  1703. // Remove positioning and sizing attributes when they are under the influence of layout mode
  1704. if (layoutMode_ != LM_FREE && !IsFixedWidth() && !IsFixedHeight())
  1705. {
  1706. if (!RemoveChildXML(dest, "Min Size"))
  1707. return false;
  1708. }
  1709. if (parent_ && parent_->layoutMode_ != LM_FREE)
  1710. {
  1711. if (!RemoveChildXML(dest, "Position"))
  1712. return false;
  1713. if (!RemoveChildXML(dest, "Size"))
  1714. return false;
  1715. }
  1716. return true;
  1717. }
  1718. void UIElement::UpdateAnchoring()
  1719. {
  1720. if (parent_ && enableAnchor_)
  1721. {
  1722. IntVector2 newSize;
  1723. newSize.x_ = (int)(parent_->size_.x_ * Clamp(anchorMax_.x_ - anchorMin_.x_, 0.0f, 1.0f)) + maxOffset_.x_ - minOffset_.x_;
  1724. newSize.y_ = (int)(parent_->size_.y_ * Clamp(anchorMax_.y_ - anchorMin_.y_, 0.0f, 1.0f)) + maxOffset_.y_ - minOffset_.y_;
  1725. if (position_ != minOffset_)
  1726. SetPosition(minOffset_);
  1727. if (size_ != newSize)
  1728. SetSize(newSize);
  1729. }
  1730. }
  1731. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1732. {
  1733. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1734. {
  1735. UIElement* element = *i;
  1736. dest.Push(element);
  1737. if (!element->children_.Empty())
  1738. element->GetChildrenRecursive(dest);
  1739. }
  1740. }
  1741. void UIElement::ApplyStyleRecursive(UIElement* element)
  1742. {
  1743. // If child element style file changes as result of being (re)parented and it has a defined style, apply it now
  1744. if (!element->appliedStyle_.Empty() && element->appliedStyleFile_.Get() != element->GetDefaultStyle())
  1745. {
  1746. element->SetStyle(element->appliedStyle_);
  1747. for (Vector<SharedPtr<UIElement> >::ConstIterator i = element->children_.Begin(); i != element->children_.End(); ++i)
  1748. element->ApplyStyleRecursive(*i);
  1749. }
  1750. }
  1751. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1752. {
  1753. int width = begin + end;
  1754. if (sizes.Empty())
  1755. return width;
  1756. for (unsigned i = 0; i < sizes.Size(); ++i)
  1757. {
  1758. // If calculating maximum size, and the default is specified, do not overflow it
  1759. if (sizes[i] == M_MAX_INT)
  1760. return M_MAX_INT;
  1761. width += sizes[i] + spacing;
  1762. }
  1763. // The last spacing is not needed
  1764. return width - spacing;
  1765. }
  1766. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1767. const PODVector<int>& maxSizes, const PODVector<float>& flexScales, int targetSize, int begin, int end, int spacing)
  1768. {
  1769. unsigned numChildren = sizes.Size();
  1770. if (!numChildren)
  1771. return;
  1772. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1773. if (targetTotalSize < 0)
  1774. targetTotalSize = 0;
  1775. int targetChildSize = targetTotalSize / numChildren;
  1776. int remainder = targetTotalSize % numChildren;
  1777. float add = (float)remainder / numChildren;
  1778. float acc = 0.0f;
  1779. // Initial pass
  1780. for (unsigned i = 0; i < numChildren; ++i)
  1781. {
  1782. auto targetSize = (int)(targetChildSize * flexScales[i]);
  1783. if (remainder)
  1784. {
  1785. acc += add;
  1786. if (acc >= 0.5f)
  1787. {
  1788. acc -= 1.0f;
  1789. ++targetSize;
  1790. --remainder;
  1791. }
  1792. }
  1793. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1794. }
  1795. // Error correction passes
  1796. for (;;)
  1797. {
  1798. int actualTotalSize = 0;
  1799. for (unsigned i = 0; i < numChildren; ++i)
  1800. actualTotalSize += sizes[i];
  1801. int error = targetTotalSize - actualTotalSize;
  1802. // Break if no error
  1803. if (!error)
  1804. break;
  1805. // Check which of the children can be resized to correct the error. If none, must break
  1806. PODVector<unsigned> resizable;
  1807. for (unsigned i = 0; i < numChildren; ++i)
  1808. {
  1809. if (error < 0 && sizes[i] > minSizes[i])
  1810. resizable.Push(i);
  1811. else if (error > 0 && sizes[i] < maxSizes[i])
  1812. resizable.Push(i);
  1813. }
  1814. if (resizable.Empty())
  1815. break;
  1816. int numResizable = resizable.Size();
  1817. int errorPerChild = error / numResizable;
  1818. remainder = (abs(error)) % numResizable;
  1819. add = (float)remainder / numResizable;
  1820. acc = 0.0f;
  1821. for (int i = 0; i < numResizable; ++i)
  1822. {
  1823. unsigned index = resizable[i];
  1824. int targetSize = sizes[index] + errorPerChild;
  1825. if (remainder)
  1826. {
  1827. acc += add;
  1828. if (acc >= 0.5f)
  1829. {
  1830. acc -= 1.0f;
  1831. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1832. --remainder;
  1833. }
  1834. }
  1835. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1836. }
  1837. }
  1838. // Calculate final positions and store the maximum child element size for optimizations
  1839. layoutElementMaxSize_ = 0;
  1840. int position = begin;
  1841. for (unsigned i = 0; i < numChildren; ++i)
  1842. {
  1843. positions[i] = position;
  1844. position += sizes[i] + spacing;
  1845. if (sizes[i] > layoutElementMaxSize_)
  1846. layoutElementMaxSize_ = sizes[i];
  1847. }
  1848. }
  1849. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1850. {
  1851. IntVector2 ret(IntVector2::ZERO);
  1852. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1853. switch (ha)
  1854. {
  1855. case HA_LEFT:
  1856. ret.x_ = layoutBorder_.left_;
  1857. break;
  1858. case HA_RIGHT:
  1859. ret.x_ = -layoutBorder_.right_;
  1860. break;
  1861. default:
  1862. break;
  1863. }
  1864. VerticalAlignment va = child->GetVerticalAlignment();
  1865. switch (va)
  1866. {
  1867. case VA_TOP:
  1868. ret.y_ = layoutBorder_.top_;
  1869. break;
  1870. case VA_BOTTOM:
  1871. ret.y_ = -layoutBorder_.bottom_;
  1872. break;
  1873. default:
  1874. break;
  1875. }
  1876. return ret;
  1877. }
  1878. void UIElement::Detach()
  1879. {
  1880. parent_ = nullptr;
  1881. MarkDirty();
  1882. }
  1883. void UIElement::VerifyChildAlignment()
  1884. {
  1885. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1886. {
  1887. // Reapply child alignments. If they are illegal compared to layout, they will be set left/top as neded
  1888. (*i)->SetHorizontalAlignment((*i)->GetHorizontalAlignment());
  1889. (*i)->SetVerticalAlignment((*i)->GetVerticalAlignment());
  1890. }
  1891. }
  1892. void UIElement::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1893. {
  1894. using namespace PostUpdate;
  1895. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1896. }
  1897. void UIElement::SetRenderTexture(Texture2D* texture)
  1898. {
  1899. if (auto* ui = GetSubsystem<UI>())
  1900. ui->SetElementRenderTexture(this, texture);
  1901. }
  1902. }