UIElement.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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::SetTempVisible(bool enable)
  944. {
  945. visible_ = enable;
  946. }
  947. void UIElement::AdjustScissor(IntRect& currentScissor)
  948. {
  949. if (clipChildren_)
  950. {
  951. IntVector2 screenPos = GetScreenPosition();
  952. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  953. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  954. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  955. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  956. if (currentScissor.right_ < currentScissor.left_)
  957. currentScissor.right_ = currentScissor.left_;
  958. if (currentScissor.bottom_ < currentScissor.top_)
  959. currentScissor.bottom_ = currentScissor.top_;
  960. }
  961. }
  962. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, IntRect
  963. currentScissor)
  964. {
  965. unsigned initialSize = quads.Size();
  966. GetBatches(batches, quads, currentScissor);
  967. for (unsigned i = initialSize; i < quads.Size(); ++i)
  968. {
  969. quads[i].left_ += offset.x_;
  970. quads[i].top_ += offset.y_;
  971. quads[i].right_ += offset.x_;
  972. quads[i].bottom_ += offset.y_;
  973. }
  974. AdjustScissor(currentScissor);
  975. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  976. {
  977. if ((*i)->IsVisible())
  978. (*i)->GetBatchesWithOffset(offset, batches, quads, currentScissor);
  979. }
  980. }
  981. void UIElement::MarkDirty()
  982. {
  983. positionDirty_ = true;
  984. opacityDirty_ = true;
  985. derivedColorDirty_ = true;
  986. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  987. (*i)->MarkDirty();
  988. }
  989. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  990. {
  991. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  992. {
  993. UIElement* element = *i;
  994. dest.Push(element);
  995. if (!element->children_.Empty())
  996. element->GetChildrenRecursive(dest);
  997. }
  998. }
  999. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1000. {
  1001. int width = begin + end;
  1002. for (unsigned i = 0; i < sizes.Size(); ++i)
  1003. {
  1004. // If calculating maximum size, and the default is specified, do not overflow it
  1005. if (sizes[i] == M_MAX_INT)
  1006. return M_MAX_INT;
  1007. width += sizes[i];
  1008. if (i < sizes.Size() - 1)
  1009. width += spacing;
  1010. }
  1011. return width;
  1012. }
  1013. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1014. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1015. {
  1016. int numChildren = sizes.Size();
  1017. if (!numChildren)
  1018. return;
  1019. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1020. if (targetTotalSize < 0)
  1021. targetTotalSize = 0;
  1022. int targetChildSize = targetTotalSize / numChildren;
  1023. int remainder = targetTotalSize % numChildren;
  1024. float add = (float)remainder / numChildren;
  1025. float acc = 0.0f;
  1026. // Initial pass
  1027. for (int i = 0; i < numChildren; ++i)
  1028. {
  1029. int targetSize = targetChildSize;
  1030. if (remainder)
  1031. {
  1032. acc += add;
  1033. if (acc >= 0.5f)
  1034. {
  1035. acc -= 1.0f;
  1036. ++targetSize;
  1037. --remainder;
  1038. }
  1039. }
  1040. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1041. }
  1042. // Error correction passes
  1043. for (;;)
  1044. {
  1045. int actualTotalSize = 0;
  1046. for (int i = 0; i < numChildren; ++i)
  1047. actualTotalSize += sizes[i];
  1048. int error = targetTotalSize - actualTotalSize;
  1049. // Break if no error
  1050. if (!error)
  1051. break;
  1052. // Check which of the children can be resized to correct the error. If none, must break
  1053. PODVector<unsigned> resizable;
  1054. for (int i = 0; i < numChildren; ++i)
  1055. {
  1056. if (error < 0 && sizes[i] > minSizes[i])
  1057. resizable.Push(i);
  1058. else if (error > 0 && sizes[i] < maxSizes[i])
  1059. resizable.Push(i);
  1060. }
  1061. if (resizable.Empty())
  1062. break;
  1063. int numResizable = resizable.Size();
  1064. int errorPerChild = error / numResizable;
  1065. remainder = (abs(error)) % numResizable;
  1066. add = (float)remainder / numResizable;
  1067. acc = 0.0f;
  1068. for (int i = 0; i < numResizable; ++i)
  1069. {
  1070. unsigned index = resizable[i];
  1071. int targetSize = sizes[index] + errorPerChild;
  1072. if (remainder)
  1073. {
  1074. acc += add;
  1075. if (acc >= 0.5f)
  1076. {
  1077. acc -= 1.0f;
  1078. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1079. --remainder;
  1080. }
  1081. }
  1082. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1083. }
  1084. }
  1085. // Calculate final positions and store the minimum child element size
  1086. layoutMinSize_ = M_MAX_INT;
  1087. int position = begin;
  1088. for (int i = 0; i < numChildren; ++i)
  1089. {
  1090. positions[i] = position;
  1091. position += sizes[i];
  1092. position += spacing;
  1093. if (sizes[i] < layoutMinSize_)
  1094. layoutMinSize_ = sizes[i];
  1095. }
  1096. }
  1097. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1098. {
  1099. IntVector2 ret(IntVector2::ZERO);
  1100. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1101. switch (ha)
  1102. {
  1103. case HA_LEFT:
  1104. ret.x_ = layoutBorder_.left_;
  1105. break;
  1106. case HA_RIGHT:
  1107. ret.x_ = -layoutBorder_.right_;
  1108. break;
  1109. }
  1110. VerticalAlignment va = child->GetVerticalAlignment();
  1111. switch (va)
  1112. {
  1113. case VA_TOP:
  1114. ret.y_ = layoutBorder_.top_;
  1115. break;
  1116. case VA_BOTTOM:
  1117. ret.y_ = -layoutBorder_.bottom_;
  1118. break;
  1119. }
  1120. return ret;
  1121. }