UIElement.cpp 58 KB

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