UIElement.cpp 58 KB

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