UIElement.cpp 59 KB

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