UIElement.cpp 59 KB

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