UIElement.cpp 58 KB

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