UIElement.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. 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.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::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 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. int maxChildWidth = M_MAX_INT;
  601. for (unsigned i = 0; i < children_.Size(); ++i)
  602. {
  603. if (!children_[i]->IsVisible())
  604. continue;
  605. positions.Push(0);
  606. sizes.Push(children_[i]->GetHeight());
  607. minSizes.Push(children_[i]->GetMinHeight());
  608. maxSizes.Push(children_[i]->GetMaxHeight());
  609. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth());
  610. }
  611. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  612. layoutSpacing_);
  613. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  614. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  615. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  616. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  617. if (minSize_.x_ != maxSize_.x_)
  618. minSize_.x_ = minWidth;
  619. if (minSize_.y_ != maxSize_.y_)
  620. minSize_.y_ = minHeight;
  621. SetSize(width, height);
  622. width = size_.x_;
  623. height = size_.y_;
  624. unsigned j = 0;
  625. for (unsigned i = 0; i < children_.Size(); ++i)
  626. {
  627. if (!children_[i]->IsVisible())
  628. continue;
  629. children_[i]->SetVerticalAlignment(VA_TOP);
  630. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  631. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  632. ++j;
  633. }
  634. }
  635. EnableLayoutUpdate();
  636. }
  637. void UIElement::DisableLayoutUpdate()
  638. {
  639. ++layoutNestingLevel_;
  640. }
  641. void UIElement::EnableLayoutUpdate()
  642. {
  643. --layoutNestingLevel_;
  644. }
  645. void UIElement::BringToFront()
  646. {
  647. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  648. UIElement* root = GetRoot();
  649. UIElement* ptr = this;
  650. while (ptr && ptr->GetParent() != root)
  651. ptr = ptr->GetParent();
  652. if (!ptr || !ptr->GetBringToFront())
  653. return;
  654. // Get the highest priority used by all other top level elements, assign that to the new front element
  655. // and decrease others' priority by one. However, take into account only active (enabled) elements
  656. // and those which have the BringToBack flag set
  657. int maxPriority = M_MIN_INT;
  658. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  659. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  660. {
  661. UIElement* other = *i;
  662. if (other->IsActive() && other->bringToBack_ && other != ptr)
  663. {
  664. int priority = other->GetPriority();
  665. maxPriority = Max(priority, maxPriority);
  666. other->SetPriority(priority - 1);
  667. }
  668. }
  669. if (maxPriority != M_MIN_INT)
  670. ptr->SetPriority(maxPriority);
  671. }
  672. void UIElement::AddChild(UIElement* element)
  673. {
  674. InsertChild(children_.Size(), element);
  675. }
  676. void UIElement::InsertChild(unsigned index, UIElement* element)
  677. {
  678. // Check for illegal or redundant parent assignment
  679. if (!element || element == this || element->parent_ == this)
  680. return;
  681. // Check for possible cyclic parent assignment
  682. UIElement* parent = parent_;
  683. while (parent)
  684. {
  685. if (parent == element)
  686. return;
  687. parent = parent->parent_;
  688. }
  689. // Add first, then remove from old parent, to ensure the element does not get deleted
  690. if (index >= children_.Size())
  691. children_.Push(SharedPtr<UIElement>(element));
  692. else
  693. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  694. if (element->parent_)
  695. element->parent_->RemoveChild(element);
  696. if (sortChildren_)
  697. sortOrderDirty_ = true;
  698. element->parent_ = this;
  699. element->MarkDirty();
  700. UpdateLayout();
  701. }
  702. void UIElement::RemoveChild(UIElement* element)
  703. {
  704. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  705. {
  706. if (*i == element)
  707. {
  708. element->parent_ = 0;
  709. element->MarkDirty();
  710. children_.Erase(i);
  711. UpdateLayout();
  712. return;
  713. }
  714. }
  715. }
  716. void UIElement::RemoveAllChildren()
  717. {
  718. while (children_.Size())
  719. {
  720. const SharedPtr<UIElement>& element = children_.Back();
  721. element->parent_ = 0;
  722. element->MarkDirty();
  723. children_.Pop();
  724. }
  725. }
  726. void UIElement::Remove()
  727. {
  728. if (parent_)
  729. parent_->RemoveChild(this);
  730. }
  731. void UIElement::SetParent(UIElement* parent)
  732. {
  733. if (parent)
  734. parent->AddChild(this);
  735. }
  736. IntVector2 UIElement::GetScreenPosition()
  737. {
  738. if (positionDirty_)
  739. {
  740. IntVector2 pos = position_;
  741. const UIElement* parent = parent_;
  742. const UIElement* current = this;
  743. while (parent)
  744. {
  745. switch (current->horizontalAlignment_)
  746. {
  747. case HA_LEFT:
  748. pos.x_ += parent->position_.x_;
  749. break;
  750. case HA_CENTER:
  751. pos.x_ += parent->position_.x_ + parent->size_.x_ / 2 - current->size_.x_ / 2;
  752. break;
  753. case HA_RIGHT:
  754. pos.x_ += parent->position_.x_ + parent->size_.x_ - current->size_.x_;
  755. break;
  756. }
  757. switch (current->verticalAlignment_)
  758. {
  759. case VA_TOP:
  760. pos.y_ += parent->position_.y_;
  761. break;
  762. case VA_CENTER:
  763. pos.y_ += parent->position_.y_ + parent->size_.y_ / 2 - current->size_.y_ / 2;
  764. break;
  765. case VA_BOTTOM:
  766. pos.y_ += parent->position_.y_ + parent->size_.y_ - current->size_.y_;
  767. break;
  768. }
  769. pos += parent->childOffset_;
  770. current = parent;
  771. parent = parent->parent_;
  772. }
  773. screenPosition_ = pos;
  774. positionDirty_ = false;
  775. }
  776. return screenPosition_;
  777. }
  778. float UIElement::GetDerivedOpacity()
  779. {
  780. if (opacityDirty_)
  781. {
  782. float opacity = opacity_;
  783. const UIElement* parent = parent_;
  784. while (parent)
  785. {
  786. opacity *= parent->opacity_;
  787. parent = parent->parent_;
  788. }
  789. derivedOpacity_ = opacity;
  790. opacityDirty_ = false;
  791. }
  792. return derivedOpacity_;
  793. }
  794. bool UIElement::HasFocus() const
  795. {
  796. UI* ui = GetSubsystem<UI>();
  797. if (!ui)
  798. return false;
  799. else
  800. return ui->GetFocusElement() == this;
  801. }
  802. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  803. {
  804. dest.Clear();
  805. if (!recursive)
  806. {
  807. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  808. dest.Push(*i);
  809. }
  810. else
  811. GetChildrenRecursive(dest);
  812. }
  813. unsigned UIElement::GetNumChildren(bool recursive) const
  814. {
  815. if (!recursive)
  816. return children_.Size();
  817. else
  818. {
  819. unsigned allChildren = children_.Size();
  820. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  821. allChildren += (*i)->GetNumChildren(true);
  822. return allChildren;
  823. }
  824. }
  825. UIElement* UIElement::GetChild(unsigned index) const
  826. {
  827. return index < children_.Size() ? children_[index] : (UIElement*)0;
  828. }
  829. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  830. {
  831. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  832. {
  833. if ((*i)->name_ == name)
  834. return *i;
  835. if (recursive)
  836. {
  837. UIElement* element = (*i)->GetChild(name, true);
  838. if (element)
  839. return element;
  840. }
  841. }
  842. return 0;
  843. }
  844. UIElement* UIElement::GetRoot() const
  845. {
  846. UIElement* root = parent_;
  847. if (!root)
  848. return 0;
  849. while (root->GetParent())
  850. root = root->GetParent();
  851. return root;
  852. }
  853. unsigned UIElement::GetUIntColor()
  854. {
  855. if (derivedColorDirty_)
  856. {
  857. Color color = color_[C_TOPLEFT];
  858. color.a_ *= GetDerivedOpacity();
  859. uintColor_ = color.ToUInt();
  860. derivedColorDirty_ = false;
  861. }
  862. return uintColor_;
  863. }
  864. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  865. {
  866. return screenPosition - GetScreenPosition();
  867. }
  868. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  869. {
  870. return position + GetScreenPosition();
  871. }
  872. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  873. {
  874. if (isScreen)
  875. position = ScreenToElement(position);
  876. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  877. }
  878. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  879. {
  880. // If child elements are clipped, no need to expand the rect
  881. if (clipChildren_)
  882. return IsInside(position, isScreen);
  883. if (!isScreen)
  884. position = ElementToScreen(position);
  885. IntRect combined = GetCombinedScreenRect();
  886. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  887. position.y_ < combined.bottom_;
  888. }
  889. IntRect UIElement::GetCombinedScreenRect()
  890. {
  891. IntVector2 screenPosition(GetScreenPosition());
  892. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  893. if (!clipChildren_)
  894. {
  895. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  896. {
  897. IntVector2 childPos = (*i)->GetScreenPosition();
  898. const IntVector2& childSize = (*i)->GetSize();
  899. if (childPos.x_ < combined.left_)
  900. combined.left_ = childPos.x_;
  901. if (childPos.y_ < combined.top_)
  902. combined.top_ = childPos.y_;
  903. if (childPos.x_ + childSize.x_ > combined.right_)
  904. combined.right_ = childPos.x_ + childSize.x_;
  905. if (childPos.y_ + childSize.y_ > combined.bottom_)
  906. combined.bottom_ = childPos.y_ + childSize.y_;
  907. }
  908. }
  909. return combined;
  910. }
  911. void UIElement::SortChildren()
  912. {
  913. if (sortChildren_ && sortOrderDirty_)
  914. {
  915. Sort(children_.Begin(), children_.End(), CompareUIElements);
  916. sortOrderDirty_ = false;
  917. }
  918. }
  919. void UIElement::SetChildOffset(const IntVector2& offset)
  920. {
  921. if (offset != childOffset_)
  922. {
  923. childOffset_ = offset;
  924. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  925. (*i)->MarkDirty();
  926. }
  927. }
  928. void UIElement::SetHovering(bool enable)
  929. {
  930. hovering_ = enable;
  931. }
  932. void UIElement::AdjustScissor(IntRect& currentScissor)
  933. {
  934. if (clipChildren_)
  935. {
  936. IntVector2 screenPos = GetScreenPosition();
  937. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  938. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  939. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  940. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  941. if (currentScissor.right_ < currentScissor.left_)
  942. currentScissor.right_ = currentScissor.left_;
  943. if (currentScissor.bottom_ < currentScissor.top_)
  944. currentScissor.bottom_ = currentScissor.top_;
  945. }
  946. }
  947. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, IntRect
  948. currentScissor)
  949. {
  950. unsigned initialSize = quads.Size();
  951. GetBatches(batches, quads, currentScissor);
  952. for (unsigned i = initialSize; i < quads.Size(); ++i)
  953. {
  954. quads[i].left_ += offset.x_;
  955. quads[i].top_ += offset.y_;
  956. quads[i].right_ += offset.x_;
  957. quads[i].bottom_ += offset.y_;
  958. }
  959. AdjustScissor(currentScissor);
  960. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  961. {
  962. if ((*i)->IsVisible())
  963. (*i)->GetBatchesWithOffset(offset, batches, quads, currentScissor);
  964. }
  965. }
  966. void UIElement::MarkDirty()
  967. {
  968. positionDirty_ = true;
  969. opacityDirty_ = true;
  970. derivedColorDirty_ = true;
  971. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  972. (*i)->MarkDirty();
  973. }
  974. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  975. {
  976. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  977. {
  978. UIElement* element = *i;
  979. dest.Push(element);
  980. if (!element->children_.Empty())
  981. element->GetChildrenRecursive(dest);
  982. }
  983. }
  984. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  985. {
  986. int width = begin + end;
  987. for (unsigned i = 0; i < sizes.Size(); ++i)
  988. {
  989. // If calculating maximum size, and the default is specified, do not overflow it
  990. if (sizes[i] == M_MAX_INT)
  991. return M_MAX_INT;
  992. width += sizes[i];
  993. if (i < sizes.Size() - 1)
  994. width += spacing;
  995. }
  996. return width;
  997. }
  998. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  999. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1000. {
  1001. int numChildren = sizes.Size();
  1002. if (!numChildren)
  1003. return;
  1004. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1005. if (targetTotalSize < 0)
  1006. targetTotalSize = 0;
  1007. int targetChildSize = targetTotalSize / numChildren;
  1008. int remainder = targetTotalSize % numChildren;
  1009. float add = (float)remainder / numChildren;
  1010. float acc = 0.0f;
  1011. // Initial pass
  1012. for (int i = 0; i < numChildren; ++i)
  1013. {
  1014. int targetSize = targetChildSize;
  1015. if (remainder)
  1016. {
  1017. acc += add;
  1018. if (acc >= 0.5f)
  1019. {
  1020. acc -= 1.0f;
  1021. ++targetSize;
  1022. --remainder;
  1023. }
  1024. }
  1025. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1026. }
  1027. // Error correction passes
  1028. for (;;)
  1029. {
  1030. int actualTotalSize = 0;
  1031. for (int i = 0; i < numChildren; ++i)
  1032. actualTotalSize += sizes[i];
  1033. int error = targetTotalSize - actualTotalSize;
  1034. // Break if no error
  1035. if (!error)
  1036. break;
  1037. // Check which of the children can be resized to correct the error. If none, must break
  1038. PODVector<unsigned> resizable;
  1039. for (int i = 0; i < numChildren; ++i)
  1040. {
  1041. if (error < 0 && sizes[i] > minSizes[i])
  1042. resizable.Push(i);
  1043. else if (error > 0 && sizes[i] < maxSizes[i])
  1044. resizable.Push(i);
  1045. }
  1046. if (resizable.Empty())
  1047. break;
  1048. int numResizable = resizable.Size();
  1049. int errorPerChild = error / numResizable;
  1050. remainder = (abs(error)) % numResizable;
  1051. add = (float)remainder / numResizable;
  1052. acc = 0.0f;
  1053. for (int i = 0; i < numResizable; ++i)
  1054. {
  1055. unsigned index = resizable[i];
  1056. int targetSize = sizes[index] + errorPerChild;
  1057. if (remainder)
  1058. {
  1059. acc += add;
  1060. if (acc >= 0.5f)
  1061. {
  1062. acc -= 1.0f;
  1063. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1064. --remainder;
  1065. }
  1066. }
  1067. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1068. }
  1069. }
  1070. // Calculate final positions and store the minimum child element size
  1071. layoutMinSize_ = M_MAX_INT;
  1072. int position = begin;
  1073. for (int i = 0; i < numChildren; ++i)
  1074. {
  1075. positions[i] = position;
  1076. position += sizes[i];
  1077. position += spacing;
  1078. if (sizes[i] < layoutMinSize_)
  1079. layoutMinSize_ = sizes[i];
  1080. }
  1081. }
  1082. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1083. {
  1084. IntVector2 ret(IntVector2::ZERO);
  1085. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1086. switch (ha)
  1087. {
  1088. case HA_LEFT:
  1089. ret.x_ = layoutBorder_.left_;
  1090. break;
  1091. case HA_RIGHT:
  1092. ret.x_ = -layoutBorder_.right_;
  1093. break;
  1094. }
  1095. VerticalAlignment va = child->GetVerticalAlignment();
  1096. switch (va)
  1097. {
  1098. case VA_TOP:
  1099. ret.y_ = layoutBorder_.top_;
  1100. break;
  1101. case VA_BOTTOM:
  1102. ret.y_ = -layoutBorder_.bottom_;
  1103. break;
  1104. }
  1105. return ret;
  1106. }