UIElement.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029
  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 "../../Core/Context.h"
  23. #include "../../Core/CoreEvents.h"
  24. #include "../../Container/HashSet.h"
  25. #include "../../Container/Sort.h"
  26. #include "../../IO/Log.h"
  27. #include "../../Resource/ResourceCache.h"
  28. #include "../../Scene/ObjectAnimation.h"
  29. #include "Cursor.h"
  30. #include "UI.h"
  31. #include "UIElement.h"
  32. #include "UIEvents.h"
  33. #include "../../DebugNew.h"
  34. namespace Atomic
  35. {
  36. const char* horizontalAlignments[] =
  37. {
  38. "Left",
  39. "Center",
  40. "Right",
  41. 0
  42. };
  43. const char* verticalAlignments[] =
  44. {
  45. "Top",
  46. "Center",
  47. "Bottom",
  48. 0
  49. };
  50. static const char* focusModes[] =
  51. {
  52. "NotFocusable",
  53. "ResetFocus",
  54. "Focusable",
  55. "FocusableDefocusable",
  56. 0
  57. };
  58. static const char* dragDropModes[] =
  59. {
  60. "Disabled",
  61. "Source",
  62. "Target",
  63. "SourceAndTarget",
  64. 0
  65. };
  66. static const char* layoutModes[] =
  67. {
  68. "Free",
  69. "Horizontal",
  70. "Vertical",
  71. 0
  72. };
  73. extern const char* UI_CATEGORY;
  74. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  75. {
  76. return lhs->GetPriority() < rhs->GetPriority();
  77. }
  78. XPathQuery UIElement::styleXPathQuery_("/elements/element[@type=$typeName]", "typeName:String");
  79. UIElement::UIElement(Context* context) :
  80. Animatable(context),
  81. parent_(0),
  82. clipBorder_(IntRect::ZERO),
  83. priority_(0),
  84. bringToFront_(false),
  85. bringToBack_(true),
  86. clipChildren_(false),
  87. sortChildren_(true),
  88. useDerivedOpacity_(true),
  89. editable_(true),
  90. selected_(false),
  91. visible_(true),
  92. hovering_(false),
  93. internal_(false),
  94. focusMode_(FM_NOTFOCUSABLE),
  95. dragDropMode_(DD_DISABLED),
  96. layoutMode_(LM_FREE),
  97. layoutSpacing_(0),
  98. layoutBorder_(IntRect::ZERO),
  99. layoutFlexScale_(Vector2::ONE),
  100. resizeNestingLevel_(0),
  101. layoutNestingLevel_(0),
  102. layoutMinSize_(0),
  103. layoutMaxSize_(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. ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_FILE);
  139. ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  140. ACCESSOR_ATTRIBUTE("Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  141. ACCESSOR_ATTRIBUTE("Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  142. ACCESSOR_ATTRIBUTE("Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2(M_MAX_INT, M_MAX_INT), AM_FILE);
  143. ENUM_ACCESSOR_ATTRIBUTE("Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment,
  144. horizontalAlignments, HA_LEFT, AM_FILE);
  145. ENUM_ACCESSOR_ATTRIBUTE("Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments,
  146. VA_TOP, AM_FILE);
  147. ACCESSOR_ATTRIBUTE("Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  148. ACCESSOR_ATTRIBUTE("Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  149. ACCESSOR_ATTRIBUTE("Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  150. ACCESSOR_ATTRIBUTE("Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  151. ATTRIBUTE("Top Left Color", Color, color_[0], Color::WHITE, AM_FILE);
  152. ATTRIBUTE("Top Right Color", Color, color_[1], Color::WHITE, AM_FILE);
  153. ATTRIBUTE("Bottom Left Color", Color, color_[2], Color::WHITE, AM_FILE);
  154. ATTRIBUTE("Bottom Right Color", Color, color_[3], Color::WHITE, AM_FILE);
  155. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, false, AM_FILE);
  156. ACCESSOR_ATTRIBUTE("Is Editable", IsEditable, SetEditable, bool, true, AM_FILE);
  157. ACCESSOR_ATTRIBUTE("Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  158. ACCESSOR_ATTRIBUTE("Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  159. ACCESSOR_ATTRIBUTE("Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  160. ACCESSOR_ATTRIBUTE("Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  161. ACCESSOR_ATTRIBUTE("Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  162. ACCESSOR_ATTRIBUTE("Use Derived Opacity", GetUseDerivedOpacity, SetUseDerivedOpacity, bool, true, AM_FILE);
  163. ENUM_ACCESSOR_ATTRIBUTE("Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  164. ENUM_ACCESSOR_ATTRIBUTE("Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  165. ENUM_ACCESSOR_ATTRIBUTE("Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  166. ACCESSOR_ATTRIBUTE("Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  167. ACCESSOR_ATTRIBUTE("Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  168. ACCESSOR_ATTRIBUTE("Layout Flex Scale", GetLayoutFlexScale, SetLayoutFlexScale, Vector2, Vector2::ONE, AM_FILE);
  169. ACCESSOR_ATTRIBUTE("Indent", GetIndent, SetIndent, int, 0, AM_FILE);
  170. ACCESSOR_ATTRIBUTE("Indent Spacing", GetIndentSpacing, SetIndentSpacing, int, 16, AM_FILE);
  171. 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. 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. 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. 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. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  530. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  531. if (validatedSize != size_)
  532. {
  533. size_ = validatedSize;
  534. if (resizeNestingLevel_ == 1)
  535. {
  536. // Check if parent element's layout needs to be updated first
  537. if (parent_)
  538. parent_->UpdateLayout();
  539. MarkDirty();
  540. OnResize();
  541. UpdateLayout();
  542. using namespace Resized;
  543. VariantMap& eventData = GetEventDataMap();
  544. eventData[P_ELEMENT] = this;
  545. eventData[P_WIDTH] = size_.x_;
  546. eventData[P_HEIGHT] = size_.y_;
  547. SendEvent(E_RESIZED, eventData);
  548. }
  549. }
  550. --resizeNestingLevel_;
  551. }
  552. void UIElement::SetSize(int width, int height)
  553. {
  554. SetSize(IntVector2(width, height));
  555. }
  556. void UIElement::SetWidth(int width)
  557. {
  558. SetSize(IntVector2(width, size_.y_));
  559. }
  560. void UIElement::SetHeight(int height)
  561. {
  562. SetSize(IntVector2(size_.x_, height));
  563. }
  564. void UIElement::SetMinSize(const IntVector2& minSize)
  565. {
  566. minSize_.x_ = Max(minSize.x_, 0);
  567. minSize_.y_ = Max(minSize.y_, 0);
  568. SetSize(size_);
  569. }
  570. void UIElement::SetMinSize(int width, int height)
  571. {
  572. SetMinSize(IntVector2(width, height));
  573. }
  574. void UIElement::SetMinWidth(int width)
  575. {
  576. SetMinSize(IntVector2(width, minSize_.y_));
  577. }
  578. void UIElement::SetMinHeight(int height)
  579. {
  580. SetMinSize(IntVector2(minSize_.x_, height));
  581. }
  582. void UIElement::SetMaxSize(const IntVector2& maxSize)
  583. {
  584. maxSize_.x_ = Max(maxSize.x_, 0);
  585. maxSize_.y_ = Max(maxSize.y_, 0);
  586. SetSize(size_);
  587. }
  588. void UIElement::SetMaxSize(int width, int height)
  589. {
  590. SetMaxSize(IntVector2(width, height));
  591. }
  592. void UIElement::SetMaxWidth(int width)
  593. {
  594. SetMaxSize(IntVector2(width, maxSize_.y_));
  595. }
  596. void UIElement::SetMaxHeight(int height)
  597. {
  598. SetMaxSize(IntVector2(maxSize_.x_, height));
  599. }
  600. void UIElement::SetFixedSize(const IntVector2& size)
  601. {
  602. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  603. SetSize(size);
  604. }
  605. void UIElement::SetFixedSize(int width, int height)
  606. {
  607. SetFixedSize(IntVector2(width, height));
  608. }
  609. void UIElement::SetFixedWidth(int width)
  610. {
  611. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  612. SetWidth(width);
  613. }
  614. void UIElement::SetFixedHeight(int height)
  615. {
  616. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  617. SetHeight(height);
  618. }
  619. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  620. {
  621. SetHorizontalAlignment(hAlign);
  622. SetVerticalAlignment(vAlign);
  623. }
  624. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  625. {
  626. if (align != HA_LEFT && parent_ && parent_->GetLayoutMode() == LM_HORIZONTAL)
  627. {
  628. LOGWARNING("Forcing left alignment because parent element has horizontal layout");
  629. align = HA_LEFT;
  630. }
  631. if (horizontalAlignment_ != align)
  632. {
  633. horizontalAlignment_ = align;
  634. MarkDirty();
  635. }
  636. }
  637. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  638. {
  639. if (align != VA_TOP && parent_ && parent_->GetLayoutMode() == LM_VERTICAL)
  640. {
  641. LOGWARNING("Forcing top alignment because parent element has vertical layout");
  642. align = VA_TOP;
  643. }
  644. if (verticalAlignment_ != align)
  645. {
  646. verticalAlignment_ = align;
  647. MarkDirty();
  648. }
  649. }
  650. void UIElement::SetClipBorder(const IntRect& rect)
  651. {
  652. clipBorder_.left_ = Max(rect.left_, 0);
  653. clipBorder_.top_ = Max(rect.top_, 0);
  654. clipBorder_.right_ = Max(rect.right_, 0);
  655. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  656. }
  657. void UIElement::SetColor(const Color& color)
  658. {
  659. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  660. color_[i] = color;
  661. colorGradient_ = false;
  662. derivedColorDirty_ = true;
  663. }
  664. void UIElement::SetColor(Corner corner, const Color& color)
  665. {
  666. color_[corner] = color;
  667. colorGradient_ = false;
  668. derivedColorDirty_ = true;
  669. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  670. {
  671. if (i != corner && color_[i] != color_[corner])
  672. colorGradient_ = true;
  673. }
  674. }
  675. void UIElement::SetPriority(int priority)
  676. {
  677. priority_ = priority;
  678. if (parent_)
  679. parent_->sortOrderDirty_ = true;
  680. }
  681. void UIElement::SetOpacity(float opacity)
  682. {
  683. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  684. MarkDirty();
  685. }
  686. void UIElement::SetBringToFront(bool enable)
  687. {
  688. bringToFront_ = enable;
  689. }
  690. void UIElement::SetBringToBack(bool enable)
  691. {
  692. bringToBack_ = enable;
  693. }
  694. void UIElement::SetClipChildren(bool enable)
  695. {
  696. clipChildren_ = enable;
  697. }
  698. void UIElement::SetSortChildren(bool enable)
  699. {
  700. if (!sortChildren_ && enable)
  701. sortOrderDirty_ = true;
  702. sortChildren_ = enable;
  703. }
  704. void UIElement::SetUseDerivedOpacity(bool enable)
  705. {
  706. useDerivedOpacity_ = enable;
  707. }
  708. void UIElement::SetEnabled(bool enable)
  709. {
  710. enabled_ = enable;
  711. enabledPrev_ = enable;
  712. }
  713. void UIElement::SetDeepEnabled(bool enable)
  714. {
  715. enabled_ = enable;
  716. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  717. (*i)->SetDeepEnabled(enable);
  718. }
  719. void UIElement::ResetDeepEnabled()
  720. {
  721. enabled_ = enabledPrev_;
  722. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  723. (*i)->ResetDeepEnabled();
  724. }
  725. void UIElement::SetEnabledRecursive(bool enable)
  726. {
  727. enabled_ = enable;
  728. enabledPrev_ = enable;
  729. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  730. (*i)->SetEnabledRecursive(enable);
  731. }
  732. void UIElement::SetEditable(bool enable)
  733. {
  734. editable_ = enable;
  735. OnSetEditable();
  736. }
  737. void UIElement::SetFocusMode(FocusMode mode)
  738. {
  739. focusMode_ = mode;
  740. }
  741. void UIElement::SetFocus(bool enable)
  742. {
  743. // Invisible elements should not receive focus
  744. if (focusMode_ < FM_FOCUSABLE || !IsVisibleEffective())
  745. enable = false;
  746. UI* ui = GetSubsystem<UI>();
  747. if (enable)
  748. {
  749. if (ui->GetFocusElement() != this)
  750. ui->SetFocusElement(this);
  751. }
  752. else
  753. {
  754. if (ui->GetFocusElement() == this)
  755. ui->SetFocusElement(0);
  756. }
  757. }
  758. void UIElement::SetSelected(bool enable)
  759. {
  760. selected_ = enable;
  761. }
  762. void UIElement::SetVisible(bool enable)
  763. {
  764. if (enable != visible_)
  765. {
  766. visible_ = enable;
  767. // Parent's layout may change as a result of visibility change
  768. if (parent_)
  769. parent_->UpdateLayout();
  770. using namespace VisibleChanged;
  771. VariantMap& eventData = GetEventDataMap();
  772. eventData[P_ELEMENT] = this;
  773. eventData[P_VISIBLE] = visible_;
  774. SendEvent(E_VISIBLECHANGED, eventData);
  775. // If the focus element becomes effectively hidden, clear focus
  776. if (!enable)
  777. {
  778. UIElement* focusElement = GetSubsystem<UI>()->GetFocusElement();
  779. if (focusElement && !focusElement->IsVisibleEffective())
  780. focusElement->SetFocus(false);
  781. }
  782. }
  783. }
  784. void UIElement::SetDragDropMode(unsigned mode)
  785. {
  786. dragDropMode_ = mode;
  787. }
  788. bool UIElement::SetStyle(const String& styleName, XMLFile* file)
  789. {
  790. // If empty style was requested, replace with type name
  791. String actualStyleName = !styleName.Empty() ? styleName : GetTypeName();
  792. appliedStyle_ = actualStyleName;
  793. if (styleName == "none")
  794. return true;
  795. if (!file)
  796. {
  797. file = GetDefaultStyle();
  798. if (!file)
  799. return false;
  800. }
  801. else
  802. {
  803. // If a custom style file specified, remember it
  804. defaultStyle_ = file;
  805. }
  806. styleXPathQuery_.SetVariable("typeName", actualStyleName);
  807. XMLElement styleElem = file->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  808. return styleElem && SetStyle(styleElem);
  809. }
  810. bool UIElement::SetStyle(const XMLElement& element)
  811. {
  812. appliedStyle_ = element.GetAttribute("type");
  813. // Consider style attribute values as instance-level attribute default values
  814. return LoadXML(element, true);
  815. }
  816. bool UIElement::SetStyleAuto(XMLFile* file)
  817. {
  818. return SetStyle(String::EMPTY, file);
  819. }
  820. void UIElement::SetDefaultStyle(XMLFile* style)
  821. {
  822. defaultStyle_ = style;
  823. }
  824. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  825. {
  826. layoutMode_ = mode;
  827. layoutSpacing_ = Max(spacing, 0);
  828. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  829. VerifyChildAlignment();
  830. UpdateLayout();
  831. }
  832. void UIElement::SetLayoutMode(LayoutMode mode)
  833. {
  834. layoutMode_ = mode;
  835. VerifyChildAlignment();
  836. UpdateLayout();
  837. }
  838. void UIElement::SetLayoutSpacing(int spacing)
  839. {
  840. layoutSpacing_ = Max(spacing, 0);
  841. UpdateLayout();
  842. }
  843. void UIElement::SetLayoutBorder(const IntRect& border)
  844. {
  845. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  846. UpdateLayout();
  847. }
  848. void UIElement::SetLayoutFlexScale(const Vector2& scale)
  849. {
  850. layoutFlexScale_ = Vector2(Max(scale.x_, 0.0f), Max(scale.y_, 0.0f));
  851. }
  852. void UIElement::SetIndent(int indent)
  853. {
  854. indent_ = indent;
  855. if (parent_)
  856. parent_->UpdateLayout();
  857. UpdateLayout();
  858. OnIndentSet();
  859. }
  860. void UIElement::SetIndentSpacing(int indentSpacing)
  861. {
  862. indentSpacing_ = Max(indentSpacing, 0);
  863. if (parent_)
  864. parent_->UpdateLayout();
  865. UpdateLayout();
  866. OnIndentSet();
  867. }
  868. void UIElement::UpdateLayout()
  869. {
  870. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  871. return;
  872. // Prevent further updates while this update happens
  873. DisableLayoutUpdate();
  874. PODVector<int> positions;
  875. PODVector<int> sizes;
  876. PODVector<int> minSizes;
  877. PODVector<int> maxSizes;
  878. PODVector<float> flexScales;
  879. int baseIndentWidth = GetIndentWidth();
  880. if (layoutMode_ == LM_HORIZONTAL)
  881. {
  882. int minChildHeight = 0;
  883. for (unsigned i = 0; i < children_.Size(); ++i)
  884. {
  885. if (!children_[i]->IsVisible())
  886. continue;
  887. positions.Push(baseIndentWidth);
  888. unsigned indent = (unsigned)children_[i]->GetIndentWidth();
  889. sizes.Push(children_[i]->GetWidth() + indent);
  890. minSizes.Push(children_[i]->GetMinWidth() + indent);
  891. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  892. flexScales.Push(children_[i]->GetLayoutFlexScale().x_);
  893. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  894. }
  895. CalculateLayout(positions, sizes, minSizes, maxSizes, flexScales, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  896. layoutSpacing_);
  897. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  898. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  899. int minWidth =
  900. Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  901. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  902. // Respect fixed size if already set
  903. if (minSize_.x_ != maxSize_.x_)
  904. minSize_.x_ = minWidth;
  905. if (minSize_.y_ != maxSize_.y_)
  906. minSize_.y_ = minHeight;
  907. SetSize(width, height);
  908. // Validate the size before resizing child elements, in case of min/max limits
  909. width = size_.x_;
  910. height = size_.y_;
  911. unsigned j = 0;
  912. for (unsigned i = 0; i < children_.Size(); ++i)
  913. {
  914. if (!children_[i]->IsVisible())
  915. continue;
  916. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  917. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  918. ++j;
  919. }
  920. }
  921. else if (layoutMode_ == LM_VERTICAL)
  922. {
  923. int minChildWidth = 0;
  924. for (unsigned i = 0; i < children_.Size(); ++i)
  925. {
  926. if (!children_[i]->IsVisible())
  927. continue;
  928. positions.Push(0);
  929. sizes.Push(children_[i]->GetHeight());
  930. minSizes.Push(children_[i]->GetMinHeight());
  931. maxSizes.Push(children_[i]->GetMaxHeight());
  932. flexScales.Push(children_[i]->GetLayoutFlexScale().y_);
  933. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth() + children_[i]->GetIndentWidth());
  934. }
  935. CalculateLayout(positions, sizes, minSizes, maxSizes, flexScales, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  936. layoutSpacing_);
  937. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  938. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  939. int minHeight =
  940. Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  941. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  942. if (minSize_.x_ != maxSize_.x_)
  943. minSize_.x_ = minWidth;
  944. if (minSize_.y_ != maxSize_.y_)
  945. minSize_.y_ = minHeight;
  946. SetSize(width, height);
  947. width = size_.x_;
  948. height = size_.y_;
  949. unsigned j = 0;
  950. for (unsigned i = 0; i < children_.Size(); ++i)
  951. {
  952. if (!children_[i]->IsVisible())
  953. continue;
  954. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_ + baseIndentWidth, positions[j]);
  955. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  956. ++j;
  957. }
  958. }
  959. using namespace LayoutUpdated;
  960. VariantMap& eventData = GetEventDataMap();
  961. eventData[P_ELEMENT] = this;
  962. SendEvent(E_LAYOUTUPDATED, eventData);
  963. EnableLayoutUpdate();
  964. }
  965. void UIElement::DisableLayoutUpdate()
  966. {
  967. ++layoutNestingLevel_;
  968. }
  969. void UIElement::EnableLayoutUpdate()
  970. {
  971. --layoutNestingLevel_;
  972. }
  973. void UIElement::BringToFront()
  974. {
  975. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  976. UIElement* root = GetRoot();
  977. // If element is detached from hierarchy, this must be a no-op
  978. if (!root)
  979. return;
  980. UIElement* ptr = this;
  981. while (ptr && ptr->GetParent() != root)
  982. ptr = ptr->GetParent();
  983. if (!ptr || !ptr->GetBringToFront())
  984. return;
  985. // Get the highest priority used by all other top level elements, assign that to the new front element
  986. // and decrease others' priority where necessary. However, take into account only input-enabled
  987. // elements and those which have the BringToBack flag set
  988. HashSet<int> usedPriorities;
  989. int maxPriority = M_MIN_INT;
  990. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  991. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  992. {
  993. UIElement* other = *i;
  994. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  995. {
  996. int priority = other->GetPriority();
  997. // M_MAX_INT is used by popups and tooltips. Disregard these to avoid an "arms race" with the priorities
  998. if (priority == M_MAX_INT)
  999. continue;
  1000. usedPriorities.Insert(priority);
  1001. maxPriority = Max(priority, maxPriority);
  1002. }
  1003. }
  1004. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  1005. {
  1006. ptr->SetPriority(maxPriority);
  1007. int minPriority = maxPriority;
  1008. while (usedPriorities.Contains(minPriority))
  1009. --minPriority;
  1010. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  1011. {
  1012. UIElement* other = *i;
  1013. int priority = other->GetPriority();
  1014. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  1015. other->SetPriority(priority - 1);
  1016. }
  1017. }
  1018. }
  1019. UIElement* UIElement::CreateChild(StringHash type, const String& name, unsigned index)
  1020. {
  1021. // Check that creation succeeds and that the object in fact is a UI element
  1022. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  1023. if (!newElement)
  1024. {
  1025. LOGERROR("Could not create unknown UI element type " + type.ToString());
  1026. return 0;
  1027. }
  1028. if (!name.Empty())
  1029. newElement->SetName(name);
  1030. InsertChild(index, newElement);
  1031. return newElement;
  1032. }
  1033. void UIElement::AddChild(UIElement* element)
  1034. {
  1035. InsertChild(M_MAX_UNSIGNED, element);
  1036. }
  1037. void UIElement::InsertChild(unsigned index, UIElement* element)
  1038. {
  1039. // Check for illegal or redundant parent assignment
  1040. if (!element || element == this || element->parent_ == this)
  1041. return;
  1042. // Check for possible cyclic parent assignment
  1043. UIElement* parent = parent_;
  1044. while (parent)
  1045. {
  1046. if (parent == element)
  1047. return;
  1048. parent = parent->parent_;
  1049. }
  1050. // Add first, then remove from old parent, to ensure the element does not get deleted
  1051. if (index >= children_.Size())
  1052. children_.Push(SharedPtr<UIElement>(element));
  1053. else
  1054. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  1055. XMLFile* previousStyleFile = element->GetDefaultStyle();
  1056. element->Remove();
  1057. if (sortChildren_)
  1058. sortOrderDirty_ = true;
  1059. element->parent_ = this;
  1060. element->MarkDirty();
  1061. // If child element did not already have a style file, but has specified a style name, apply it now
  1062. if (!previousStyleFile && !element->appliedStyle_.Empty() && GetDefaultStyle())
  1063. element->SetStyle(element->appliedStyle_);
  1064. VerifyChildAlignment();
  1065. UpdateLayout();
  1066. // Send change event
  1067. UIElement* root = GetRoot();
  1068. UIElement* sender = GetElementEventSender();
  1069. if (sender)
  1070. {
  1071. using namespace ElementAdded;
  1072. VariantMap& eventData = GetEventDataMap();
  1073. eventData[P_ROOT] = root;
  1074. eventData[P_PARENT] = this;
  1075. eventData[P_ELEMENT] = element;
  1076. sender->SendEvent(E_ELEMENTADDED, eventData);
  1077. }
  1078. }
  1079. void UIElement::RemoveChild(UIElement* element, unsigned index)
  1080. {
  1081. for (unsigned i = index; i < children_.Size(); ++i)
  1082. {
  1083. if (children_[i] == element)
  1084. {
  1085. // Send change event if not already being destroyed
  1086. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1087. if (sender)
  1088. {
  1089. using namespace ElementRemoved;
  1090. VariantMap& eventData = GetEventDataMap();
  1091. eventData[P_ROOT] = GetRoot();
  1092. eventData[P_PARENT] = this;
  1093. eventData[P_ELEMENT] = element;
  1094. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1095. }
  1096. element->Detach();
  1097. children_.Erase(i);
  1098. UpdateLayout();
  1099. return;
  1100. }
  1101. }
  1102. }
  1103. void UIElement::RemoveChildAtIndex(unsigned index)
  1104. {
  1105. if (index >= children_.Size())
  1106. return;
  1107. // Send change event if not already being destroyed
  1108. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1109. if (sender)
  1110. {
  1111. using namespace ElementRemoved;
  1112. VariantMap& eventData = GetEventDataMap();
  1113. eventData[P_ROOT] = GetRoot();
  1114. eventData[P_PARENT] = this;
  1115. eventData[P_ELEMENT] = children_[index];
  1116. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1117. }
  1118. children_[index]->Detach();
  1119. children_.Erase(index);
  1120. UpdateLayout();
  1121. }
  1122. void UIElement::RemoveAllChildren()
  1123. {
  1124. UIElement* root = GetRoot();
  1125. UIElement* sender = Refs() > 0 ? GetElementEventSender() : 0;
  1126. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End();)
  1127. {
  1128. // Send change event if not already being destroyed
  1129. if (sender)
  1130. {
  1131. using namespace ElementRemoved;
  1132. VariantMap& eventData = GetEventDataMap();
  1133. eventData[P_ROOT] = root;
  1134. eventData[P_PARENT] = this;
  1135. eventData[P_ELEMENT] = (*i).Get();
  1136. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1137. }
  1138. (*i++)->Detach();
  1139. }
  1140. children_.Clear();
  1141. UpdateLayout();
  1142. }
  1143. void UIElement::Remove()
  1144. {
  1145. if (parent_)
  1146. parent_->RemoveChild(this);
  1147. }
  1148. unsigned UIElement::FindChild(UIElement* element) const
  1149. {
  1150. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  1151. return i != children_.End() ? (unsigned)(i - children_.Begin()) : M_MAX_UNSIGNED;
  1152. }
  1153. void UIElement::SetParent(UIElement* parent, unsigned index)
  1154. {
  1155. if (parent)
  1156. parent->InsertChild(index, this);
  1157. }
  1158. void UIElement::SetVar(StringHash key, const Variant& value)
  1159. {
  1160. vars_[key] = value;
  1161. }
  1162. void UIElement::SetInternal(bool enable)
  1163. {
  1164. internal_ = enable;
  1165. }
  1166. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  1167. {
  1168. traversalMode_ = traversalMode;
  1169. }
  1170. void UIElement::SetElementEventSender(bool flag)
  1171. {
  1172. elementEventSender_ = flag;
  1173. }
  1174. float UIElement::GetDerivedOpacity() const
  1175. {
  1176. if (!useDerivedOpacity_)
  1177. return opacity_;
  1178. if (opacityDirty_)
  1179. {
  1180. derivedOpacity_ = opacity_;
  1181. const UIElement* parent = parent_;
  1182. while (parent)
  1183. {
  1184. derivedOpacity_ *= parent->opacity_;
  1185. parent = parent->parent_;
  1186. }
  1187. opacityDirty_ = false;
  1188. }
  1189. return derivedOpacity_;
  1190. }
  1191. bool UIElement::HasFocus() const
  1192. {
  1193. return GetSubsystem<UI>()->GetFocusElement() == this;
  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. void UIElement::OnAttributeAnimationAdded()
  1428. {
  1429. if (attributeAnimationInfos_.Size() == 1)
  1430. SubscribeToEvent(E_POSTUPDATE, HANDLER(UIElement, HandlePostUpdate));
  1431. }
  1432. void UIElement::OnAttributeAnimationRemoved()
  1433. {
  1434. if (attributeAnimationInfos_.Empty())
  1435. UnsubscribeFromEvent(E_POSTUPDATE);
  1436. }
  1437. void UIElement::SetObjectAttributeAnimation(const String& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed)
  1438. {
  1439. Vector<String> names = name.Split('/');
  1440. // Only attribute name
  1441. if (names.Size() == 1)
  1442. SetAttributeAnimation(name, attributeAnimation, wrapMode, speed);
  1443. else
  1444. {
  1445. // Name must in following format: "#0/#1/attribute"
  1446. UIElement* element = this;
  1447. for (unsigned i = 0; i < names.Size() - 1; ++i)
  1448. {
  1449. if (names[i].Front() != '#')
  1450. {
  1451. LOGERROR("Invalid name " + name);
  1452. return;
  1453. }
  1454. unsigned index = (unsigned)ToInt(names[i].Substring(1, names[i].Length() - 1));
  1455. element = element->GetChild(index);
  1456. if (!element)
  1457. {
  1458. LOGERROR("Could not find element by name " + name);
  1459. return;
  1460. }
  1461. }
  1462. element->SetAttributeAnimation(names.Back(), attributeAnimation, wrapMode, speed);
  1463. }
  1464. }
  1465. void UIElement::MarkDirty()
  1466. {
  1467. positionDirty_ = true;
  1468. opacityDirty_ = true;
  1469. derivedColorDirty_ = true;
  1470. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1471. (*i)->MarkDirty();
  1472. }
  1473. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name) const
  1474. {
  1475. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName]", "attributeName:String");
  1476. if (!matchXPathQuery.SetVariable("attributeName", name))
  1477. return false;
  1478. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1479. return !removeElem || parent.RemoveChild(removeElem);
  1480. }
  1481. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name, const String& value) const
  1482. {
  1483. static XPathQuery matchXPathQuery
  1484. ("./attribute[@name=$attributeName and @value=$attributeValue]", "attributeName:String, attributeValue:String");
  1485. if (!matchXPathQuery.SetVariable("attributeName", name))
  1486. return false;
  1487. if (!matchXPathQuery.SetVariable("attributeValue", value))
  1488. return false;
  1489. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1490. return !removeElem || parent.RemoveChild(removeElem);
  1491. }
  1492. bool UIElement::FilterUIStyleAttributes(XMLElement& dest, const XMLElement& styleElem) const
  1493. {
  1494. // Remove style attribute only when its value is identical to the value stored in style file
  1495. String style = styleElem.GetAttribute("style");
  1496. if (!style.Empty())
  1497. {
  1498. if (style == dest.GetAttribute("style"))
  1499. {
  1500. if (!dest.RemoveAttribute("style"))
  1501. {
  1502. LOGWARNING("Could not remove style attribute");
  1503. return false;
  1504. }
  1505. }
  1506. }
  1507. // Perform the same action recursively for internal child elements stored in style file
  1508. XMLElement childDest = dest.GetChild("element");
  1509. XMLElement childElem = styleElem.GetChild("element");
  1510. while (childDest && childElem)
  1511. {
  1512. if (!childElem.GetBool("internal"))
  1513. {
  1514. LOGERROR("Invalid style file, style element can only contain internal child elements");
  1515. return false;
  1516. }
  1517. if (!FilterUIStyleAttributes(childDest, childElem))
  1518. return false;
  1519. childDest = childDest.GetNext("element");
  1520. childElem = childElem.GetNext("element");
  1521. }
  1522. // Remove style attribute when it is the same as its type, however, if it is an internal element then replace it to "none" instead
  1523. if (!dest.GetAttribute("style").Empty() && dest.GetAttribute("style") == dest.GetAttribute("type"))
  1524. {
  1525. if (internal_)
  1526. {
  1527. if (!dest.SetAttribute("style", "none"))
  1528. return false;
  1529. }
  1530. else
  1531. {
  1532. if (!dest.RemoveAttribute("style"))
  1533. return false;
  1534. }
  1535. }
  1536. return true;
  1537. }
  1538. bool UIElement::FilterImplicitAttributes(XMLElement& dest) const
  1539. {
  1540. // Remove positioning and sizing attributes when they are under the influence of layout mode
  1541. if (layoutMode_ != LM_FREE && !IsFixedWidth() && !IsFixedHeight())
  1542. {
  1543. if (!RemoveChildXML(dest, "Min Size"))
  1544. return false;
  1545. }
  1546. if (parent_ && parent_->layoutMode_ != LM_FREE)
  1547. {
  1548. if (!RemoveChildXML(dest, "Position"))
  1549. return false;
  1550. if (!RemoveChildXML(dest, "Size"))
  1551. return false;
  1552. }
  1553. return true;
  1554. }
  1555. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1556. {
  1557. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1558. {
  1559. UIElement* element = *i;
  1560. dest.Push(element);
  1561. if (!element->children_.Empty())
  1562. element->GetChildrenRecursive(dest);
  1563. }
  1564. }
  1565. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1566. {
  1567. int width = begin + end;
  1568. if (sizes.Empty())
  1569. return width;
  1570. for (unsigned i = 0; i < sizes.Size(); ++i)
  1571. {
  1572. // If calculating maximum size, and the default is specified, do not overflow it
  1573. if (sizes[i] == M_MAX_INT)
  1574. return M_MAX_INT;
  1575. width += sizes[i] + spacing;
  1576. }
  1577. // The last spacing is not needed
  1578. return width - spacing;
  1579. }
  1580. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1581. const PODVector<int>& maxSizes, const PODVector<float>& flexScales, int targetSize, int begin, int end, int spacing)
  1582. {
  1583. unsigned numChildren = sizes.Size();
  1584. if (!numChildren)
  1585. return;
  1586. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1587. if (targetTotalSize < 0)
  1588. targetTotalSize = 0;
  1589. int targetChildSize = targetTotalSize / numChildren;
  1590. int remainder = targetTotalSize % numChildren;
  1591. float add = (float)remainder / numChildren;
  1592. float acc = 0.0f;
  1593. // Initial pass
  1594. for (unsigned i = 0; i < numChildren; ++i)
  1595. {
  1596. int targetSize = (int)(targetChildSize * flexScales[i]);
  1597. if (remainder)
  1598. {
  1599. acc += add;
  1600. if (acc >= 0.5f)
  1601. {
  1602. acc -= 1.0f;
  1603. ++targetSize;
  1604. --remainder;
  1605. }
  1606. }
  1607. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1608. }
  1609. // Error correction passes
  1610. for (;;)
  1611. {
  1612. int actualTotalSize = 0;
  1613. for (unsigned i = 0; i < numChildren; ++i)
  1614. actualTotalSize += sizes[i];
  1615. int error = targetTotalSize - actualTotalSize;
  1616. // Break if no error
  1617. if (!error)
  1618. break;
  1619. // Check which of the children can be resized to correct the error. If none, must break
  1620. PODVector<unsigned> resizable;
  1621. for (unsigned i = 0; i < numChildren; ++i)
  1622. {
  1623. if (error < 0 && sizes[i] > minSizes[i])
  1624. resizable.Push(i);
  1625. else if (error > 0 && sizes[i] < maxSizes[i])
  1626. resizable.Push(i);
  1627. }
  1628. if (resizable.Empty())
  1629. break;
  1630. int numResizable = resizable.Size();
  1631. int errorPerChild = error / numResizable;
  1632. remainder = (abs(error)) % numResizable;
  1633. add = (float)remainder / numResizable;
  1634. acc = 0.0f;
  1635. for (int i = 0; i < numResizable; ++i)
  1636. {
  1637. unsigned index = resizable[i];
  1638. int targetSize = sizes[index] + errorPerChild;
  1639. if (remainder)
  1640. {
  1641. acc += add;
  1642. if (acc >= 0.5f)
  1643. {
  1644. acc -= 1.0f;
  1645. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1646. --remainder;
  1647. }
  1648. }
  1649. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1650. }
  1651. }
  1652. // Calculate final positions and store the minimum child element size
  1653. layoutMinSize_ = M_MAX_INT;
  1654. layoutMaxSize_ = 0;
  1655. int position = begin;
  1656. for (unsigned i = 0; i < numChildren; ++i)
  1657. {
  1658. positions[i] = position;
  1659. position += sizes[i] + spacing;
  1660. if (sizes[i] < layoutMinSize_)
  1661. layoutMinSize_ = sizes[i];
  1662. if (sizes[i] > layoutMaxSize_)
  1663. layoutMaxSize_ = sizes[i];
  1664. }
  1665. }
  1666. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1667. {
  1668. IntVector2 ret(IntVector2::ZERO);
  1669. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1670. switch (ha)
  1671. {
  1672. case HA_LEFT:
  1673. ret.x_ = layoutBorder_.left_;
  1674. break;
  1675. case HA_RIGHT:
  1676. ret.x_ = -layoutBorder_.right_;
  1677. break;
  1678. default:
  1679. break;
  1680. }
  1681. VerticalAlignment va = child->GetVerticalAlignment();
  1682. switch (va)
  1683. {
  1684. case VA_TOP:
  1685. ret.y_ = layoutBorder_.top_;
  1686. break;
  1687. case VA_BOTTOM:
  1688. ret.y_ = -layoutBorder_.bottom_;
  1689. break;
  1690. default:
  1691. break;
  1692. }
  1693. return ret;
  1694. }
  1695. void UIElement::Detach()
  1696. {
  1697. parent_ = 0;
  1698. MarkDirty();
  1699. }
  1700. void UIElement::VerifyChildAlignment()
  1701. {
  1702. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1703. {
  1704. // Reapply child alignments. If they are illegal compared to layout, they will be set left/top as neded
  1705. (*i)->SetHorizontalAlignment((*i)->GetHorizontalAlignment());
  1706. (*i)->SetVerticalAlignment((*i)->GetVerticalAlignment());
  1707. }
  1708. }
  1709. void UIElement::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1710. {
  1711. using namespace PostUpdate;
  1712. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1713. }
  1714. }