UIElement.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. //
  2. // Copyright (c) 2008-2013 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 "HashSet.h"
  25. #include "Log.h"
  26. #include "ResourceCache.h"
  27. #include "Sort.h"
  28. #include "StringUtils.h"
  29. #include "UI.h"
  30. #include "UIElement.h"
  31. #include "UIEvents.h"
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. static const char* horizontalAlignments[] =
  36. {
  37. "Left",
  38. "Center",
  39. "Right",
  40. 0
  41. };
  42. static const char* verticalAlignments[] =
  43. {
  44. "Top",
  45. "Center",
  46. "Bottom",
  47. 0
  48. };
  49. static const char* focusModes[] =
  50. {
  51. "NotFocusable",
  52. "ResetFocus",
  53. "Focusable",
  54. "FocusableDefocusable",
  55. 0
  56. };
  57. static const char* dragDropModes[] =
  58. {
  59. "Disabled",
  60. "Source",
  61. "Target",
  62. "SourceAndTarget",
  63. 0
  64. };
  65. static const char* layoutModes[] =
  66. {
  67. "Free",
  68. "Horizontal",
  69. "Vertical",
  70. 0
  71. };
  72. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  73. {
  74. return lhs->GetPriority() < rhs->GetPriority();
  75. }
  76. template<> HorizontalAlignment Variant::Get<HorizontalAlignment>() const
  77. {
  78. return (HorizontalAlignment)GetInt();
  79. }
  80. template<> VerticalAlignment Variant::Get<VerticalAlignment>() const
  81. {
  82. return (VerticalAlignment)GetInt();
  83. }
  84. template<> FocusMode Variant::Get<FocusMode>() const
  85. {
  86. return (FocusMode)GetInt();
  87. }
  88. template<> LayoutMode Variant::Get<LayoutMode>() const
  89. {
  90. return (LayoutMode)GetInt();
  91. }
  92. OBJECTTYPESTATIC(UIElement);
  93. UIElement::UIElement(Context* context) :
  94. Serializable(context),
  95. parent_(0),
  96. clipBorder_(IntRect::ZERO),
  97. priority_(0),
  98. bringToFront_(false),
  99. bringToBack_(true),
  100. clipChildren_(false),
  101. sortChildren_(true),
  102. active_(false),
  103. selected_(false),
  104. visible_(true),
  105. hovering_(false),
  106. internal_(false),
  107. focusMode_(FM_NOTFOCUSABLE),
  108. dragDropMode_(DD_DISABLED),
  109. layoutMode_(LM_FREE),
  110. layoutSpacing_(0),
  111. layoutBorder_(IntRect::ZERO),
  112. resizeNestingLevel_(0),
  113. layoutNestingLevel_(0),
  114. layoutMinSize_(0),
  115. position_(IntVector2::ZERO),
  116. size_(IntVector2::ZERO),
  117. minSize_(IntVector2::ZERO),
  118. maxSize_(M_MAX_INT, M_MAX_INT),
  119. childOffset_(IntVector2::ZERO),
  120. horizontalAlignment_(HA_LEFT),
  121. verticalAlignment_(VA_TOP),
  122. opacity_(1.0f),
  123. positionDirty_(true),
  124. opacityDirty_(true),
  125. derivedColorDirty_(true),
  126. sortOrderDirty_(false),
  127. colorGradient_(false)
  128. {
  129. }
  130. UIElement::~UIElement()
  131. {
  132. // If child elements have outside references, detach them
  133. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  134. {
  135. if (i->Refs() > 1)
  136. (*i)->Detach();
  137. }
  138. }
  139. void UIElement::RegisterObject(Context* context)
  140. {
  141. context->RegisterFactory<UIElement>();
  142. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_STRING, "Name", GetName, SetName, String, String(), AM_FILE);
  143. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  144. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  145. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  146. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2::ZERO, AM_FILE);
  147. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_FILE);
  148. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_FILE);
  149. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  150. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  151. ACCESSOR_ATTRIBUTE(UIElement, VAR_FLOAT, "Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  152. ATTRIBUTE(UIElement, VAR_COLOR, "Top Left Color", color_[0], Color::WHITE, AM_FILE);
  153. ATTRIBUTE(UIElement, VAR_COLOR, "Top Right Color", color_[1], Color::WHITE, AM_FILE);
  154. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Left Color", color_[2], Color::WHITE, AM_FILE);
  155. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Right Color", color_[3], Color::WHITE, AM_FILE);
  156. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Active", IsActive, SetActive, bool, false, AM_FILE);
  157. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  158. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  159. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  160. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  161. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  162. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  163. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  164. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  166. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  167. ATTRIBUTE(UIElement, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE);
  168. }
  169. void UIElement::ApplyAttributes()
  170. {
  171. colorGradient_ = false;
  172. derivedColorDirty_ = true;
  173. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  174. {
  175. if (color_[i] != color_[0])
  176. colorGradient_ = true;
  177. }
  178. }
  179. bool UIElement::LoadXML(const XMLElement& source)
  180. {
  181. return LoadXML(source, 0);
  182. }
  183. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile)
  184. {
  185. // Apply the style first, but only for non-internal elements
  186. if (!internal_ && styleFile)
  187. {
  188. // Use style override if defined, otherwise type name
  189. String styleName = source.GetAttribute("style");
  190. if (styleName.Empty())
  191. styleName = GetTypeName();
  192. SetStyle(styleFile, styleName);
  193. }
  194. // Then load rest of the attributes from the source
  195. if (!Serializable::LoadXML(source))
  196. return false;
  197. unsigned nextInternalChild = 0;
  198. // Load child elements. Internal elements are not to be created as they already exist
  199. XMLElement childElem = source.GetChild("element");
  200. while (childElem)
  201. {
  202. bool internalElem = childElem.GetBool("internal");
  203. String typeName = childElem.GetAttribute("type");
  204. if (typeName.Empty())
  205. typeName = "UIElement";
  206. UIElement* child = 0;
  207. if (!internalElem)
  208. child = CreateChild(ShortStringHash(typeName));
  209. else
  210. {
  211. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  212. {
  213. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  214. {
  215. child = children_[i];
  216. nextInternalChild = i + 1;
  217. break;
  218. }
  219. }
  220. if (!child)
  221. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  222. }
  223. if (child)
  224. {
  225. if (!child->LoadXML(childElem, styleFile))
  226. return false;
  227. }
  228. childElem = childElem.GetNext("element");
  229. }
  230. ApplyAttributes();
  231. return true;
  232. }
  233. bool UIElement::SaveXML(XMLElement& dest)
  234. {
  235. // Write type and internal flag
  236. if (!dest.SetString("type", GetTypeName()))
  237. return false;
  238. if (internal_)
  239. {
  240. if (!dest.SetBool("internal", internal_))
  241. return false;
  242. }
  243. // Write attributes
  244. if (!Serializable::SaveXML(dest))
  245. return false;
  246. // Write child elements
  247. for (unsigned i = 0; i < children_.Size(); ++i)
  248. {
  249. UIElement* element = children_[i];
  250. XMLElement childElem = dest.CreateChild("element");
  251. if (!element->SaveXML(childElem))
  252. return false;
  253. }
  254. return true;
  255. }
  256. void UIElement::Update(float timeStep)
  257. {
  258. }
  259. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor)
  260. {
  261. // Reset hovering for next frame
  262. hovering_ = false;
  263. }
  264. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  265. {
  266. hovering_ = true;
  267. }
  268. void UIElement::OnClick(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  269. {
  270. }
  271. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  272. {
  273. }
  274. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  275. {
  276. }
  277. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)
  278. {
  279. }
  280. bool UIElement::OnDragDropTest(UIElement* source)
  281. {
  282. return true;
  283. }
  284. bool UIElement::OnDragDropFinish(UIElement* source)
  285. {
  286. return true;
  287. }
  288. void UIElement::OnWheel(int delta, int buttons, int qualifiers)
  289. {
  290. }
  291. void UIElement::OnKey(int key, int buttons, int qualifiers)
  292. {
  293. }
  294. void UIElement::OnChar(unsigned c, int buttons, int qualifiers)
  295. {
  296. }
  297. void UIElement::OnResize()
  298. {
  299. }
  300. bool UIElement::LoadXML(Deserializer& source)
  301. {
  302. SharedPtr<XMLFile> xml(new XMLFile(context_));
  303. if (!xml->Load(source))
  304. return false;
  305. return LoadXML(xml->GetRoot());
  306. }
  307. bool UIElement::SaveXML(Serializer& dest)
  308. {
  309. SharedPtr<XMLFile> xml(new XMLFile(context_));
  310. XMLElement rootElem = xml->CreateRoot("element");
  311. if (!SaveXML(rootElem))
  312. return false;
  313. return xml->Save(dest);
  314. }
  315. void UIElement::SetName(const String& name)
  316. {
  317. name_ = name;
  318. }
  319. void UIElement::SetPosition(const IntVector2& position)
  320. {
  321. if (position != position_)
  322. {
  323. position_ = position;
  324. MarkDirty();
  325. }
  326. }
  327. void UIElement::SetPosition(int x, int y)
  328. {
  329. SetPosition(IntVector2(x, y));
  330. }
  331. void UIElement::SetSize(const IntVector2& size)
  332. {
  333. ++resizeNestingLevel_;
  334. IntVector2 validatedSize;
  335. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  336. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  337. if (validatedSize != size_)
  338. {
  339. size_ = validatedSize;
  340. if (resizeNestingLevel_ == 1)
  341. {
  342. // Check if parent element's layout needs to be updated first
  343. if (parent_)
  344. parent_->UpdateLayout();
  345. MarkDirty();
  346. OnResize();
  347. UpdateLayout();
  348. using namespace Resized;
  349. VariantMap eventData;
  350. eventData[P_ELEMENT] = (void*)this;
  351. eventData[P_WIDTH] = size_.x_;
  352. eventData[P_HEIGHT] = size_.y_;
  353. SendEvent(E_RESIZED, eventData);
  354. }
  355. }
  356. --resizeNestingLevel_;
  357. }
  358. void UIElement::SetSize(int width, int height)
  359. {
  360. SetSize(IntVector2(width, height));
  361. }
  362. void UIElement::SetWidth(int width)
  363. {
  364. SetSize(IntVector2(width, size_.y_));
  365. }
  366. void UIElement::SetHeight(int height)
  367. {
  368. SetSize(IntVector2(size_.x_, height));
  369. }
  370. void UIElement::SetMinSize(const IntVector2& minSize)
  371. {
  372. minSize_.x_ = Max(minSize.x_, 0);
  373. minSize_.y_ = Max(minSize.y_, 0);
  374. SetSize(size_);
  375. }
  376. void UIElement::SetMinSize(int width, int height)
  377. {
  378. SetMinSize(IntVector2(width, height));
  379. }
  380. void UIElement::SetMinWidth(int width)
  381. {
  382. SetMinSize(IntVector2(width, minSize_.y_));
  383. }
  384. void UIElement::SetMinHeight(int height)
  385. {
  386. SetMinSize(IntVector2(minSize_.x_, height));
  387. }
  388. void UIElement::SetMaxSize(const IntVector2& maxSize)
  389. {
  390. maxSize_.x_ = Max(maxSize.x_, 0);
  391. maxSize_.y_ = Max(maxSize.y_, 0);
  392. SetSize(size_);
  393. }
  394. void UIElement::SetMaxSize(int width, int height)
  395. {
  396. SetMaxSize(IntVector2(width, height));
  397. }
  398. void UIElement::SetMaxWidth(int width)
  399. {
  400. SetMaxSize(IntVector2(width, maxSize_.y_));
  401. }
  402. void UIElement::SetMaxHeight(int height)
  403. {
  404. SetMaxSize(IntVector2(maxSize_.x_, height));
  405. }
  406. void UIElement::SetFixedSize(const IntVector2& size)
  407. {
  408. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  409. SetSize(size);
  410. }
  411. void UIElement::SetFixedSize(int width, int height)
  412. {
  413. SetFixedSize(IntVector2(width, height));
  414. }
  415. void UIElement::SetFixedWidth(int width)
  416. {
  417. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  418. SetWidth(width);
  419. }
  420. void UIElement::SetFixedHeight(int height)
  421. {
  422. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  423. SetHeight(height);
  424. }
  425. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  426. {
  427. horizontalAlignment_ = hAlign;
  428. verticalAlignment_ = vAlign;
  429. MarkDirty();
  430. }
  431. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  432. {
  433. horizontalAlignment_ = align;
  434. MarkDirty();
  435. }
  436. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  437. {
  438. verticalAlignment_ = align;
  439. MarkDirty();
  440. }
  441. void UIElement::SetClipBorder(const IntRect& rect)
  442. {
  443. clipBorder_.left_ = Max(rect.left_, 0);
  444. clipBorder_.top_ = Max(rect.top_, 0);
  445. clipBorder_.right_ = Max(rect.right_, 0);
  446. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  447. }
  448. void UIElement::SetColor(const Color& color)
  449. {
  450. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  451. color_[i] = color;
  452. colorGradient_ = false;
  453. derivedColorDirty_ = true;
  454. }
  455. void UIElement::SetColor(Corner corner, const Color& color)
  456. {
  457. color_[corner] = color;
  458. colorGradient_ = false;
  459. derivedColorDirty_ = true;
  460. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  461. {
  462. if (i != corner && color_[i] != color_[corner])
  463. colorGradient_ = true;
  464. }
  465. }
  466. void UIElement::SetPriority(int priority)
  467. {
  468. priority_ = priority;
  469. if (parent_)
  470. parent_->sortOrderDirty_ = true;
  471. }
  472. void UIElement::SetOpacity(float opacity)
  473. {
  474. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  475. MarkDirty();
  476. }
  477. void UIElement::SetBringToFront(bool enable)
  478. {
  479. bringToFront_ = enable;
  480. }
  481. void UIElement::SetBringToBack(bool enable)
  482. {
  483. bringToBack_ = enable;
  484. }
  485. void UIElement::SetClipChildren(bool enable)
  486. {
  487. clipChildren_ = enable;
  488. }
  489. void UIElement::SetSortChildren(bool enable)
  490. {
  491. if (!sortChildren_ && enable)
  492. sortOrderDirty_ = true;
  493. sortChildren_ = enable;
  494. }
  495. void UIElement::SetActive(bool enable)
  496. {
  497. active_ = enable;
  498. }
  499. void UIElement::SetFocusMode(FocusMode mode)
  500. {
  501. focusMode_ = mode;
  502. }
  503. void UIElement::SetFocus(bool enable)
  504. {
  505. if (focusMode_ < FM_FOCUSABLE)
  506. enable = false;
  507. UI* ui = GetSubsystem<UI>();
  508. if (!ui)
  509. return;
  510. if (enable)
  511. {
  512. if (ui->GetFocusElement() != this)
  513. ui->SetFocusElement(this);
  514. }
  515. else
  516. {
  517. if (ui->GetFocusElement() == this)
  518. ui->SetFocusElement(0);
  519. }
  520. }
  521. void UIElement::SetSelected(bool enable)
  522. {
  523. selected_ = enable;
  524. }
  525. void UIElement::SetVisible(bool enable)
  526. {
  527. if (enable != visible_)
  528. {
  529. visible_ = enable;
  530. // Parent's layout may change as a result of visibility change
  531. if (parent_)
  532. parent_->UpdateLayout();
  533. using namespace VisibleChanged;
  534. VariantMap eventData;
  535. eventData[P_ELEMENT] = (void*)this;
  536. eventData[P_VISIBLE] = visible_;
  537. SendEvent(E_VISIBLECHANGED, eventData);
  538. }
  539. }
  540. void UIElement::SetDragDropMode(unsigned mode)
  541. {
  542. dragDropMode_ = mode;
  543. }
  544. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  545. {
  546. if (!file)
  547. return;
  548. XMLElement rootElem = file->GetRoot();
  549. XMLElement childElem = rootElem.GetChild("element");
  550. while (childElem)
  551. {
  552. if (typeName == childElem.GetAttribute("type"))
  553. {
  554. SetStyle(childElem);
  555. return;
  556. }
  557. childElem = childElem.GetNext("element");
  558. }
  559. }
  560. void UIElement::SetStyle(const XMLElement& element)
  561. {
  562. LoadXML(element);
  563. }
  564. void UIElement::SetStyleAuto(XMLFile* file)
  565. {
  566. SetStyle(file, GetTypeName());
  567. }
  568. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  569. {
  570. layoutMode_ = mode;
  571. layoutSpacing_ = Max(spacing, 0);
  572. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  573. UpdateLayout();
  574. }
  575. void UIElement::SetLayoutMode(LayoutMode mode)
  576. {
  577. layoutMode_ = mode;
  578. UpdateLayout();
  579. }
  580. void UIElement::SetLayoutSpacing(int spacing)
  581. {
  582. layoutSpacing_ = Max(spacing, 0);
  583. UpdateLayout();
  584. }
  585. void UIElement::SetLayoutBorder(const IntRect& border)
  586. {
  587. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  588. UpdateLayout();
  589. }
  590. void UIElement::UpdateLayout()
  591. {
  592. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  593. return;
  594. // Prevent further updates while this update happens
  595. DisableLayoutUpdate();
  596. PODVector<int> positions;
  597. PODVector<int> sizes;
  598. PODVector<int> minSizes;
  599. PODVector<int> maxSizes;
  600. if (layoutMode_ == LM_HORIZONTAL)
  601. {
  602. int minChildHeight = 0;
  603. for (unsigned i = 0; i < children_.Size(); ++i)
  604. {
  605. if (!children_[i]->IsVisible())
  606. continue;
  607. positions.Push(0);
  608. sizes.Push(children_[i]->GetWidth());
  609. minSizes.Push(children_[i]->GetMinWidth());
  610. maxSizes.Push(children_[i]->GetMaxWidth());
  611. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  612. }
  613. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  614. layoutSpacing_);
  615. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  616. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  617. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  618. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  619. // Respect fixed size if already set
  620. if (minSize_.x_ != maxSize_.x_)
  621. minSize_.x_ = minWidth;
  622. if (minSize_.y_ != maxSize_.y_)
  623. minSize_.y_ = minHeight;
  624. SetSize(width, height);
  625. // Validate the size before resizing child elements, in case of min/max limits
  626. width = size_.x_;
  627. height = size_.y_;
  628. unsigned j = 0;
  629. for (unsigned i = 0; i < children_.Size(); ++i)
  630. {
  631. if (!children_[i]->IsVisible())
  632. continue;
  633. children_[i]->SetHorizontalAlignment(HA_LEFT);
  634. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  635. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  636. ++j;
  637. }
  638. }
  639. else if (layoutMode_ == LM_VERTICAL)
  640. {
  641. int minChildWidth = 0;
  642. for (unsigned i = 0; i < children_.Size(); ++i)
  643. {
  644. if (!children_[i]->IsVisible())
  645. continue;
  646. positions.Push(0);
  647. sizes.Push(children_[i]->GetHeight());
  648. minSizes.Push(children_[i]->GetMinHeight());
  649. maxSizes.Push(children_[i]->GetMaxHeight());
  650. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth());
  651. }
  652. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  653. layoutSpacing_);
  654. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  655. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  656. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  657. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  658. if (minSize_.x_ != maxSize_.x_)
  659. minSize_.x_ = minWidth;
  660. if (minSize_.y_ != maxSize_.y_)
  661. minSize_.y_ = minHeight;
  662. SetSize(width, height);
  663. width = size_.x_;
  664. height = size_.y_;
  665. unsigned j = 0;
  666. for (unsigned i = 0; i < children_.Size(); ++i)
  667. {
  668. if (!children_[i]->IsVisible())
  669. continue;
  670. children_[i]->SetVerticalAlignment(VA_TOP);
  671. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  672. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  673. ++j;
  674. }
  675. }
  676. EnableLayoutUpdate();
  677. }
  678. void UIElement::DisableLayoutUpdate()
  679. {
  680. ++layoutNestingLevel_;
  681. }
  682. void UIElement::EnableLayoutUpdate()
  683. {
  684. --layoutNestingLevel_;
  685. }
  686. void UIElement::BringToFront()
  687. {
  688. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  689. UIElement* root = GetRoot();
  690. UIElement* ptr = this;
  691. while (ptr && ptr->GetParent() != root)
  692. ptr = ptr->GetParent();
  693. if (!ptr || !ptr->GetBringToFront())
  694. return;
  695. // Get the highest priority used by all other top level elements, assign that to the new front element
  696. // and decrease others' priority where necessary. However, take into account only active (enabled)
  697. // elements and those which have the BringToBack flag set
  698. HashSet<int> usedPriorities;
  699. int maxPriority = M_MIN_INT;
  700. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  701. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  702. {
  703. UIElement* other = *i;
  704. if (other->IsActive() && other->bringToBack_ && other != ptr)
  705. {
  706. int priority = other->GetPriority();
  707. usedPriorities.Insert(priority);
  708. maxPriority = Max(priority, maxPriority);
  709. }
  710. }
  711. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  712. {
  713. ptr->SetPriority(maxPriority);
  714. int minPriority = maxPriority;
  715. while (usedPriorities.Contains(minPriority))
  716. --minPriority;
  717. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  718. {
  719. UIElement* other = *i;
  720. int priority = other->GetPriority();
  721. if (other->IsActive() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  722. other->SetPriority(priority - 1);
  723. }
  724. }
  725. }
  726. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name)
  727. {
  728. // Check that creation succeeds and that the object in fact is a UI element
  729. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  730. if (!newElement)
  731. {
  732. LOGERROR("Could not create unknown UI element type " + type.ToString());
  733. return 0;
  734. }
  735. newElement->SetName(name);
  736. AddChild(newElement);
  737. return newElement;
  738. }
  739. void UIElement::AddChild(UIElement* element)
  740. {
  741. InsertChild(children_.Size(), element);
  742. }
  743. void UIElement::InsertChild(unsigned index, UIElement* element)
  744. {
  745. // Check for illegal or redundant parent assignment
  746. if (!element || element == this || element->parent_ == this)
  747. return;
  748. // Check for possible cyclic parent assignment
  749. UIElement* parent = parent_;
  750. while (parent)
  751. {
  752. if (parent == element)
  753. return;
  754. parent = parent->parent_;
  755. }
  756. // Add first, then remove from old parent, to ensure the element does not get deleted
  757. if (index >= children_.Size())
  758. children_.Push(SharedPtr<UIElement>(element));
  759. else
  760. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  761. element->Remove();
  762. if (sortChildren_)
  763. sortOrderDirty_ = true;
  764. element->parent_ = this;
  765. element->MarkDirty();
  766. UpdateLayout();
  767. }
  768. void UIElement::RemoveChild(UIElement* element, unsigned index)
  769. {
  770. for (unsigned i = index; i < children_.Size(); ++i)
  771. {
  772. if (children_[i] == element)
  773. {
  774. element->Detach();
  775. children_.Erase(i);
  776. UpdateLayout();
  777. return;
  778. }
  779. }
  780. }
  781. void UIElement::RemoveAllChildren()
  782. {
  783. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  784. (*i++)->Detach();
  785. children_.Clear();
  786. }
  787. void UIElement::Remove()
  788. {
  789. if (parent_)
  790. parent_->RemoveChild(this);
  791. }
  792. void UIElement::SetParent(UIElement* parent)
  793. {
  794. if (parent)
  795. parent->AddChild(this);
  796. }
  797. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  798. {
  799. vars_[key] = value;
  800. }
  801. void UIElement::SetInternal(bool enable)
  802. {
  803. internal_ = enable;
  804. }
  805. IntVector2 UIElement::GetScreenPosition() const
  806. {
  807. if (positionDirty_)
  808. {
  809. IntVector2 pos = position_;
  810. const UIElement* parent = parent_;
  811. const UIElement* current = this;
  812. while (parent)
  813. {
  814. switch (current->horizontalAlignment_)
  815. {
  816. case HA_LEFT:
  817. pos.x_ += parent->position_.x_;
  818. break;
  819. case HA_CENTER:
  820. pos.x_ += parent->position_.x_ + parent->size_.x_ / 2 - current->size_.x_ / 2;
  821. break;
  822. case HA_RIGHT:
  823. pos.x_ += parent->position_.x_ + parent->size_.x_ - current->size_.x_;
  824. break;
  825. }
  826. switch (current->verticalAlignment_)
  827. {
  828. case VA_TOP:
  829. pos.y_ += parent->position_.y_;
  830. break;
  831. case VA_CENTER:
  832. pos.y_ += parent->position_.y_ + parent->size_.y_ / 2 - current->size_.y_ / 2;
  833. break;
  834. case VA_BOTTOM:
  835. pos.y_ += parent->position_.y_ + parent->size_.y_ - current->size_.y_;
  836. break;
  837. }
  838. pos += parent->childOffset_;
  839. current = parent;
  840. parent = parent->parent_;
  841. }
  842. screenPosition_ = pos;
  843. positionDirty_ = false;
  844. }
  845. return screenPosition_;
  846. }
  847. float UIElement::GetDerivedOpacity() const
  848. {
  849. if (opacityDirty_)
  850. {
  851. float opacity = opacity_;
  852. const UIElement* parent = parent_;
  853. while (parent)
  854. {
  855. opacity *= parent->opacity_;
  856. parent = parent->parent_;
  857. }
  858. derivedOpacity_ = opacity;
  859. opacityDirty_ = false;
  860. }
  861. return derivedOpacity_;
  862. }
  863. bool UIElement::HasFocus() const
  864. {
  865. UI* ui = GetSubsystem<UI>();
  866. if (!ui)
  867. return false;
  868. else
  869. return ui->GetFocusElement() == this;
  870. }
  871. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  872. {
  873. dest.Clear();
  874. if (!recursive)
  875. {
  876. dest.Reserve(children_.Size());
  877. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  878. dest.Push(*i);
  879. }
  880. else
  881. GetChildrenRecursive(dest);
  882. }
  883. unsigned UIElement::GetNumChildren(bool recursive) const
  884. {
  885. if (!recursive)
  886. return children_.Size();
  887. else
  888. {
  889. unsigned allChildren = children_.Size();
  890. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  891. allChildren += (*i)->GetNumChildren(true);
  892. return allChildren;
  893. }
  894. }
  895. UIElement* UIElement::GetChild(unsigned index) const
  896. {
  897. return index < children_.Size() ? children_[index] : (UIElement*)0;
  898. }
  899. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  900. {
  901. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  902. {
  903. if ((*i)->name_ == name)
  904. return *i;
  905. if (recursive)
  906. {
  907. UIElement* element = (*i)->GetChild(name, true);
  908. if (element)
  909. return element;
  910. }
  911. }
  912. return 0;
  913. }
  914. UIElement* UIElement::GetRoot() const
  915. {
  916. UIElement* root = parent_;
  917. if (!root)
  918. return 0;
  919. while (root->GetParent())
  920. root = root->GetParent();
  921. return root;
  922. }
  923. const Color& UIElement::GetDerivedColor() const
  924. {
  925. if (derivedColorDirty_)
  926. {
  927. derivedColor_ = color_[C_TOPLEFT];
  928. derivedColor_.a_ *= GetDerivedOpacity();
  929. derivedColorDirty_ = false;
  930. }
  931. return derivedColor_;
  932. }
  933. const Variant& UIElement::GetVar(ShortStringHash key) const
  934. {
  935. VariantMap::ConstIterator i = vars_.Find(key);
  936. if (i != vars_.End())
  937. return i->second_;
  938. else
  939. return Variant::EMPTY;
  940. }
  941. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  942. {
  943. return screenPosition - GetScreenPosition();
  944. }
  945. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  946. {
  947. return position + GetScreenPosition();
  948. }
  949. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  950. {
  951. if (isScreen)
  952. position = ScreenToElement(position);
  953. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  954. }
  955. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  956. {
  957. // If child elements are clipped, no need to expand the rect
  958. if (clipChildren_)
  959. return IsInside(position, isScreen);
  960. if (!isScreen)
  961. position = ElementToScreen(position);
  962. IntRect combined = GetCombinedScreenRect();
  963. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  964. position.y_ < combined.bottom_;
  965. }
  966. IntRect UIElement::GetCombinedScreenRect()
  967. {
  968. IntVector2 screenPosition(GetScreenPosition());
  969. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  970. if (!clipChildren_)
  971. {
  972. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  973. {
  974. IntVector2 childPos = (*i)->GetScreenPosition();
  975. const IntVector2& childSize = (*i)->GetSize();
  976. if (childPos.x_ < combined.left_)
  977. combined.left_ = childPos.x_;
  978. if (childPos.y_ < combined.top_)
  979. combined.top_ = childPos.y_;
  980. if (childPos.x_ + childSize.x_ > combined.right_)
  981. combined.right_ = childPos.x_ + childSize.x_;
  982. if (childPos.y_ + childSize.y_ > combined.bottom_)
  983. combined.bottom_ = childPos.y_ + childSize.y_;
  984. }
  985. }
  986. return combined;
  987. }
  988. void UIElement::SortChildren()
  989. {
  990. if (sortChildren_ && sortOrderDirty_)
  991. {
  992. Sort(children_.Begin(), children_.End(), CompareUIElements);
  993. sortOrderDirty_ = false;
  994. }
  995. }
  996. void UIElement::SetChildOffset(const IntVector2& offset)
  997. {
  998. if (offset != childOffset_)
  999. {
  1000. childOffset_ = offset;
  1001. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1002. (*i)->MarkDirty();
  1003. }
  1004. }
  1005. void UIElement::SetHovering(bool enable)
  1006. {
  1007. hovering_ = enable;
  1008. }
  1009. void UIElement::SetTempVisible(bool enable)
  1010. {
  1011. visible_ = enable;
  1012. }
  1013. void UIElement::AdjustScissor(IntRect& currentScissor)
  1014. {
  1015. if (clipChildren_)
  1016. {
  1017. IntVector2 screenPos = GetScreenPosition();
  1018. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1019. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1020. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1021. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1022. if (currentScissor.right_ < currentScissor.left_)
  1023. currentScissor.right_ = currentScissor.left_;
  1024. if (currentScissor.bottom_ < currentScissor.top_)
  1025. currentScissor.bottom_ = currentScissor.top_;
  1026. }
  1027. }
  1028. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, IntRect
  1029. currentScissor)
  1030. {
  1031. unsigned initialSize = quads.Size();
  1032. GetBatches(batches, quads, currentScissor);
  1033. for (unsigned i = initialSize; i < quads.Size(); ++i)
  1034. {
  1035. quads[i].left_ += offset.x_;
  1036. quads[i].top_ += offset.y_;
  1037. quads[i].right_ += offset.x_;
  1038. quads[i].bottom_ += offset.y_;
  1039. }
  1040. AdjustScissor(currentScissor);
  1041. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1042. {
  1043. if ((*i)->IsVisible())
  1044. (*i)->GetBatchesWithOffset(offset, batches, quads, currentScissor);
  1045. }
  1046. }
  1047. void UIElement::MarkDirty()
  1048. {
  1049. positionDirty_ = true;
  1050. opacityDirty_ = true;
  1051. derivedColorDirty_ = true;
  1052. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1053. (*i)->MarkDirty();
  1054. }
  1055. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1056. {
  1057. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1058. {
  1059. UIElement* element = *i;
  1060. dest.Push(element);
  1061. if (!element->children_.Empty())
  1062. element->GetChildrenRecursive(dest);
  1063. }
  1064. }
  1065. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1066. {
  1067. int width = begin + end;
  1068. if (sizes.Empty())
  1069. return width;
  1070. for (unsigned i = 0; i < sizes.Size(); ++i)
  1071. {
  1072. // If calculating maximum size, and the default is specified, do not overflow it
  1073. if (sizes[i] == M_MAX_INT)
  1074. return M_MAX_INT;
  1075. width += sizes[i] + spacing;
  1076. }
  1077. // The last spacing is not needed
  1078. return width - spacing;
  1079. }
  1080. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1081. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1082. {
  1083. int numChildren = sizes.Size();
  1084. if (!numChildren)
  1085. return;
  1086. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1087. if (targetTotalSize < 0)
  1088. targetTotalSize = 0;
  1089. int targetChildSize = targetTotalSize / numChildren;
  1090. int remainder = targetTotalSize % numChildren;
  1091. float add = (float)remainder / numChildren;
  1092. float acc = 0.0f;
  1093. // Initial pass
  1094. for (int i = 0; i < numChildren; ++i)
  1095. {
  1096. int targetSize = targetChildSize;
  1097. if (remainder)
  1098. {
  1099. acc += add;
  1100. if (acc >= 0.5f)
  1101. {
  1102. acc -= 1.0f;
  1103. ++targetSize;
  1104. --remainder;
  1105. }
  1106. }
  1107. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1108. }
  1109. // Error correction passes
  1110. for (;;)
  1111. {
  1112. int actualTotalSize = 0;
  1113. for (int i = 0; i < numChildren; ++i)
  1114. actualTotalSize += sizes[i];
  1115. int error = targetTotalSize - actualTotalSize;
  1116. // Break if no error
  1117. if (!error)
  1118. break;
  1119. // Check which of the children can be resized to correct the error. If none, must break
  1120. PODVector<unsigned> resizable;
  1121. for (int i = 0; i < numChildren; ++i)
  1122. {
  1123. if (error < 0 && sizes[i] > minSizes[i])
  1124. resizable.Push(i);
  1125. else if (error > 0 && sizes[i] < maxSizes[i])
  1126. resizable.Push(i);
  1127. }
  1128. if (resizable.Empty())
  1129. break;
  1130. int numResizable = resizable.Size();
  1131. int errorPerChild = error / numResizable;
  1132. remainder = (abs(error)) % numResizable;
  1133. add = (float)remainder / numResizable;
  1134. acc = 0.0f;
  1135. for (int i = 0; i < numResizable; ++i)
  1136. {
  1137. unsigned index = resizable[i];
  1138. int targetSize = sizes[index] + errorPerChild;
  1139. if (remainder)
  1140. {
  1141. acc += add;
  1142. if (acc >= 0.5f)
  1143. {
  1144. acc -= 1.0f;
  1145. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1146. --remainder;
  1147. }
  1148. }
  1149. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1150. }
  1151. }
  1152. // Calculate final positions and store the minimum child element size
  1153. layoutMinSize_ = M_MAX_INT;
  1154. int position = begin;
  1155. for (int i = 0; i < numChildren; ++i)
  1156. {
  1157. positions[i] = position;
  1158. position += sizes[i] + spacing;
  1159. if (sizes[i] < layoutMinSize_)
  1160. layoutMinSize_ = sizes[i];
  1161. }
  1162. }
  1163. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1164. {
  1165. IntVector2 ret(IntVector2::ZERO);
  1166. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1167. switch (ha)
  1168. {
  1169. case HA_LEFT:
  1170. ret.x_ = layoutBorder_.left_;
  1171. break;
  1172. case HA_RIGHT:
  1173. ret.x_ = -layoutBorder_.right_;
  1174. break;
  1175. default:
  1176. break;
  1177. }
  1178. VerticalAlignment va = child->GetVerticalAlignment();
  1179. switch (va)
  1180. {
  1181. case VA_TOP:
  1182. ret.y_ = layoutBorder_.top_;
  1183. break;
  1184. case VA_BOTTOM:
  1185. ret.y_ = -layoutBorder_.bottom_;
  1186. break;
  1187. default:
  1188. break;
  1189. }
  1190. return ret;
  1191. }
  1192. void UIElement::Detach()
  1193. {
  1194. parent_ = 0;
  1195. MarkDirty();
  1196. }
  1197. }