UIElement.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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. 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. bringToFront_(false),
  73. bringToBack_(true),
  74. clipChildren_(false),
  75. sortChildren_(true),
  76. active_(false),
  77. selected_(false),
  78. visible_(true),
  79. hovering_(false),
  80. focusMode_(FM_NOTFOCUSABLE),
  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. opacity_(1.0f),
  96. positionDirty_(true),
  97. opacityDirty_(true),
  98. derivedColorDirty_(true),
  99. sortOrderDirty_(false),
  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.GetAttribute("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.GetAttributeLower("horizontal");
  158. if (alignElem.HasAttribute("vertical"))
  159. vert = alignElem.GetAttributeLower("vertical");
  160. if (alignElem.HasAttribute("h"))
  161. horiz = alignElem.GetAttributeLower("h");
  162. if (alignElem.HasAttribute("v"))
  163. vert = alignElem.GetAttributeLower("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").GetAttributeLower("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").GetAttributeLower("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.GetAttributeLower("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::OnDragBegin(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 c, int buttons, int qualifiers)
  272. {
  273. }
  274. void UIElement::OnResize()
  275. {
  276. }
  277. void UIElement::SetName(const String& name)
  278. {
  279. name_ = name;
  280. }
  281. void UIElement::SetPosition(const IntVector2& position)
  282. {
  283. if (position != position_)
  284. {
  285. position_ = position;
  286. MarkDirty();
  287. }
  288. }
  289. void UIElement::SetPosition(int x, int y)
  290. {
  291. SetPosition(IntVector2(x, y));
  292. }
  293. void UIElement::SetSize(const IntVector2& size)
  294. {
  295. ++resizeNestingLevel_;
  296. IntVector2 validatedSize;
  297. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  298. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  299. if (validatedSize != size_)
  300. {
  301. size_ = validatedSize;
  302. if (resizeNestingLevel_ == 1)
  303. {
  304. // Check if parent element's layout needs to be updated first
  305. if (parent_)
  306. parent_->UpdateLayout();
  307. MarkDirty();
  308. OnResize();
  309. UpdateLayout();
  310. using namespace Resized;
  311. VariantMap eventData;
  312. eventData[P_ELEMENT] = (void*)this;
  313. eventData[P_WIDTH] = size_.x_;
  314. eventData[P_HEIGHT] = size_.y_;
  315. SendEvent(E_RESIZED, eventData);
  316. }
  317. }
  318. --resizeNestingLevel_;
  319. }
  320. void UIElement::SetSize(int width, int height)
  321. {
  322. SetSize(IntVector2(width, height));
  323. }
  324. void UIElement::SetWidth(int width)
  325. {
  326. SetSize(IntVector2(width, size_.y_));
  327. }
  328. void UIElement::SetHeight(int height)
  329. {
  330. SetSize(IntVector2(size_.x_, height));
  331. }
  332. void UIElement::SetMinSize(const IntVector2& minSize)
  333. {
  334. minSize_.x_ = Max(minSize.x_, 0);
  335. minSize_.y_ = Max(minSize.y_, 0);
  336. SetSize(size_);
  337. }
  338. void UIElement::SetMinSize(int width, int height)
  339. {
  340. SetMinSize(IntVector2(width, height));
  341. }
  342. void UIElement::SetMinWidth(int width)
  343. {
  344. SetMinSize(IntVector2(width, minSize_.y_));
  345. }
  346. void UIElement::SetMinHeight(int height)
  347. {
  348. SetMinSize(IntVector2(minSize_.x_, height));
  349. }
  350. void UIElement::SetMaxSize(const IntVector2& maxSize)
  351. {
  352. maxSize_.x_ = Max(maxSize.x_, 0);
  353. maxSize_.y_ = Max(maxSize.y_, 0);
  354. SetSize(size_);
  355. }
  356. void UIElement::SetMaxSize(int width, int height)
  357. {
  358. SetMaxSize(IntVector2(width, height));
  359. }
  360. void UIElement::SetMaxWidth(int width)
  361. {
  362. SetMaxSize(IntVector2(width, maxSize_.y_));
  363. }
  364. void UIElement::SetMaxHeight(int height)
  365. {
  366. SetMaxSize(IntVector2(maxSize_.x_, height));
  367. }
  368. void UIElement::SetFixedSize(const IntVector2& size)
  369. {
  370. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  371. SetSize(size);
  372. }
  373. void UIElement::SetFixedSize(int width, int height)
  374. {
  375. SetFixedSize(IntVector2(width, height));
  376. }
  377. void UIElement::SetFixedWidth(int width)
  378. {
  379. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  380. SetWidth(width);
  381. }
  382. void UIElement::SetFixedHeight(int height)
  383. {
  384. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  385. SetHeight(height);
  386. }
  387. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  388. {
  389. horizontalAlignment_ = hAlign;
  390. verticalAlignment_ = vAlign;
  391. MarkDirty();
  392. }
  393. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  394. {
  395. horizontalAlignment_ = align;
  396. MarkDirty();
  397. }
  398. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  399. {
  400. verticalAlignment_ = align;
  401. MarkDirty();
  402. }
  403. void UIElement::SetClipBorder(const IntRect& rect)
  404. {
  405. clipBorder_.left_ = Max(rect.left_, 0);
  406. clipBorder_.top_ = Max(rect.top_, 0);
  407. clipBorder_.right_ = Max(rect.right_, 0);
  408. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  409. }
  410. void UIElement::SetColor(const Color& color)
  411. {
  412. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  413. color_[i] = color;
  414. colorGradient_ = false;
  415. derivedColorDirty_ = true;
  416. }
  417. void UIElement::SetColor(Corner corner, const Color& color)
  418. {
  419. color_[corner] = color;
  420. colorGradient_ = false;
  421. derivedColorDirty_ = true;
  422. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  423. {
  424. if (i != corner && color_[i] != color_[corner])
  425. colorGradient_ = true;
  426. }
  427. }
  428. void UIElement::SetPriority(int priority)
  429. {
  430. priority_ = priority;
  431. if (parent_)
  432. parent_->sortOrderDirty_ = true;
  433. }
  434. void UIElement::SetOpacity(float opacity)
  435. {
  436. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  437. MarkDirty();
  438. }
  439. void UIElement::SetBringToFront(bool enable)
  440. {
  441. bringToFront_ = enable;
  442. }
  443. void UIElement::SetBringToBack(bool enable)
  444. {
  445. bringToBack_ = enable;
  446. }
  447. void UIElement::SetClipChildren(bool enable)
  448. {
  449. clipChildren_ = enable;
  450. }
  451. void UIElement::SetSortChildren(bool enable)
  452. {
  453. if (!sortChildren_ && enable)
  454. sortOrderDirty_ = true;
  455. sortChildren_ = enable;
  456. }
  457. void UIElement::SetActive(bool enable)
  458. {
  459. active_ = enable;
  460. }
  461. void UIElement::SetFocusMode(FocusMode mode)
  462. {
  463. focusMode_ = mode;
  464. }
  465. void UIElement::SetFocus(bool enable)
  466. {
  467. if (focusMode_ < FM_FOCUSABLE)
  468. enable = false;
  469. UI* ui = GetSubsystem<UI>();
  470. if (!ui)
  471. return;
  472. if (enable)
  473. {
  474. if (ui->GetFocusElement() != this)
  475. ui->SetFocusElement(this);
  476. }
  477. else
  478. {
  479. if (ui->GetFocusElement() == this)
  480. ui->SetFocusElement(0);
  481. }
  482. }
  483. void UIElement::SetSelected(bool enable)
  484. {
  485. selected_ = enable;
  486. }
  487. void UIElement::SetVisible(bool enable)
  488. {
  489. if (enable != visible_)
  490. {
  491. visible_ = enable;
  492. // Parent's layout may change as a result of visibility change
  493. if (parent_)
  494. parent_->UpdateLayout();
  495. using namespace VisibleChanged;
  496. VariantMap eventData;
  497. eventData[P_ELEMENT] = (void*)this;
  498. eventData[P_VISIBLE] = visible_;
  499. SendEvent(E_VISIBLECHANGED, eventData);
  500. }
  501. }
  502. void UIElement::SetDragDropMode(unsigned mode)
  503. {
  504. dragDropMode_ = mode;
  505. }
  506. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  507. {
  508. if (!file)
  509. return;
  510. XMLElement rootElem = file->GetRoot();
  511. XMLElement childElem = rootElem.GetChild("element");
  512. while (childElem)
  513. {
  514. if (typeName == childElem.GetAttribute("type"))
  515. {
  516. SetStyle(childElem);
  517. return;
  518. }
  519. childElem = childElem.GetNext("element");
  520. }
  521. }
  522. void UIElement::SetStyleAuto(XMLFile* file)
  523. {
  524. SetStyle(file, GetTypeName());
  525. }
  526. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  527. {
  528. layoutMode_ = mode;
  529. layoutSpacing_ = Max(spacing, 0);
  530. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  531. UpdateLayout();
  532. }
  533. void UIElement::SetLayoutMode(LayoutMode mode)
  534. {
  535. layoutMode_ = mode;
  536. UpdateLayout();
  537. }
  538. void UIElement::SetLayoutSpacing(int spacing)
  539. {
  540. layoutSpacing_ = Max(spacing, 0);
  541. UpdateLayout();
  542. }
  543. void UIElement::SetLayoutBorder(const IntRect& border)
  544. {
  545. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  546. UpdateLayout();
  547. }
  548. void UIElement::UpdateLayout()
  549. {
  550. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  551. return;
  552. // Prevent further updates while this update happens
  553. DisableLayoutUpdate();
  554. PODVector<int> positions;
  555. PODVector<int> sizes;
  556. PODVector<int> minSizes;
  557. PODVector<int> maxSizes;
  558. if (layoutMode_ == LM_HORIZONTAL)
  559. {
  560. int minChildHeight = 0;
  561. for (unsigned i = 0; i < children_.Size(); ++i)
  562. {
  563. if (!children_[i]->IsVisible())
  564. continue;
  565. positions.Push(0);
  566. sizes.Push(children_[i]->GetWidth());
  567. minSizes.Push(children_[i]->GetMinWidth());
  568. maxSizes.Push(children_[i]->GetMaxWidth());
  569. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  570. }
  571. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  572. layoutSpacing_);
  573. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  574. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  575. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  576. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  577. // Respect fixed size if already set
  578. if (minSize_.x_ != maxSize_.x_)
  579. minSize_.x_ = minWidth;
  580. if (minSize_.y_ != maxSize_.y_)
  581. minSize_.y_ = minHeight;
  582. SetSize(width, height);
  583. // Validate the size before resizing child elements, in case of min/max limits
  584. width = size_.x_;
  585. height = size_.y_;
  586. unsigned j = 0;
  587. for (unsigned i = 0; i < children_.Size(); ++i)
  588. {
  589. if (!children_[i]->IsVisible())
  590. continue;
  591. children_[i]->SetHorizontalAlignment(HA_LEFT);
  592. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  593. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  594. ++j;
  595. }
  596. }
  597. if (layoutMode_ == LM_VERTICAL)
  598. {
  599. int minChildWidth = 0;
  600. for (unsigned i = 0; i < children_.Size(); ++i)
  601. {
  602. if (!children_[i]->IsVisible())
  603. continue;
  604. positions.Push(0);
  605. sizes.Push(children_[i]->GetHeight());
  606. minSizes.Push(children_[i]->GetMinHeight());
  607. maxSizes.Push(children_[i]->GetMaxHeight());
  608. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth());
  609. }
  610. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  611. layoutSpacing_);
  612. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  613. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  614. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  615. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  616. if (minSize_.x_ != maxSize_.x_)
  617. minSize_.x_ = minWidth;
  618. if (minSize_.y_ != maxSize_.y_)
  619. minSize_.y_ = minHeight;
  620. SetSize(width, height);
  621. width = size_.x_;
  622. height = size_.y_;
  623. unsigned j = 0;
  624. for (unsigned i = 0; i < children_.Size(); ++i)
  625. {
  626. if (!children_[i]->IsVisible())
  627. continue;
  628. children_[i]->SetVerticalAlignment(VA_TOP);
  629. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  630. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  631. ++j;
  632. }
  633. }
  634. EnableLayoutUpdate();
  635. }
  636. void UIElement::DisableLayoutUpdate()
  637. {
  638. ++layoutNestingLevel_;
  639. }
  640. void UIElement::EnableLayoutUpdate()
  641. {
  642. --layoutNestingLevel_;
  643. }
  644. void UIElement::BringToFront()
  645. {
  646. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  647. UIElement* root = GetRoot();
  648. UIElement* ptr = this;
  649. while (ptr && ptr->GetParent() != root)
  650. ptr = ptr->GetParent();
  651. if (!ptr || !ptr->GetBringToFront())
  652. return;
  653. // Get the highest priority used by all other top level elements, assign that to the new front element
  654. // and decrease others' priority by one. However, take into account only active (enabled) elements
  655. // and those which have the BringToBack flag set
  656. int maxPriority = M_MIN_INT;
  657. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  658. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  659. {
  660. UIElement* other = *i;
  661. if (other->IsActive() && other->bringToBack_ && other != ptr)
  662. {
  663. int priority = other->GetPriority();
  664. maxPriority = Max(priority, maxPriority);
  665. other->SetPriority(priority - 1);
  666. }
  667. }
  668. if (maxPriority != M_MIN_INT)
  669. ptr->SetPriority(maxPriority);
  670. }
  671. void UIElement::AddChild(UIElement* element)
  672. {
  673. InsertChild(children_.Size(), element);
  674. }
  675. void UIElement::InsertChild(unsigned index, UIElement* element)
  676. {
  677. // Check for illegal or redundant parent assignment
  678. if (!element || element == this || element->parent_ == this)
  679. return;
  680. // Check for possible cyclic parent assignment
  681. UIElement* parent = parent_;
  682. while (parent)
  683. {
  684. if (parent == element)
  685. return;
  686. parent = parent->parent_;
  687. }
  688. // Add first, then remove from old parent, to ensure the element does not get deleted
  689. if (index >= children_.Size())
  690. children_.Push(SharedPtr<UIElement>(element));
  691. else
  692. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  693. if (element->parent_)
  694. element->parent_->RemoveChild(element);
  695. if (sortChildren_)
  696. sortOrderDirty_ = true;
  697. element->parent_ = this;
  698. element->MarkDirty();
  699. UpdateLayout();
  700. }
  701. void UIElement::RemoveChild(UIElement* element)
  702. {
  703. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  704. {
  705. if (*i == element)
  706. {
  707. element->parent_ = 0;
  708. element->MarkDirty();
  709. children_.Erase(i);
  710. UpdateLayout();
  711. return;
  712. }
  713. }
  714. }
  715. void UIElement::RemoveAllChildren()
  716. {
  717. while (children_.Size())
  718. {
  719. const SharedPtr<UIElement>& element = children_.Back();
  720. element->parent_ = 0;
  721. element->MarkDirty();
  722. children_.Pop();
  723. }
  724. }
  725. void UIElement::Remove()
  726. {
  727. if (parent_)
  728. parent_->RemoveChild(this);
  729. }
  730. void UIElement::SetParent(UIElement* parent)
  731. {
  732. if (parent)
  733. parent->AddChild(this);
  734. }
  735. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  736. {
  737. vars_[key] = value;
  738. }
  739. IntVector2 UIElement::GetScreenPosition()
  740. {
  741. if (positionDirty_)
  742. {
  743. IntVector2 pos = position_;
  744. const UIElement* parent = parent_;
  745. const UIElement* current = this;
  746. while (parent)
  747. {
  748. switch (current->horizontalAlignment_)
  749. {
  750. case HA_LEFT:
  751. pos.x_ += parent->position_.x_;
  752. break;
  753. case HA_CENTER:
  754. pos.x_ += parent->position_.x_ + parent->size_.x_ / 2 - current->size_.x_ / 2;
  755. break;
  756. case HA_RIGHT:
  757. pos.x_ += parent->position_.x_ + parent->size_.x_ - current->size_.x_;
  758. break;
  759. }
  760. switch (current->verticalAlignment_)
  761. {
  762. case VA_TOP:
  763. pos.y_ += parent->position_.y_;
  764. break;
  765. case VA_CENTER:
  766. pos.y_ += parent->position_.y_ + parent->size_.y_ / 2 - current->size_.y_ / 2;
  767. break;
  768. case VA_BOTTOM:
  769. pos.y_ += parent->position_.y_ + parent->size_.y_ - current->size_.y_;
  770. break;
  771. }
  772. pos += parent->childOffset_;
  773. current = parent;
  774. parent = parent->parent_;
  775. }
  776. screenPosition_ = pos;
  777. positionDirty_ = false;
  778. }
  779. return screenPosition_;
  780. }
  781. float UIElement::GetDerivedOpacity()
  782. {
  783. if (opacityDirty_)
  784. {
  785. float opacity = opacity_;
  786. const UIElement* parent = parent_;
  787. while (parent)
  788. {
  789. opacity *= parent->opacity_;
  790. parent = parent->parent_;
  791. }
  792. derivedOpacity_ = opacity;
  793. opacityDirty_ = false;
  794. }
  795. return derivedOpacity_;
  796. }
  797. bool UIElement::HasFocus() const
  798. {
  799. UI* ui = GetSubsystem<UI>();
  800. if (!ui)
  801. return false;
  802. else
  803. return ui->GetFocusElement() == this;
  804. }
  805. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  806. {
  807. dest.Clear();
  808. if (!recursive)
  809. {
  810. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  811. dest.Push(*i);
  812. }
  813. else
  814. GetChildrenRecursive(dest);
  815. }
  816. unsigned UIElement::GetNumChildren(bool recursive) const
  817. {
  818. if (!recursive)
  819. return children_.Size();
  820. else
  821. {
  822. unsigned allChildren = children_.Size();
  823. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  824. allChildren += (*i)->GetNumChildren(true);
  825. return allChildren;
  826. }
  827. }
  828. UIElement* UIElement::GetChild(unsigned index) const
  829. {
  830. return index < children_.Size() ? children_[index] : (UIElement*)0;
  831. }
  832. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  833. {
  834. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  835. {
  836. if ((*i)->name_ == name)
  837. return *i;
  838. if (recursive)
  839. {
  840. UIElement* element = (*i)->GetChild(name, true);
  841. if (element)
  842. return element;
  843. }
  844. }
  845. return 0;
  846. }
  847. UIElement* UIElement::GetRoot() const
  848. {
  849. UIElement* root = parent_;
  850. if (!root)
  851. return 0;
  852. while (root->GetParent())
  853. root = root->GetParent();
  854. return root;
  855. }
  856. unsigned UIElement::GetUIntColor()
  857. {
  858. if (derivedColorDirty_)
  859. {
  860. Color color = color_[C_TOPLEFT];
  861. color.a_ *= GetDerivedOpacity();
  862. uintColor_ = color.ToUInt();
  863. derivedColorDirty_ = false;
  864. }
  865. return uintColor_;
  866. }
  867. const Variant& UIElement::GetVar(ShortStringHash key) const
  868. {
  869. VariantMap::ConstIterator i = vars_.Find(key);
  870. if (i != vars_.End())
  871. return i->second_;
  872. else
  873. return Variant::EMPTY;
  874. }
  875. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  876. {
  877. return screenPosition - GetScreenPosition();
  878. }
  879. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  880. {
  881. return position + GetScreenPosition();
  882. }
  883. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  884. {
  885. if (isScreen)
  886. position = ScreenToElement(position);
  887. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  888. }
  889. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  890. {
  891. // If child elements are clipped, no need to expand the rect
  892. if (clipChildren_)
  893. return IsInside(position, isScreen);
  894. if (!isScreen)
  895. position = ElementToScreen(position);
  896. IntRect combined = GetCombinedScreenRect();
  897. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  898. position.y_ < combined.bottom_;
  899. }
  900. IntRect UIElement::GetCombinedScreenRect()
  901. {
  902. IntVector2 screenPosition(GetScreenPosition());
  903. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  904. if (!clipChildren_)
  905. {
  906. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  907. {
  908. IntVector2 childPos = (*i)->GetScreenPosition();
  909. const IntVector2& childSize = (*i)->GetSize();
  910. if (childPos.x_ < combined.left_)
  911. combined.left_ = childPos.x_;
  912. if (childPos.y_ < combined.top_)
  913. combined.top_ = childPos.y_;
  914. if (childPos.x_ + childSize.x_ > combined.right_)
  915. combined.right_ = childPos.x_ + childSize.x_;
  916. if (childPos.y_ + childSize.y_ > combined.bottom_)
  917. combined.bottom_ = childPos.y_ + childSize.y_;
  918. }
  919. }
  920. return combined;
  921. }
  922. void UIElement::SortChildren()
  923. {
  924. if (sortChildren_ && sortOrderDirty_)
  925. {
  926. Sort(children_.Begin(), children_.End(), CompareUIElements);
  927. sortOrderDirty_ = false;
  928. }
  929. }
  930. void UIElement::SetChildOffset(const IntVector2& offset)
  931. {
  932. if (offset != childOffset_)
  933. {
  934. childOffset_ = offset;
  935. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  936. (*i)->MarkDirty();
  937. }
  938. }
  939. void UIElement::SetHovering(bool enable)
  940. {
  941. hovering_ = enable;
  942. }
  943. void UIElement::AdjustScissor(IntRect& currentScissor)
  944. {
  945. if (clipChildren_)
  946. {
  947. IntVector2 screenPos = GetScreenPosition();
  948. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  949. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  950. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  951. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  952. if (currentScissor.right_ < currentScissor.left_)
  953. currentScissor.right_ = currentScissor.left_;
  954. if (currentScissor.bottom_ < currentScissor.top_)
  955. currentScissor.bottom_ = currentScissor.top_;
  956. }
  957. }
  958. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, IntRect
  959. currentScissor)
  960. {
  961. unsigned initialSize = quads.Size();
  962. GetBatches(batches, quads, currentScissor);
  963. for (unsigned i = initialSize; i < quads.Size(); ++i)
  964. {
  965. quads[i].left_ += offset.x_;
  966. quads[i].top_ += offset.y_;
  967. quads[i].right_ += offset.x_;
  968. quads[i].bottom_ += offset.y_;
  969. }
  970. AdjustScissor(currentScissor);
  971. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  972. {
  973. if ((*i)->IsVisible())
  974. (*i)->GetBatchesWithOffset(offset, batches, quads, currentScissor);
  975. }
  976. }
  977. void UIElement::MarkDirty()
  978. {
  979. positionDirty_ = true;
  980. opacityDirty_ = true;
  981. derivedColorDirty_ = true;
  982. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  983. (*i)->MarkDirty();
  984. }
  985. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  986. {
  987. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  988. {
  989. UIElement* element = *i;
  990. dest.Push(element);
  991. if (!element->children_.Empty())
  992. element->GetChildrenRecursive(dest);
  993. }
  994. }
  995. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  996. {
  997. int width = begin + end;
  998. for (unsigned i = 0; i < sizes.Size(); ++i)
  999. {
  1000. // If calculating maximum size, and the default is specified, do not overflow it
  1001. if (sizes[i] == M_MAX_INT)
  1002. return M_MAX_INT;
  1003. width += sizes[i];
  1004. if (i < sizes.Size() - 1)
  1005. width += spacing;
  1006. }
  1007. return width;
  1008. }
  1009. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1010. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1011. {
  1012. int numChildren = sizes.Size();
  1013. if (!numChildren)
  1014. return;
  1015. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1016. if (targetTotalSize < 0)
  1017. targetTotalSize = 0;
  1018. int targetChildSize = targetTotalSize / numChildren;
  1019. int remainder = targetTotalSize % numChildren;
  1020. float add = (float)remainder / numChildren;
  1021. float acc = 0.0f;
  1022. // Initial pass
  1023. for (int i = 0; i < numChildren; ++i)
  1024. {
  1025. int targetSize = targetChildSize;
  1026. if (remainder)
  1027. {
  1028. acc += add;
  1029. if (acc >= 0.5f)
  1030. {
  1031. acc -= 1.0f;
  1032. ++targetSize;
  1033. --remainder;
  1034. }
  1035. }
  1036. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1037. }
  1038. // Error correction passes
  1039. for (;;)
  1040. {
  1041. int actualTotalSize = 0;
  1042. for (int i = 0; i < numChildren; ++i)
  1043. actualTotalSize += sizes[i];
  1044. int error = targetTotalSize - actualTotalSize;
  1045. // Break if no error
  1046. if (!error)
  1047. break;
  1048. // Check which of the children can be resized to correct the error. If none, must break
  1049. PODVector<unsigned> resizable;
  1050. for (int i = 0; i < numChildren; ++i)
  1051. {
  1052. if (error < 0 && sizes[i] > minSizes[i])
  1053. resizable.Push(i);
  1054. else if (error > 0 && sizes[i] < maxSizes[i])
  1055. resizable.Push(i);
  1056. }
  1057. if (resizable.Empty())
  1058. break;
  1059. int numResizable = resizable.Size();
  1060. int errorPerChild = error / numResizable;
  1061. remainder = (abs(error)) % numResizable;
  1062. add = (float)remainder / numResizable;
  1063. acc = 0.0f;
  1064. for (int i = 0; i < numResizable; ++i)
  1065. {
  1066. unsigned index = resizable[i];
  1067. int targetSize = sizes[index] + errorPerChild;
  1068. if (remainder)
  1069. {
  1070. acc += add;
  1071. if (acc >= 0.5f)
  1072. {
  1073. acc -= 1.0f;
  1074. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1075. --remainder;
  1076. }
  1077. }
  1078. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1079. }
  1080. }
  1081. // Calculate final positions and store the minimum child element size
  1082. layoutMinSize_ = M_MAX_INT;
  1083. int position = begin;
  1084. for (int i = 0; i < numChildren; ++i)
  1085. {
  1086. positions[i] = position;
  1087. position += sizes[i];
  1088. position += spacing;
  1089. if (sizes[i] < layoutMinSize_)
  1090. layoutMinSize_ = sizes[i];
  1091. }
  1092. }
  1093. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1094. {
  1095. IntVector2 ret(IntVector2::ZERO);
  1096. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1097. switch (ha)
  1098. {
  1099. case HA_LEFT:
  1100. ret.x_ = layoutBorder_.left_;
  1101. break;
  1102. case HA_RIGHT:
  1103. ret.x_ = -layoutBorder_.right_;
  1104. break;
  1105. }
  1106. VerticalAlignment va = child->GetVerticalAlignment();
  1107. switch (va)
  1108. {
  1109. case VA_TOP:
  1110. ret.y_ = layoutBorder_.top_;
  1111. break;
  1112. case VA_BOTTOM:
  1113. ret.y_ = -layoutBorder_.bottom_;
  1114. break;
  1115. }
  1116. return ret;
  1117. }