UIElement.cpp 61 KB

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