UIElement.cpp 41 KB

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