UIElement.cpp 59 KB

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