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