UIElement.cpp 37 KB

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