UIElement.cpp 38 KB

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