UIElement.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "ResourceCache.h"
  26. #include "Sort.h"
  27. #include "StringUtils.h"
  28. #include "UI.h"
  29. #include "UIElement.h"
  30. #include "UIEvents.h"
  31. #include "DebugNew.h"
  32. namespace Urho3D
  33. {
  34. static const String horizontalAlignments[] =
  35. {
  36. "left",
  37. "center",
  38. "right",
  39. ""
  40. };
  41. static const String verticalAlignments[] =
  42. {
  43. "top",
  44. "center",
  45. "bottom",
  46. ""
  47. };
  48. static const String focusModes[] =
  49. {
  50. "notfocusable",
  51. "resetfocus",
  52. "focusable",
  53. "focusabledefocusable",
  54. ""
  55. };
  56. static const String dragDropModes[] =
  57. {
  58. "disabled",
  59. "source",
  60. "target",
  61. "sourceandtarget",
  62. ""
  63. };
  64. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  65. {
  66. return lhs->GetPriority() < rhs->GetPriority();
  67. }
  68. OBJECTTYPESTATIC(UIElement);
  69. UIElement::UIElement(Context* context) :
  70. Object(context),
  71. parent_(0),
  72. clipBorder_(IntRect::ZERO),
  73. priority_(0),
  74. bringToFront_(false),
  75. bringToBack_(true),
  76. clipChildren_(false),
  77. sortChildren_(true),
  78. active_(false),
  79. selected_(false),
  80. visible_(true),
  81. hovering_(false),
  82. focusMode_(FM_NOTFOCUSABLE),
  83. dragDropMode_(DD_DISABLED),
  84. layoutMode_(LM_FREE),
  85. layoutSpacing_(0),
  86. layoutBorder_(IntRect::ZERO),
  87. resizeNestingLevel_(0),
  88. layoutNestingLevel_(0),
  89. layoutMinSize_(0),
  90. position_(IntVector2::ZERO),
  91. size_(IntVector2::ZERO),
  92. minSize_(IntVector2::ZERO),
  93. maxSize_(M_MAX_INT, M_MAX_INT),
  94. childOffset_(IntVector2::ZERO),
  95. horizontalAlignment_(HA_LEFT),
  96. verticalAlignment_(VA_TOP),
  97. opacity_(1.0f),
  98. positionDirty_(true),
  99. opacityDirty_(true),
  100. derivedColorDirty_(true),
  101. sortOrderDirty_(false),
  102. colorGradient_(false)
  103. {
  104. }
  105. UIElement::~UIElement()
  106. {
  107. // If child elements have outside references, detach them
  108. while (children_.Size())
  109. {
  110. const SharedPtr<UIElement>& element = children_.Back();
  111. if (element.Refs() > 1)
  112. {
  113. element->parent_ = 0;
  114. element->MarkDirty();
  115. }
  116. children_.Pop();
  117. }
  118. }
  119. void UIElement::RegisterObject(Context* context)
  120. {
  121. context->RegisterFactory<UIElement>();
  122. }
  123. void UIElement::SetStyle(const XMLElement& element)
  124. {
  125. if (element.HasAttribute("name"))
  126. name_ = element.GetAttribute("name");
  127. if (element.HasChild("position"))
  128. SetPosition(element.GetChild("position").GetIntVector2("value"));
  129. if (element.HasChild("size"))
  130. SetSize(element.GetChild("size").GetIntVector2("value"));
  131. if (element.HasChild("width"))
  132. SetWidth(element.GetChild("width").GetInt("value"));
  133. if (element.HasChild("height"))
  134. SetHeight(element.GetChild("height").GetInt("value"));
  135. if (element.HasChild("minsize"))
  136. SetMinSize(element.GetChild("minsize").GetIntVector2("value"));
  137. if (element.HasChild("minwidth"))
  138. SetMinWidth(element.GetChild("minwidth").GetInt("value"));
  139. if (element.HasChild("minheight"))
  140. SetMinHeight(element.GetChild("minheight").GetInt("value"));
  141. if (element.HasChild("maxsize"))
  142. SetMaxSize(element.GetChild("maxsize").GetIntVector2("value"));
  143. if (element.HasChild("maxwidth"))
  144. SetMinWidth(element.GetChild("maxwidth").GetInt("value"));
  145. if (element.HasChild("maxheight"))
  146. SetMinHeight(element.GetChild("maxheight").GetInt("value"));
  147. if (element.HasChild("fixedsize"))
  148. SetFixedSize(element.GetChild("fixedsize").GetIntVector2("value"));
  149. if (element.HasChild("fixedwidth"))
  150. SetFixedWidth(element.GetChild("fixedwidth").GetInt("value"));
  151. if (element.HasChild("fixedheight"))
  152. SetFixedHeight(element.GetChild("fixedheight").GetInt("value"));
  153. if (element.HasChild("alignment"))
  154. {
  155. XMLElement alignElem = element.GetChild("alignment");
  156. String horiz;
  157. String vert;
  158. if (alignElem.HasAttribute("horizontal"))
  159. horiz = alignElem.GetAttributeLower("horizontal");
  160. if (alignElem.HasAttribute("vertical"))
  161. vert = alignElem.GetAttributeLower("vertical");
  162. if (alignElem.HasAttribute("h"))
  163. horiz = alignElem.GetAttributeLower("h");
  164. if (alignElem.HasAttribute("v"))
  165. vert = alignElem.GetAttributeLower("v");
  166. if (!horiz.Empty())
  167. SetHorizontalAlignment((HorizontalAlignment)GetStringListIndex(horiz, horizontalAlignments, HA_LEFT));
  168. if (!vert.Empty())
  169. SetVerticalAlignment((VerticalAlignment)GetStringListIndex(vert, verticalAlignments, VA_TOP));
  170. }
  171. if (element.HasChild("clipborder"))
  172. SetClipBorder(element.GetChild("clipborder").GetIntRect("value"));
  173. if (element.HasChild("priority"))
  174. SetPriority(element.GetChild("priority").GetInt("value"));
  175. if (element.HasChild("opacity"))
  176. SetOpacity(element.GetChild("opacity").GetFloat("value"));
  177. if (element.HasChild("color"))
  178. {
  179. XMLElement colorElem = element.GetChild("color");
  180. if (colorElem.HasAttribute("value"))
  181. SetColor(colorElem.GetColor("value"));
  182. if (colorElem.HasAttribute("topleft"))
  183. SetColor(C_TOPLEFT, colorElem.GetColor("topleft"));
  184. if (colorElem.HasAttribute("topright"))
  185. SetColor(C_TOPRIGHT, colorElem.GetColor("topright"));
  186. if (colorElem.HasAttribute("bottomleft"))
  187. SetColor(C_BOTTOMLEFT, colorElem.GetColor("bottomleft"));
  188. if (colorElem.HasAttribute("bottomright"))
  189. SetColor(C_BOTTOMRIGHT, colorElem.GetColor("bottomright"));
  190. }
  191. if (element.HasChild("bringtofront"))
  192. SetBringToFront(element.GetChild("bringtofront").GetBool("enable"));
  193. if (element.HasChild("bringtoback"))
  194. SetBringToBack(element.GetChild("bringtoback").GetBool("enable"));
  195. if (element.HasChild("clipchildren"))
  196. SetClipChildren(element.GetChild("clipchildren").GetBool("enable"));
  197. if (element.HasChild("enabled"))
  198. SetActive(element.GetChild("enabled").GetBool("enable"));
  199. if (element.HasChild("selected"))
  200. SetSelected(element.GetChild("selected").GetBool("enable"));
  201. if (element.HasChild("visible"))
  202. SetVisible(element.GetChild("visible").GetBool("enable"));
  203. if (element.HasChild("focusmode"))
  204. {
  205. String focusMode = element.GetChild("focusmode").GetAttributeLower("value");
  206. SetFocusMode((FocusMode)GetStringListIndex(focusMode, focusModes, FM_NOTFOCUSABLE));
  207. if (focusMode == "defocusable")
  208. SetFocusMode(FM_FOCUSABLE_DEFOCUSABLE);
  209. }
  210. if (element.HasChild("dragdropmode"))
  211. {
  212. String dragDropMode = element.GetChild("dragdropmode").GetAttributeLower("value");
  213. SetDragDropMode(GetStringListIndex(dragDropMode, dragDropModes, DD_DISABLED));
  214. }
  215. if (element.HasChild("layout"))
  216. {
  217. XMLElement layoutElem = element.GetChild("layout");
  218. String mode = layoutElem.GetAttributeLower("mode");
  219. if (mode == "free")
  220. layoutMode_ = LM_FREE;
  221. if (mode == "horizontal" || mode == "h")
  222. layoutMode_ = LM_HORIZONTAL;
  223. if (mode == "vertical" || mode == "v")
  224. layoutMode_ = LM_VERTICAL;
  225. if (layoutElem.HasAttribute("spacing"))
  226. layoutSpacing_ = Max(layoutElem.GetInt("spacing"), 0);
  227. if (layoutElem.HasAttribute("border"))
  228. SetLayoutBorder(layoutElem.GetIntRect("border"));
  229. else
  230. UpdateLayout();
  231. }
  232. if (element.HasChild("vars"))
  233. vars_ = element.GetChild("vars").GetVariantMap();
  234. }
  235. void UIElement::Update(float timeStep)
  236. {
  237. }
  238. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor)
  239. {
  240. // Reset hovering for next frame
  241. hovering_ = false;
  242. }
  243. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  244. {
  245. hovering_ = true;
  246. }
  247. void UIElement::OnClick(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  248. {
  249. }
  250. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  251. {
  252. }
  253. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  254. {
  255. }
  256. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)
  257. {
  258. }
  259. bool UIElement::OnDragDropTest(UIElement* source)
  260. {
  261. return true;
  262. }
  263. bool UIElement::OnDragDropFinish(UIElement* source)
  264. {
  265. return true;
  266. }
  267. void UIElement::OnWheel(int delta, int buttons, int qualifiers)
  268. {
  269. }
  270. void UIElement::OnKey(int key, int buttons, int qualifiers)
  271. {
  272. }
  273. void UIElement::OnChar(unsigned c, int buttons, int qualifiers)
  274. {
  275. }
  276. void UIElement::OnResize()
  277. {
  278. }
  279. void UIElement::SetName(const String& name)
  280. {
  281. name_ = name;
  282. }
  283. void UIElement::SetPosition(const IntVector2& position)
  284. {
  285. if (position != position_)
  286. {
  287. position_ = position;
  288. MarkDirty();
  289. }
  290. }
  291. void UIElement::SetPosition(int x, int y)
  292. {
  293. SetPosition(IntVector2(x, y));
  294. }
  295. void UIElement::SetSize(const IntVector2& size)
  296. {
  297. ++resizeNestingLevel_;
  298. IntVector2 validatedSize;
  299. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  300. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  301. if (validatedSize != size_)
  302. {
  303. size_ = validatedSize;
  304. if (resizeNestingLevel_ == 1)
  305. {
  306. // Check if parent element's layout needs to be updated first
  307. if (parent_)
  308. parent_->UpdateLayout();
  309. MarkDirty();
  310. OnResize();
  311. UpdateLayout();
  312. using namespace Resized;
  313. VariantMap eventData;
  314. eventData[P_ELEMENT] = (void*)this;
  315. eventData[P_WIDTH] = size_.x_;
  316. eventData[P_HEIGHT] = size_.y_;
  317. SendEvent(E_RESIZED, eventData);
  318. }
  319. }
  320. --resizeNestingLevel_;
  321. }
  322. void UIElement::SetSize(int width, int height)
  323. {
  324. SetSize(IntVector2(width, height));
  325. }
  326. void UIElement::SetWidth(int width)
  327. {
  328. SetSize(IntVector2(width, size_.y_));
  329. }
  330. void UIElement::SetHeight(int height)
  331. {
  332. SetSize(IntVector2(size_.x_, height));
  333. }
  334. void UIElement::SetMinSize(const IntVector2& minSize)
  335. {
  336. minSize_.x_ = Max(minSize.x_, 0);
  337. minSize_.y_ = Max(minSize.y_, 0);
  338. SetSize(size_);
  339. }
  340. void UIElement::SetMinSize(int width, int height)
  341. {
  342. SetMinSize(IntVector2(width, height));
  343. }
  344. void UIElement::SetMinWidth(int width)
  345. {
  346. SetMinSize(IntVector2(width, minSize_.y_));
  347. }
  348. void UIElement::SetMinHeight(int height)
  349. {
  350. SetMinSize(IntVector2(minSize_.x_, height));
  351. }
  352. void UIElement::SetMaxSize(const IntVector2& maxSize)
  353. {
  354. maxSize_.x_ = Max(maxSize.x_, 0);
  355. maxSize_.y_ = Max(maxSize.y_, 0);
  356. SetSize(size_);
  357. }
  358. void UIElement::SetMaxSize(int width, int height)
  359. {
  360. SetMaxSize(IntVector2(width, height));
  361. }
  362. void UIElement::SetMaxWidth(int width)
  363. {
  364. SetMaxSize(IntVector2(width, maxSize_.y_));
  365. }
  366. void UIElement::SetMaxHeight(int height)
  367. {
  368. SetMaxSize(IntVector2(maxSize_.x_, height));
  369. }
  370. void UIElement::SetFixedSize(const IntVector2& size)
  371. {
  372. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  373. SetSize(size);
  374. }
  375. void UIElement::SetFixedSize(int width, int height)
  376. {
  377. SetFixedSize(IntVector2(width, height));
  378. }
  379. void UIElement::SetFixedWidth(int width)
  380. {
  381. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  382. SetWidth(width);
  383. }
  384. void UIElement::SetFixedHeight(int height)
  385. {
  386. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  387. SetHeight(height);
  388. }
  389. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  390. {
  391. horizontalAlignment_ = hAlign;
  392. verticalAlignment_ = vAlign;
  393. MarkDirty();
  394. }
  395. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  396. {
  397. horizontalAlignment_ = align;
  398. MarkDirty();
  399. }
  400. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  401. {
  402. verticalAlignment_ = align;
  403. MarkDirty();
  404. }
  405. void UIElement::SetClipBorder(const IntRect& rect)
  406. {
  407. clipBorder_.left_ = Max(rect.left_, 0);
  408. clipBorder_.top_ = Max(rect.top_, 0);
  409. clipBorder_.right_ = Max(rect.right_, 0);
  410. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  411. }
  412. void UIElement::SetColor(const Color& color)
  413. {
  414. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  415. color_[i] = color;
  416. colorGradient_ = false;
  417. derivedColorDirty_ = true;
  418. }
  419. void UIElement::SetColor(Corner corner, const Color& color)
  420. {
  421. color_[corner] = color;
  422. colorGradient_ = false;
  423. derivedColorDirty_ = true;
  424. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  425. {
  426. if (i != corner && color_[i] != color_[corner])
  427. colorGradient_ = true;
  428. }
  429. }
  430. void UIElement::SetPriority(int priority)
  431. {
  432. priority_ = priority;
  433. if (parent_)
  434. parent_->sortOrderDirty_ = true;
  435. }
  436. void UIElement::SetOpacity(float opacity)
  437. {
  438. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  439. MarkDirty();
  440. }
  441. void UIElement::SetBringToFront(bool enable)
  442. {
  443. bringToFront_ = enable;
  444. }
  445. void UIElement::SetBringToBack(bool enable)
  446. {
  447. bringToBack_ = enable;
  448. }
  449. void UIElement::SetClipChildren(bool enable)
  450. {
  451. clipChildren_ = enable;
  452. }
  453. void UIElement::SetSortChildren(bool enable)
  454. {
  455. if (!sortChildren_ && enable)
  456. sortOrderDirty_ = true;
  457. sortChildren_ = enable;
  458. }
  459. void UIElement::SetActive(bool enable)
  460. {
  461. active_ = enable;
  462. }
  463. void UIElement::SetFocusMode(FocusMode mode)
  464. {
  465. focusMode_ = mode;
  466. }
  467. void UIElement::SetFocus(bool enable)
  468. {
  469. if (focusMode_ < FM_FOCUSABLE)
  470. enable = false;
  471. UI* ui = GetSubsystem<UI>();
  472. if (!ui)
  473. return;
  474. if (enable)
  475. {
  476. if (ui->GetFocusElement() != this)
  477. ui->SetFocusElement(this);
  478. }
  479. else
  480. {
  481. if (ui->GetFocusElement() == this)
  482. ui->SetFocusElement(0);
  483. }
  484. }
  485. void UIElement::SetSelected(bool enable)
  486. {
  487. selected_ = enable;
  488. }
  489. void UIElement::SetVisible(bool enable)
  490. {
  491. if (enable != visible_)
  492. {
  493. visible_ = enable;
  494. // Parent's layout may change as a result of visibility change
  495. if (parent_)
  496. parent_->UpdateLayout();
  497. using namespace VisibleChanged;
  498. VariantMap eventData;
  499. eventData[P_ELEMENT] = (void*)this;
  500. eventData[P_VISIBLE] = visible_;
  501. SendEvent(E_VISIBLECHANGED, eventData);
  502. }
  503. }
  504. void UIElement::SetDragDropMode(unsigned mode)
  505. {
  506. dragDropMode_ = mode;
  507. }
  508. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  509. {
  510. if (!file)
  511. return;
  512. XMLElement rootElem = file->GetRoot();
  513. XMLElement childElem = rootElem.GetChild("element");
  514. while (childElem)
  515. {
  516. if (typeName == childElem.GetAttribute("type"))
  517. {
  518. SetStyle(childElem);
  519. return;
  520. }
  521. childElem = childElem.GetNext("element");
  522. }
  523. }
  524. void UIElement::SetStyleAuto(XMLFile* file)
  525. {
  526. SetStyle(file, GetTypeName());
  527. }
  528. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  529. {
  530. layoutMode_ = mode;
  531. layoutSpacing_ = Max(spacing, 0);
  532. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  533. UpdateLayout();
  534. }
  535. void UIElement::SetLayoutMode(LayoutMode mode)
  536. {
  537. layoutMode_ = mode;
  538. UpdateLayout();
  539. }
  540. void UIElement::SetLayoutSpacing(int spacing)
  541. {
  542. layoutSpacing_ = Max(spacing, 0);
  543. UpdateLayout();
  544. }
  545. void UIElement::SetLayoutBorder(const IntRect& border)
  546. {
  547. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  548. UpdateLayout();
  549. }
  550. void UIElement::UpdateLayout()
  551. {
  552. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  553. return;
  554. // Prevent further updates while this update happens
  555. DisableLayoutUpdate();
  556. PODVector<int> positions;
  557. PODVector<int> sizes;
  558. PODVector<int> minSizes;
  559. PODVector<int> maxSizes;
  560. if (layoutMode_ == LM_HORIZONTAL)
  561. {
  562. int minChildHeight = 0;
  563. for (unsigned i = 0; i < children_.Size(); ++i)
  564. {
  565. if (!children_[i]->IsVisible())
  566. continue;
  567. positions.Push(0);
  568. sizes.Push(children_[i]->GetWidth());
  569. minSizes.Push(children_[i]->GetMinWidth());
  570. maxSizes.Push(children_[i]->GetMaxWidth());
  571. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  572. }
  573. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  574. layoutSpacing_);
  575. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  576. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  577. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  578. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  579. // Respect fixed size if already set
  580. if (minSize_.x_ != maxSize_.x_)
  581. minSize_.x_ = minWidth;
  582. if (minSize_.y_ != maxSize_.y_)
  583. minSize_.y_ = minHeight;
  584. SetSize(width, height);
  585. // Validate the size before resizing child elements, in case of min/max limits
  586. width = size_.x_;
  587. height = size_.y_;
  588. unsigned j = 0;
  589. for (unsigned i = 0; i < children_.Size(); ++i)
  590. {
  591. if (!children_[i]->IsVisible())
  592. continue;
  593. children_[i]->SetHorizontalAlignment(HA_LEFT);
  594. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  595. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  596. ++j;
  597. }
  598. }
  599. if (layoutMode_ == LM_VERTICAL)
  600. {
  601. int minChildWidth = 0;
  602. for (unsigned i = 0; i < children_.Size(); ++i)
  603. {
  604. if (!children_[i]->IsVisible())
  605. continue;
  606. positions.Push(0);
  607. sizes.Push(children_[i]->GetHeight());
  608. minSizes.Push(children_[i]->GetMinHeight());
  609. maxSizes.Push(children_[i]->GetMaxHeight());
  610. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth());
  611. }
  612. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  613. layoutSpacing_);
  614. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  615. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  616. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  617. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  618. if (minSize_.x_ != maxSize_.x_)
  619. minSize_.x_ = minWidth;
  620. if (minSize_.y_ != maxSize_.y_)
  621. minSize_.y_ = minHeight;
  622. SetSize(width, height);
  623. width = size_.x_;
  624. height = size_.y_;
  625. unsigned j = 0;
  626. for (unsigned i = 0; i < children_.Size(); ++i)
  627. {
  628. if (!children_[i]->IsVisible())
  629. continue;
  630. children_[i]->SetVerticalAlignment(VA_TOP);
  631. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  632. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  633. ++j;
  634. }
  635. }
  636. EnableLayoutUpdate();
  637. }
  638. void UIElement::DisableLayoutUpdate()
  639. {
  640. ++layoutNestingLevel_;
  641. }
  642. void UIElement::EnableLayoutUpdate()
  643. {
  644. --layoutNestingLevel_;
  645. }
  646. void UIElement::BringToFront()
  647. {
  648. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  649. UIElement* root = GetRoot();
  650. UIElement* ptr = this;
  651. while (ptr && ptr->GetParent() != root)
  652. ptr = ptr->GetParent();
  653. if (!ptr || !ptr->GetBringToFront())
  654. return;
  655. // Get the highest priority used by all other top level elements, assign that to the new front element
  656. // and decrease others' priority by one. However, take into account only active (enabled) elements
  657. // and those which have the BringToBack flag set
  658. int maxPriority = M_MIN_INT;
  659. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  660. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  661. {
  662. UIElement* other = *i;
  663. if (other->IsActive() && other->bringToBack_ && other != ptr)
  664. {
  665. int priority = other->GetPriority();
  666. maxPriority = Max(priority, maxPriority);
  667. other->SetPriority(priority - 1);
  668. }
  669. }
  670. if (maxPriority != M_MIN_INT)
  671. ptr->SetPriority(maxPriority);
  672. }
  673. void UIElement::AddChild(UIElement* element)
  674. {
  675. InsertChild(children_.Size(), element);
  676. }
  677. void UIElement::InsertChild(unsigned index, UIElement* element)
  678. {
  679. // Check for illegal or redundant parent assignment
  680. if (!element || element == this || element->parent_ == this)
  681. return;
  682. // Check for possible cyclic parent assignment
  683. UIElement* parent = parent_;
  684. while (parent)
  685. {
  686. if (parent == element)
  687. return;
  688. parent = parent->parent_;
  689. }
  690. // Add first, then remove from old parent, to ensure the element does not get deleted
  691. if (index >= children_.Size())
  692. children_.Push(SharedPtr<UIElement>(element));
  693. else
  694. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  695. if (element->parent_)
  696. element->parent_->RemoveChild(element);
  697. if (sortChildren_)
  698. sortOrderDirty_ = true;
  699. element->parent_ = this;
  700. element->MarkDirty();
  701. UpdateLayout();
  702. }
  703. void UIElement::RemoveChild(UIElement* element)
  704. {
  705. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  706. {
  707. if (*i == element)
  708. {
  709. element->parent_ = 0;
  710. element->MarkDirty();
  711. children_.Erase(i);
  712. UpdateLayout();
  713. return;
  714. }
  715. }
  716. }
  717. void UIElement::RemoveAllChildren()
  718. {
  719. while (children_.Size())
  720. {
  721. const SharedPtr<UIElement>& element = children_.Back();
  722. element->parent_ = 0;
  723. element->MarkDirty();
  724. children_.Pop();
  725. }
  726. }
  727. void UIElement::Remove()
  728. {
  729. if (parent_)
  730. parent_->RemoveChild(this);
  731. }
  732. void UIElement::SetParent(UIElement* parent)
  733. {
  734. if (parent)
  735. parent->AddChild(this);
  736. }
  737. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  738. {
  739. vars_[key] = value;
  740. }
  741. IntVector2 UIElement::GetScreenPosition()
  742. {
  743. if (positionDirty_)
  744. {
  745. IntVector2 pos = position_;
  746. const UIElement* parent = parent_;
  747. const UIElement* current = this;
  748. while (parent)
  749. {
  750. switch (current->horizontalAlignment_)
  751. {
  752. case HA_LEFT:
  753. pos.x_ += parent->position_.x_;
  754. break;
  755. case HA_CENTER:
  756. pos.x_ += parent->position_.x_ + parent->size_.x_ / 2 - current->size_.x_ / 2;
  757. break;
  758. case HA_RIGHT:
  759. pos.x_ += parent->position_.x_ + parent->size_.x_ - current->size_.x_;
  760. break;
  761. }
  762. switch (current->verticalAlignment_)
  763. {
  764. case VA_TOP:
  765. pos.y_ += parent->position_.y_;
  766. break;
  767. case VA_CENTER:
  768. pos.y_ += parent->position_.y_ + parent->size_.y_ / 2 - current->size_.y_ / 2;
  769. break;
  770. case VA_BOTTOM:
  771. pos.y_ += parent->position_.y_ + parent->size_.y_ - current->size_.y_;
  772. break;
  773. }
  774. pos += parent->childOffset_;
  775. current = parent;
  776. parent = parent->parent_;
  777. }
  778. screenPosition_ = pos;
  779. positionDirty_ = false;
  780. }
  781. return screenPosition_;
  782. }
  783. float UIElement::GetDerivedOpacity()
  784. {
  785. if (opacityDirty_)
  786. {
  787. float opacity = opacity_;
  788. const UIElement* parent = parent_;
  789. while (parent)
  790. {
  791. opacity *= parent->opacity_;
  792. parent = parent->parent_;
  793. }
  794. derivedOpacity_ = opacity;
  795. opacityDirty_ = false;
  796. }
  797. return derivedOpacity_;
  798. }
  799. bool UIElement::HasFocus() const
  800. {
  801. UI* ui = GetSubsystem<UI>();
  802. if (!ui)
  803. return false;
  804. else
  805. return ui->GetFocusElement() == this;
  806. }
  807. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  808. {
  809. dest.Clear();
  810. if (!recursive)
  811. {
  812. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  813. dest.Push(*i);
  814. }
  815. else
  816. GetChildrenRecursive(dest);
  817. }
  818. unsigned UIElement::GetNumChildren(bool recursive) const
  819. {
  820. if (!recursive)
  821. return children_.Size();
  822. else
  823. {
  824. unsigned allChildren = children_.Size();
  825. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  826. allChildren += (*i)->GetNumChildren(true);
  827. return allChildren;
  828. }
  829. }
  830. UIElement* UIElement::GetChild(unsigned index) const
  831. {
  832. return index < children_.Size() ? children_[index] : (UIElement*)0;
  833. }
  834. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  835. {
  836. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  837. {
  838. if ((*i)->name_ == name)
  839. return *i;
  840. if (recursive)
  841. {
  842. UIElement* element = (*i)->GetChild(name, true);
  843. if (element)
  844. return element;
  845. }
  846. }
  847. return 0;
  848. }
  849. UIElement* UIElement::GetRoot() const
  850. {
  851. UIElement* root = parent_;
  852. if (!root)
  853. return 0;
  854. while (root->GetParent())
  855. root = root->GetParent();
  856. return root;
  857. }
  858. unsigned UIElement::GetUIntColor()
  859. {
  860. if (derivedColorDirty_)
  861. {
  862. Color color = color_[C_TOPLEFT];
  863. color.a_ *= GetDerivedOpacity();
  864. uintColor_ = color.ToUInt();
  865. derivedColorDirty_ = false;
  866. }
  867. return uintColor_;
  868. }
  869. const Variant& UIElement::GetVar(ShortStringHash key) const
  870. {
  871. VariantMap::ConstIterator i = vars_.Find(key);
  872. if (i != vars_.End())
  873. return i->second_;
  874. else
  875. return Variant::EMPTY;
  876. }
  877. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  878. {
  879. return screenPosition - GetScreenPosition();
  880. }
  881. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  882. {
  883. return position + GetScreenPosition();
  884. }
  885. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  886. {
  887. if (isScreen)
  888. position = ScreenToElement(position);
  889. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  890. }
  891. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  892. {
  893. // If child elements are clipped, no need to expand the rect
  894. if (clipChildren_)
  895. return IsInside(position, isScreen);
  896. if (!isScreen)
  897. position = ElementToScreen(position);
  898. IntRect combined = GetCombinedScreenRect();
  899. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  900. position.y_ < combined.bottom_;
  901. }
  902. IntRect UIElement::GetCombinedScreenRect()
  903. {
  904. IntVector2 screenPosition(GetScreenPosition());
  905. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  906. if (!clipChildren_)
  907. {
  908. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  909. {
  910. IntVector2 childPos = (*i)->GetScreenPosition();
  911. const IntVector2& childSize = (*i)->GetSize();
  912. if (childPos.x_ < combined.left_)
  913. combined.left_ = childPos.x_;
  914. if (childPos.y_ < combined.top_)
  915. combined.top_ = childPos.y_;
  916. if (childPos.x_ + childSize.x_ > combined.right_)
  917. combined.right_ = childPos.x_ + childSize.x_;
  918. if (childPos.y_ + childSize.y_ > combined.bottom_)
  919. combined.bottom_ = childPos.y_ + childSize.y_;
  920. }
  921. }
  922. return combined;
  923. }
  924. void UIElement::SortChildren()
  925. {
  926. if (sortChildren_ && sortOrderDirty_)
  927. {
  928. Sort(children_.Begin(), children_.End(), CompareUIElements);
  929. sortOrderDirty_ = false;
  930. }
  931. }
  932. void UIElement::SetChildOffset(const IntVector2& offset)
  933. {
  934. if (offset != childOffset_)
  935. {
  936. childOffset_ = offset;
  937. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  938. (*i)->MarkDirty();
  939. }
  940. }
  941. void UIElement::SetHovering(bool enable)
  942. {
  943. hovering_ = enable;
  944. }
  945. void UIElement::SetTempVisible(bool enable)
  946. {
  947. visible_ = enable;
  948. }
  949. void UIElement::AdjustScissor(IntRect& currentScissor)
  950. {
  951. if (clipChildren_)
  952. {
  953. IntVector2 screenPos = GetScreenPosition();
  954. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  955. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  956. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  957. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  958. if (currentScissor.right_ < currentScissor.left_)
  959. currentScissor.right_ = currentScissor.left_;
  960. if (currentScissor.bottom_ < currentScissor.top_)
  961. currentScissor.bottom_ = currentScissor.top_;
  962. }
  963. }
  964. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, IntRect
  965. currentScissor)
  966. {
  967. unsigned initialSize = quads.Size();
  968. GetBatches(batches, quads, currentScissor);
  969. for (unsigned i = initialSize; i < quads.Size(); ++i)
  970. {
  971. quads[i].left_ += offset.x_;
  972. quads[i].top_ += offset.y_;
  973. quads[i].right_ += offset.x_;
  974. quads[i].bottom_ += offset.y_;
  975. }
  976. AdjustScissor(currentScissor);
  977. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  978. {
  979. if ((*i)->IsVisible())
  980. (*i)->GetBatchesWithOffset(offset, batches, quads, currentScissor);
  981. }
  982. }
  983. void UIElement::MarkDirty()
  984. {
  985. positionDirty_ = true;
  986. opacityDirty_ = true;
  987. derivedColorDirty_ = true;
  988. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  989. (*i)->MarkDirty();
  990. }
  991. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  992. {
  993. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  994. {
  995. UIElement* element = *i;
  996. dest.Push(element);
  997. if (!element->children_.Empty())
  998. element->GetChildrenRecursive(dest);
  999. }
  1000. }
  1001. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1002. {
  1003. int width = begin + end;
  1004. for (unsigned i = 0; i < sizes.Size(); ++i)
  1005. {
  1006. // If calculating maximum size, and the default is specified, do not overflow it
  1007. if (sizes[i] == M_MAX_INT)
  1008. return M_MAX_INT;
  1009. width += sizes[i];
  1010. if (i < sizes.Size() - 1)
  1011. width += spacing;
  1012. }
  1013. return width;
  1014. }
  1015. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1016. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1017. {
  1018. int numChildren = sizes.Size();
  1019. if (!numChildren)
  1020. return;
  1021. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1022. if (targetTotalSize < 0)
  1023. targetTotalSize = 0;
  1024. int targetChildSize = targetTotalSize / numChildren;
  1025. int remainder = targetTotalSize % numChildren;
  1026. float add = (float)remainder / numChildren;
  1027. float acc = 0.0f;
  1028. // Initial pass
  1029. for (int i = 0; i < numChildren; ++i)
  1030. {
  1031. int targetSize = targetChildSize;
  1032. if (remainder)
  1033. {
  1034. acc += add;
  1035. if (acc >= 0.5f)
  1036. {
  1037. acc -= 1.0f;
  1038. ++targetSize;
  1039. --remainder;
  1040. }
  1041. }
  1042. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1043. }
  1044. // Error correction passes
  1045. for (;;)
  1046. {
  1047. int actualTotalSize = 0;
  1048. for (int i = 0; i < numChildren; ++i)
  1049. actualTotalSize += sizes[i];
  1050. int error = targetTotalSize - actualTotalSize;
  1051. // Break if no error
  1052. if (!error)
  1053. break;
  1054. // Check which of the children can be resized to correct the error. If none, must break
  1055. PODVector<unsigned> resizable;
  1056. for (int i = 0; i < numChildren; ++i)
  1057. {
  1058. if (error < 0 && sizes[i] > minSizes[i])
  1059. resizable.Push(i);
  1060. else if (error > 0 && sizes[i] < maxSizes[i])
  1061. resizable.Push(i);
  1062. }
  1063. if (resizable.Empty())
  1064. break;
  1065. int numResizable = resizable.Size();
  1066. int errorPerChild = error / numResizable;
  1067. remainder = (abs(error)) % numResizable;
  1068. add = (float)remainder / numResizable;
  1069. acc = 0.0f;
  1070. for (int i = 0; i < numResizable; ++i)
  1071. {
  1072. unsigned index = resizable[i];
  1073. int targetSize = sizes[index] + errorPerChild;
  1074. if (remainder)
  1075. {
  1076. acc += add;
  1077. if (acc >= 0.5f)
  1078. {
  1079. acc -= 1.0f;
  1080. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1081. --remainder;
  1082. }
  1083. }
  1084. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1085. }
  1086. }
  1087. // Calculate final positions and store the minimum child element size
  1088. layoutMinSize_ = M_MAX_INT;
  1089. int position = begin;
  1090. for (int i = 0; i < numChildren; ++i)
  1091. {
  1092. positions[i] = position;
  1093. position += sizes[i];
  1094. position += spacing;
  1095. if (sizes[i] < layoutMinSize_)
  1096. layoutMinSize_ = sizes[i];
  1097. }
  1098. }
  1099. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1100. {
  1101. IntVector2 ret(IntVector2::ZERO);
  1102. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1103. switch (ha)
  1104. {
  1105. case HA_LEFT:
  1106. ret.x_ = layoutBorder_.left_;
  1107. break;
  1108. case HA_RIGHT:
  1109. ret.x_ = -layoutBorder_.right_;
  1110. break;
  1111. }
  1112. VerticalAlignment va = child->GetVerticalAlignment();
  1113. switch (va)
  1114. {
  1115. case VA_TOP:
  1116. ret.y_ = layoutBorder_.top_;
  1117. break;
  1118. case VA_BOTTOM:
  1119. ret.y_ = -layoutBorder_.bottom_;
  1120. break;
  1121. }
  1122. return ret;
  1123. }
  1124. }