UIElement.cpp 58 KB

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