UIElement.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "Cursor.h"
  25. #include "HashSet.h"
  26. #include "Log.h"
  27. #include "ResourceCache.h"
  28. #include "Sort.h"
  29. #include "StringUtils.h"
  30. #include "UI.h"
  31. #include "UIElement.h"
  32. #include "UIEvents.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. const char* horizontalAlignments[] =
  37. {
  38. "Left",
  39. "Center",
  40. "Right",
  41. 0
  42. };
  43. const char* verticalAlignments[] =
  44. {
  45. "Top",
  46. "Center",
  47. "Bottom",
  48. 0
  49. };
  50. static const char* focusModes[] =
  51. {
  52. "NotFocusable",
  53. "ResetFocus",
  54. "Focusable",
  55. "FocusableDefocusable",
  56. 0
  57. };
  58. static const char* dragDropModes[] =
  59. {
  60. "Disabled",
  61. "Source",
  62. "Target",
  63. "SourceAndTarget",
  64. 0
  65. };
  66. static const char* layoutModes[] =
  67. {
  68. "Free",
  69. "Horizontal",
  70. "Vertical",
  71. 0
  72. };
  73. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  74. {
  75. return lhs->GetPriority() < rhs->GetPriority();
  76. }
  77. template<> HorizontalAlignment Variant::Get<HorizontalAlignment>() const
  78. {
  79. return (HorizontalAlignment)GetInt();
  80. }
  81. template<> VerticalAlignment Variant::Get<VerticalAlignment>() const
  82. {
  83. return (VerticalAlignment)GetInt();
  84. }
  85. template<> FocusMode Variant::Get<FocusMode>() const
  86. {
  87. return (FocusMode)GetInt();
  88. }
  89. template<> LayoutMode Variant::Get<LayoutMode>() const
  90. {
  91. return (LayoutMode)GetInt();
  92. }
  93. OBJECTTYPESTATIC(UIElement);
  94. UIElement::UIElement(Context* context) :
  95. Serializable(context),
  96. parent_(0),
  97. clipBorder_(IntRect::ZERO),
  98. priority_(0),
  99. bringToFront_(false),
  100. bringToBack_(true),
  101. clipChildren_(false),
  102. sortChildren_(true),
  103. useDerivedOpacity_(true),
  104. enabled_(false),
  105. selected_(false),
  106. visible_(true),
  107. hovering_(false),
  108. internal_(false),
  109. focusMode_(FM_NOTFOCUSABLE),
  110. dragDropMode_(DD_DISABLED),
  111. layoutMode_(LM_FREE),
  112. layoutSpacing_(0),
  113. layoutBorder_(IntRect::ZERO),
  114. resizeNestingLevel_(0),
  115. layoutNestingLevel_(0),
  116. layoutMinSize_(0),
  117. indent_(0),
  118. indentSpacing_(16),
  119. position_(IntVector2::ZERO),
  120. positionDirty_(true),
  121. size_(IntVector2::ZERO),
  122. minSize_(IntVector2::ZERO),
  123. maxSize_(M_MAX_INT, M_MAX_INT),
  124. childOffset_(IntVector2::ZERO),
  125. horizontalAlignment_(HA_LEFT),
  126. verticalAlignment_(VA_TOP),
  127. opacity_(1.0f),
  128. opacityDirty_(true),
  129. derivedColorDirty_(true),
  130. sortOrderDirty_(false),
  131. colorGradient_(false),
  132. traversalMode_(TM_BREADTH_FIRST),
  133. elementEventSender_(false)
  134. {
  135. }
  136. UIElement::~UIElement()
  137. {
  138. // If child elements have outside references, detach them
  139. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  140. {
  141. if (i->Refs() > 1)
  142. (*i)->Detach();
  143. }
  144. }
  145. void UIElement::RegisterObject(Context* context)
  146. {
  147. context->RegisterFactory<UIElement>();
  148. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_FILE);
  149. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  150. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  151. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  152. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2::ZERO, AM_FILE);
  153. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_FILE);
  154. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_FILE);
  155. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  156. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  157. ACCESSOR_ATTRIBUTE(UIElement, VAR_FLOAT, "Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  158. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_COLOR, "Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  159. ATTRIBUTE(UIElement, VAR_COLOR, "Top Left Color", color_[0], Color::WHITE, AM_FILE);
  160. ATTRIBUTE(UIElement, VAR_COLOR, "Top Right Color", color_[1], Color::WHITE, AM_FILE);
  161. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Left Color", color_[2], Color::WHITE, AM_FILE);
  162. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Right Color", color_[3], Color::WHITE, AM_FILE);
  163. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, false, AM_FILE);
  164. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  165. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  166. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  167. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  168. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  169. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Use Derived Opacity", GetUseDerivedOpacity, SetUseDerivedOpacity, bool, false, AM_FILE);
  170. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  171. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  172. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  173. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  174. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  175. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Indent", GetIndent, SetIndent, int, 0, AM_FILE);
  176. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Indent Spacing", GetIndentSpacing, SetIndentSpacing, int, 16, AM_FILE);
  177. ATTRIBUTE(UIElement, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE);
  178. }
  179. void UIElement::ApplyAttributes()
  180. {
  181. colorGradient_ = false;
  182. derivedColorDirty_ = true;
  183. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  184. {
  185. if (color_[i] != color_[0])
  186. colorGradient_ = true;
  187. }
  188. }
  189. bool UIElement::LoadXML(const XMLElement& source)
  190. {
  191. return LoadXML(source, 0);
  192. }
  193. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile)
  194. {
  195. // Apply the style first, but only for non-internal elements
  196. if (!internal_ && styleFile)
  197. {
  198. // Use style override if defined, otherwise type name
  199. String styleName = source.GetAttribute("style");
  200. if (styleName.Empty())
  201. styleName = GetTypeName();
  202. SetStyle(styleFile, styleName);
  203. }
  204. // Then load rest of the attributes from the source
  205. if (!Serializable::LoadXML(source))
  206. return false;
  207. unsigned nextInternalChild = 0;
  208. // Load child elements. Internal elements are not to be created as they already exist
  209. XMLElement childElem = source.GetChild("element");
  210. while (childElem)
  211. {
  212. bool internalElem = childElem.GetBool("internal");
  213. String typeName = childElem.GetAttribute("type");
  214. if (typeName.Empty())
  215. typeName = "UIElement";
  216. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  217. UIElement* child = 0;
  218. if (!internalElem)
  219. child = CreateChild(typeName, String::EMPTY, index);
  220. else
  221. {
  222. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  223. {
  224. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  225. {
  226. child = children_[i];
  227. nextInternalChild = i + 1;
  228. break;
  229. }
  230. }
  231. if (!child)
  232. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  233. }
  234. if (child)
  235. {
  236. if (!child->LoadXML(childElem, styleFile))
  237. return false;
  238. }
  239. childElem = childElem.GetNext("element");
  240. }
  241. ApplyAttributes();
  242. return true;
  243. }
  244. bool UIElement::SaveXML(XMLElement& dest)
  245. {
  246. // Write type and internal flag
  247. if (!dest.SetString("type", GetTypeName()))
  248. return false;
  249. if (internal_)
  250. {
  251. if (!dest.SetBool("internal", internal_))
  252. return false;
  253. }
  254. // Write attributes
  255. if (!Serializable::SaveXML(dest))
  256. return false;
  257. // Write child elements
  258. for (unsigned i = 0; i < children_.Size(); ++i)
  259. {
  260. UIElement* element = children_[i];
  261. XMLElement childElem = dest.CreateChild("element");
  262. if (!element->SaveXML(childElem))
  263. return false;
  264. }
  265. return true;
  266. }
  267. void UIElement::Update(float timeStep)
  268. {
  269. }
  270. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  271. {
  272. // Reset hovering for next frame
  273. hovering_ = false;
  274. }
  275. bool UIElement::IsWithinScissor(const IntRect& currentScissor)
  276. {
  277. if (!visible_)
  278. return false;
  279. const IntVector2& screenPos = GetScreenPosition();
  280. return screenPos.x_ < currentScissor.right_ && screenPos.x_ + GetWidth() > currentScissor.left_ &&
  281. screenPos.y_ < currentScissor.bottom_ && screenPos.y_ + GetHeight() > currentScissor.top_;
  282. }
  283. const IntVector2& UIElement::GetScreenPosition() const
  284. {
  285. if (positionDirty_)
  286. {
  287. IntVector2 pos = position_;
  288. const UIElement* parent = parent_;
  289. if (parent)
  290. {
  291. const IntVector2& parentScreenPos = parent->GetScreenPosition();
  292. switch (horizontalAlignment_)
  293. {
  294. case HA_LEFT:
  295. pos.x_ += parentScreenPos.x_;
  296. break;
  297. case HA_CENTER:
  298. pos.x_ += parentScreenPos.x_ + parent_->size_.x_ / 2 - size_.x_ / 2;
  299. break;
  300. case HA_RIGHT:
  301. pos.x_ += parentScreenPos.x_ + parent_->size_.x_ - size_.x_;
  302. break;
  303. }
  304. switch (verticalAlignment_)
  305. {
  306. case VA_TOP:
  307. pos.y_ += parentScreenPos.y_;
  308. break;
  309. case VA_CENTER:
  310. pos.y_ += parentScreenPos.y_ + parent_->size_.y_ / 2 - size_.y_ / 2;
  311. break;
  312. case VA_BOTTOM:
  313. pos.y_ += parentScreenPos.y_ + parent_->size_.y_ - size_.y_;
  314. break;
  315. }
  316. pos += parent_->childOffset_;
  317. }
  318. screenPosition_ = pos;
  319. positionDirty_ = false;
  320. }
  321. return screenPosition_;
  322. }
  323. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  324. {
  325. if (cursor && cursor->IsVisible())
  326. cursor->SetShape(CS_NORMAL);
  327. hovering_ = true;
  328. }
  329. void UIElement::OnClick(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  330. {
  331. }
  332. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  333. {
  334. }
  335. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  336. {
  337. }
  338. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)
  339. {
  340. }
  341. bool UIElement::OnDragDropTest(UIElement* source)
  342. {
  343. return true;
  344. }
  345. bool UIElement::OnDragDropFinish(UIElement* source)
  346. {
  347. return true;
  348. }
  349. void UIElement::OnWheel(int delta, int buttons, int qualifiers)
  350. {
  351. }
  352. void UIElement::OnKey(int key, int buttons, int qualifiers)
  353. {
  354. }
  355. void UIElement::OnChar(unsigned c, int buttons, int qualifiers)
  356. {
  357. }
  358. void UIElement::OnResize()
  359. {
  360. }
  361. void UIElement::OnPositionSet()
  362. {
  363. }
  364. bool UIElement::LoadXML(Deserializer& source)
  365. {
  366. SharedPtr<XMLFile> xml(new XMLFile(context_));
  367. if (!xml->Load(source))
  368. return false;
  369. return LoadXML(xml->GetRoot());
  370. }
  371. bool UIElement::SaveXML(Serializer& dest)
  372. {
  373. SharedPtr<XMLFile> xml(new XMLFile(context_));
  374. XMLElement rootElem = xml->CreateRoot("element");
  375. if (!SaveXML(rootElem))
  376. return false;
  377. return xml->Save(dest);
  378. }
  379. void UIElement::SetName(const String& name)
  380. {
  381. name_ = name;
  382. using namespace NameChanged;
  383. VariantMap eventData;
  384. eventData[P_ELEMENT] = (void*)this;
  385. SendEvent(E_NAMECHANGED, eventData);
  386. }
  387. void UIElement::SetPosition(const IntVector2& position)
  388. {
  389. if (position != position_)
  390. {
  391. position_ = position;
  392. OnPositionSet();
  393. MarkDirty();
  394. }
  395. }
  396. void UIElement::SetPosition(int x, int y)
  397. {
  398. SetPosition(IntVector2(x, y));
  399. }
  400. void UIElement::SetSize(const IntVector2& size)
  401. {
  402. ++resizeNestingLevel_;
  403. IntVector2 validatedSize;
  404. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  405. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  406. if (validatedSize != size_)
  407. {
  408. size_ = validatedSize;
  409. if (resizeNestingLevel_ == 1)
  410. {
  411. // Check if parent element's layout needs to be updated first
  412. if (parent_)
  413. parent_->UpdateLayout();
  414. MarkDirty();
  415. OnResize();
  416. UpdateLayout();
  417. using namespace Resized;
  418. VariantMap eventData;
  419. eventData[P_ELEMENT] = (void*)this;
  420. eventData[P_WIDTH] = size_.x_;
  421. eventData[P_HEIGHT] = size_.y_;
  422. SendEvent(E_RESIZED, eventData);
  423. }
  424. }
  425. --resizeNestingLevel_;
  426. }
  427. void UIElement::SetSize(int width, int height)
  428. {
  429. SetSize(IntVector2(width, height));
  430. }
  431. void UIElement::SetWidth(int width)
  432. {
  433. SetSize(IntVector2(width, size_.y_));
  434. }
  435. void UIElement::SetHeight(int height)
  436. {
  437. SetSize(IntVector2(size_.x_, height));
  438. }
  439. void UIElement::SetMinSize(const IntVector2& minSize)
  440. {
  441. minSize_.x_ = Max(minSize.x_, 0);
  442. minSize_.y_ = Max(minSize.y_, 0);
  443. SetSize(size_);
  444. }
  445. void UIElement::SetMinSize(int width, int height)
  446. {
  447. SetMinSize(IntVector2(width, height));
  448. }
  449. void UIElement::SetMinWidth(int width)
  450. {
  451. SetMinSize(IntVector2(width, minSize_.y_));
  452. }
  453. void UIElement::SetMinHeight(int height)
  454. {
  455. SetMinSize(IntVector2(minSize_.x_, height));
  456. }
  457. void UIElement::SetMaxSize(const IntVector2& maxSize)
  458. {
  459. maxSize_.x_ = Max(maxSize.x_, 0);
  460. maxSize_.y_ = Max(maxSize.y_, 0);
  461. SetSize(size_);
  462. }
  463. void UIElement::SetMaxSize(int width, int height)
  464. {
  465. SetMaxSize(IntVector2(width, height));
  466. }
  467. void UIElement::SetMaxWidth(int width)
  468. {
  469. SetMaxSize(IntVector2(width, maxSize_.y_));
  470. }
  471. void UIElement::SetMaxHeight(int height)
  472. {
  473. SetMaxSize(IntVector2(maxSize_.x_, height));
  474. }
  475. void UIElement::SetFixedSize(const IntVector2& size)
  476. {
  477. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  478. SetSize(size);
  479. }
  480. void UIElement::SetFixedSize(int width, int height)
  481. {
  482. SetFixedSize(IntVector2(width, height));
  483. }
  484. void UIElement::SetFixedWidth(int width)
  485. {
  486. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  487. SetWidth(width);
  488. }
  489. void UIElement::SetFixedHeight(int height)
  490. {
  491. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  492. SetHeight(height);
  493. }
  494. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  495. {
  496. horizontalAlignment_ = hAlign;
  497. verticalAlignment_ = vAlign;
  498. MarkDirty();
  499. }
  500. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  501. {
  502. horizontalAlignment_ = align;
  503. MarkDirty();
  504. }
  505. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  506. {
  507. verticalAlignment_ = align;
  508. MarkDirty();
  509. }
  510. void UIElement::SetClipBorder(const IntRect& rect)
  511. {
  512. clipBorder_.left_ = Max(rect.left_, 0);
  513. clipBorder_.top_ = Max(rect.top_, 0);
  514. clipBorder_.right_ = Max(rect.right_, 0);
  515. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  516. }
  517. void UIElement::SetColor(const Color& color)
  518. {
  519. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  520. color_[i] = color;
  521. colorGradient_ = false;
  522. derivedColorDirty_ = true;
  523. }
  524. void UIElement::SetColor(Corner corner, const Color& color)
  525. {
  526. color_[corner] = color;
  527. colorGradient_ = false;
  528. derivedColorDirty_ = true;
  529. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  530. {
  531. if (i != corner && color_[i] != color_[corner])
  532. colorGradient_ = true;
  533. }
  534. }
  535. void UIElement::SetPriority(int priority)
  536. {
  537. priority_ = priority;
  538. if (parent_)
  539. parent_->sortOrderDirty_ = true;
  540. }
  541. void UIElement::SetOpacity(float opacity)
  542. {
  543. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  544. MarkDirty();
  545. }
  546. void UIElement::SetBringToFront(bool enable)
  547. {
  548. bringToFront_ = enable;
  549. }
  550. void UIElement::SetBringToBack(bool enable)
  551. {
  552. bringToBack_ = enable;
  553. }
  554. void UIElement::SetClipChildren(bool enable)
  555. {
  556. clipChildren_ = enable;
  557. }
  558. void UIElement::SetSortChildren(bool enable)
  559. {
  560. if (!sortChildren_ && enable)
  561. sortOrderDirty_ = true;
  562. sortChildren_ = enable;
  563. }
  564. void UIElement::SetUseDerivedOpacity(bool enable)
  565. {
  566. useDerivedOpacity_ = enable;
  567. }
  568. void UIElement::SetEnabled(bool enable)
  569. {
  570. enabled_ = enable;
  571. }
  572. void UIElement::SetFocusMode(FocusMode mode)
  573. {
  574. focusMode_ = mode;
  575. }
  576. void UIElement::SetFocus(bool enable)
  577. {
  578. if (focusMode_ < FM_FOCUSABLE)
  579. enable = false;
  580. UI* ui = GetSubsystem<UI>();
  581. if (!ui)
  582. return;
  583. if (enable)
  584. {
  585. if (ui->GetFocusElement() != this)
  586. ui->SetFocusElement(this);
  587. }
  588. else
  589. {
  590. if (ui->GetFocusElement() == this)
  591. ui->SetFocusElement(0);
  592. }
  593. }
  594. void UIElement::SetSelected(bool enable)
  595. {
  596. selected_ = enable;
  597. }
  598. void UIElement::SetVisible(bool enable)
  599. {
  600. if (enable != visible_)
  601. {
  602. visible_ = enable;
  603. // Parent's layout may change as a result of visibility change
  604. if (parent_)
  605. parent_->UpdateLayout();
  606. using namespace VisibleChanged;
  607. VariantMap eventData;
  608. eventData[P_ELEMENT] = (void*)this;
  609. eventData[P_VISIBLE] = visible_;
  610. SendEvent(E_VISIBLECHANGED, eventData);
  611. }
  612. }
  613. void UIElement::SetDragDropMode(unsigned mode)
  614. {
  615. dragDropMode_ = mode;
  616. }
  617. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  618. {
  619. if (!file)
  620. return;
  621. XMLElement rootElem = file->GetRoot();
  622. XMLElement childElem = rootElem.GetChild("element");
  623. while (childElem)
  624. {
  625. if (typeName == childElem.GetAttribute("type"))
  626. {
  627. SetStyle(childElem);
  628. return;
  629. }
  630. childElem = childElem.GetNext("element");
  631. }
  632. }
  633. void UIElement::SetStyle(const XMLElement& element)
  634. {
  635. LoadXML(element);
  636. }
  637. void UIElement::SetStyleAuto(XMLFile* file)
  638. {
  639. SetStyle(file, GetTypeName());
  640. }
  641. void UIElement::SetDefaultStyle(XMLFile* style)
  642. {
  643. defaultStyle_ = style;
  644. }
  645. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  646. {
  647. layoutMode_ = mode;
  648. layoutSpacing_ = Max(spacing, 0);
  649. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  650. UpdateLayout();
  651. }
  652. void UIElement::SetLayoutMode(LayoutMode mode)
  653. {
  654. layoutMode_ = mode;
  655. UpdateLayout();
  656. }
  657. void UIElement::SetLayoutSpacing(int spacing)
  658. {
  659. layoutSpacing_ = Max(spacing, 0);
  660. UpdateLayout();
  661. }
  662. void UIElement::SetLayoutBorder(const IntRect& border)
  663. {
  664. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  665. UpdateLayout();
  666. }
  667. void UIElement::SetIndent(int indent)
  668. {
  669. indent_ = indent;
  670. if (parent_)
  671. parent_->UpdateLayout();
  672. }
  673. void UIElement::SetIndentSpacing(int indentSpacing)
  674. {
  675. indentSpacing_ = Max(indentSpacing, 0);
  676. if (parent_)
  677. parent_->UpdateLayout();
  678. }
  679. void UIElement::UpdateLayout()
  680. {
  681. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  682. return;
  683. // Prevent further updates while this update happens
  684. DisableLayoutUpdate();
  685. PODVector<int> positions;
  686. PODVector<int> sizes;
  687. PODVector<int> minSizes;
  688. PODVector<int> maxSizes;
  689. int baseIndentWidth = GetIndentWidth();
  690. if (layoutMode_ == LM_HORIZONTAL)
  691. {
  692. int minChildHeight = 0;
  693. for (unsigned i = 0; i < children_.Size(); ++i)
  694. {
  695. if (!children_[i]->IsVisible())
  696. continue;
  697. positions.Push(baseIndentWidth);
  698. unsigned indent = children_[i]->GetIndentWidth();
  699. sizes.Push(children_[i]->GetWidth() + indent);
  700. minSizes.Push(children_[i]->GetMinWidth() + indent);
  701. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  702. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  703. }
  704. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  705. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  706. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  707. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  708. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  709. // Respect fixed size if already set
  710. if (minSize_.x_ != maxSize_.x_)
  711. minSize_.x_ = minWidth;
  712. if (minSize_.y_ != maxSize_.y_)
  713. minSize_.y_ = minHeight;
  714. SetSize(width, height);
  715. // Validate the size before resizing child elements, in case of min/max limits
  716. width = size_.x_;
  717. height = size_.y_;
  718. unsigned j = 0;
  719. for (unsigned i = 0; i < children_.Size(); ++i)
  720. {
  721. if (!children_[i]->IsVisible())
  722. continue;
  723. HorizontalAlignment horizontalAlignment = children_[i]->horizontalAlignment_;
  724. children_[i]->horizontalAlignment_ = HA_LEFT;
  725. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  726. children_[i]->horizontalAlignment_ = horizontalAlignment;
  727. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  728. ++j;
  729. }
  730. }
  731. else if (layoutMode_ == LM_VERTICAL)
  732. {
  733. int minChildWidth = 0;
  734. for (unsigned i = 0; i < children_.Size(); ++i)
  735. {
  736. if (!children_[i]->IsVisible())
  737. continue;
  738. positions.Push(baseIndentWidth);
  739. sizes.Push(children_[i]->GetHeight());
  740. minSizes.Push(children_[i]->GetMinHeight());
  741. maxSizes.Push(children_[i]->GetMaxHeight());
  742. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth() + children_[i]->GetIndentWidth());
  743. }
  744. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  745. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  746. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  747. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  748. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  749. if (minSize_.x_ != maxSize_.x_)
  750. minSize_.x_ = minWidth;
  751. if (minSize_.y_ != maxSize_.y_)
  752. minSize_.y_ = minHeight;
  753. SetSize(width, height);
  754. width = size_.x_;
  755. height = size_.y_;
  756. unsigned j = 0;
  757. for (unsigned i = 0; i < children_.Size(); ++i)
  758. {
  759. if (!children_[i]->IsVisible())
  760. continue;
  761. VerticalAlignment verticalAlignment = children_[i]->verticalAlignment_;
  762. children_[i]->verticalAlignment_ = VA_TOP;
  763. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  764. children_[i]->verticalAlignment_ = verticalAlignment;
  765. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  766. ++j;
  767. }
  768. }
  769. using namespace LayoutUpdated;
  770. VariantMap eventData;
  771. eventData[P_ELEMENT] = (void*)this;
  772. SendEvent(E_LAYOUTUPDATED, eventData);
  773. EnableLayoutUpdate();
  774. }
  775. void UIElement::DisableLayoutUpdate()
  776. {
  777. ++layoutNestingLevel_;
  778. }
  779. void UIElement::EnableLayoutUpdate()
  780. {
  781. --layoutNestingLevel_;
  782. }
  783. void UIElement::BringToFront()
  784. {
  785. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  786. UIElement* root = GetRoot();
  787. // If element is detached from hierarchy, this must be a no-op
  788. if (!root)
  789. return;
  790. UIElement* ptr = this;
  791. while (ptr && ptr->GetParent() != root)
  792. ptr = ptr->GetParent();
  793. if (!ptr || !ptr->GetBringToFront())
  794. return;
  795. // Get the highest priority used by all other top level elements, assign that to the new front element
  796. // and decrease others' priority where necessary. However, take into account only input-enabled
  797. // elements and those which have the BringToBack flag set
  798. HashSet<int> usedPriorities;
  799. int maxPriority = M_MIN_INT;
  800. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  801. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  802. {
  803. UIElement* other = *i;
  804. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  805. {
  806. int priority = other->GetPriority();
  807. usedPriorities.Insert(priority);
  808. maxPriority = Max(priority, maxPriority);
  809. }
  810. }
  811. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  812. {
  813. ptr->SetPriority(maxPriority);
  814. int minPriority = maxPriority;
  815. while (usedPriorities.Contains(minPriority))
  816. --minPriority;
  817. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  818. {
  819. UIElement* other = *i;
  820. int priority = other->GetPriority();
  821. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  822. other->SetPriority(priority - 1);
  823. }
  824. }
  825. }
  826. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name, unsigned index)
  827. {
  828. // Check that creation succeeds and that the object in fact is a UI element
  829. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  830. if (!newElement)
  831. {
  832. LOGERROR("Could not create unknown UI element type " + type.ToString());
  833. return 0;
  834. }
  835. if (!name.Empty())
  836. newElement->SetName(name);
  837. InsertChild(index, newElement);
  838. return newElement;
  839. }
  840. void UIElement::AddChild(UIElement* element)
  841. {
  842. InsertChild(M_MAX_UNSIGNED, element);
  843. }
  844. void UIElement::InsertChild(unsigned index, UIElement* element)
  845. {
  846. // Check for illegal or redundant parent assignment
  847. if (!element || element == this || element->parent_ == this)
  848. return;
  849. // Check for possible cyclic parent assignment
  850. UIElement* parent = parent_;
  851. while (parent)
  852. {
  853. if (parent == element)
  854. return;
  855. parent = parent->parent_;
  856. }
  857. // Add first, then remove from old parent, to ensure the element does not get deleted
  858. if (index >= children_.Size())
  859. children_.Push(SharedPtr<UIElement>(element));
  860. else
  861. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  862. element->Remove();
  863. if (sortChildren_)
  864. sortOrderDirty_ = true;
  865. element->parent_ = this;
  866. element->MarkDirty();
  867. UpdateLayout();
  868. // Send change event
  869. UIElement* root = GetRoot();
  870. UIElement* sender = GetElementEventSender();
  871. if (sender)
  872. {
  873. using namespace ElementAdded;
  874. VariantMap eventData;
  875. eventData[P_ROOT] = (void*)root;
  876. eventData[P_PARENT] = (void*)this;
  877. eventData[P_ELEMENT] = (void*)element;
  878. sender->SendEvent(E_ELEMENTADDED, eventData);
  879. }
  880. }
  881. void UIElement::RemoveChild(UIElement* element, unsigned index)
  882. {
  883. UIElement* root = GetRoot();
  884. UIElement* sender = GetElementEventSender();
  885. for (unsigned i = index; i < children_.Size(); ++i)
  886. {
  887. if (children_[i] == element)
  888. {
  889. // Send change event if not already being destroyed
  890. if (Refs() > 0 && sender)
  891. {
  892. using namespace ElementRemoved;
  893. VariantMap eventData;
  894. eventData[P_ROOT] = (void*)root;
  895. eventData[P_PARENT] = (void*)this;
  896. eventData[P_ELEMENT] = (void*)element;
  897. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  898. }
  899. element->Detach();
  900. children_.Erase(i);
  901. UpdateLayout();
  902. return;
  903. }
  904. }
  905. }
  906. void UIElement::RemoveChildAtIndex(unsigned index)
  907. {
  908. if (index >= children_.Size())
  909. return;
  910. children_[index]->Detach();
  911. children_.Erase(index);
  912. UpdateLayout();
  913. }
  914. void UIElement::RemoveAllChildren()
  915. {
  916. UIElement* root = GetRoot();
  917. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  918. {
  919. // Send change event if not already being destroyed
  920. if (Refs() > 0 && root)
  921. {
  922. using namespace ElementRemoved;
  923. VariantMap eventData;
  924. eventData[P_ROOT] = (void*)root;
  925. eventData[P_PARENT] = (void*)this;
  926. eventData[P_ELEMENT] = (void*)(*i).Get();
  927. root->SendEvent(E_ELEMENTREMOVED, eventData);
  928. }
  929. (*i++)->Detach();
  930. }
  931. children_.Clear();
  932. }
  933. void UIElement::Remove()
  934. {
  935. if (parent_)
  936. parent_->RemoveChild(this);
  937. }
  938. unsigned UIElement::FindChild(UIElement* element) const
  939. {
  940. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  941. return i != children_.End() ? i - children_.Begin() : M_MAX_UNSIGNED;
  942. }
  943. void UIElement::SetParent(UIElement* parent)
  944. {
  945. if (parent)
  946. parent->AddChild(this);
  947. }
  948. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  949. {
  950. vars_[key] = value;
  951. }
  952. void UIElement::SetInternal(bool enable)
  953. {
  954. internal_ = enable;
  955. }
  956. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  957. {
  958. traversalMode_ = traversalMode;
  959. }
  960. void UIElement::SetElementEventSender(bool flag)
  961. {
  962. elementEventSender_ = flag;
  963. }
  964. float UIElement::GetDerivedOpacity() const
  965. {
  966. if (!useDerivedOpacity_)
  967. return opacity_;
  968. if (opacityDirty_)
  969. {
  970. derivedOpacity_ = opacity_;
  971. const UIElement* parent = parent_;
  972. while (parent)
  973. {
  974. derivedOpacity_ *= parent->opacity_;
  975. parent = parent->parent_;
  976. }
  977. opacityDirty_ = false;
  978. }
  979. return derivedOpacity_;
  980. }
  981. bool UIElement::HasFocus() const
  982. {
  983. UI* ui = GetSubsystem<UI>();
  984. if (!ui)
  985. return false;
  986. else
  987. return ui->GetFocusElement() == this;
  988. }
  989. XMLFile* UIElement::GetDefaultStyle(bool recursiveUp) const
  990. {
  991. if (recursiveUp)
  992. {
  993. const UIElement* element = this;
  994. while (element)
  995. {
  996. if (element->defaultStyle_)
  997. return element->defaultStyle_;
  998. element = element->parent_;
  999. }
  1000. return 0;
  1001. }
  1002. else
  1003. return defaultStyle_;
  1004. }
  1005. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  1006. {
  1007. dest.Clear();
  1008. if (!recursive)
  1009. {
  1010. dest.Reserve(children_.Size());
  1011. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1012. dest.Push(*i);
  1013. }
  1014. else
  1015. GetChildrenRecursive(dest);
  1016. }
  1017. unsigned UIElement::GetNumChildren(bool recursive) const
  1018. {
  1019. if (!recursive)
  1020. return children_.Size();
  1021. else
  1022. {
  1023. unsigned allChildren = children_.Size();
  1024. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1025. allChildren += (*i)->GetNumChildren(true);
  1026. return allChildren;
  1027. }
  1028. }
  1029. UIElement* UIElement::GetChild(unsigned index) const
  1030. {
  1031. return index < children_.Size() ? children_[index] : (UIElement*)0;
  1032. }
  1033. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  1034. {
  1035. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1036. {
  1037. if ((*i)->name_ == name)
  1038. return *i;
  1039. if (recursive)
  1040. {
  1041. UIElement* element = (*i)->GetChild(name, true);
  1042. if (element)
  1043. return element;
  1044. }
  1045. }
  1046. return 0;
  1047. }
  1048. UIElement* UIElement::GetChild(const ShortStringHash& key, const Variant& value, bool recursive) const
  1049. {
  1050. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1051. {
  1052. const Variant& varValue = (*i)->GetVar(key);
  1053. if (value != Variant::EMPTY ? varValue == value : varValue != Variant::EMPTY)
  1054. return *i;
  1055. if (recursive)
  1056. {
  1057. UIElement* element = (*i)->GetChild(key, value, true);
  1058. if (element)
  1059. return element;
  1060. }
  1061. }
  1062. return 0;
  1063. }
  1064. UIElement* UIElement::GetRoot() const
  1065. {
  1066. UIElement* root = parent_;
  1067. if (!root)
  1068. return 0;
  1069. while (root->GetParent())
  1070. root = root->GetParent();
  1071. return root;
  1072. }
  1073. const Color& UIElement::GetDerivedColor() const
  1074. {
  1075. if (derivedColorDirty_)
  1076. {
  1077. derivedColor_ = color_[C_TOPLEFT];
  1078. derivedColor_.a_ *= GetDerivedOpacity();
  1079. derivedColorDirty_ = false;
  1080. }
  1081. return derivedColor_;
  1082. }
  1083. const Variant& UIElement::GetVar(const ShortStringHash& key) const
  1084. {
  1085. VariantMap::ConstIterator i = vars_.Find(key);
  1086. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1087. }
  1088. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  1089. {
  1090. return screenPosition - GetScreenPosition();
  1091. }
  1092. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  1093. {
  1094. return position + GetScreenPosition();
  1095. }
  1096. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  1097. {
  1098. if (isScreen)
  1099. position = ScreenToElement(position);
  1100. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  1101. }
  1102. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  1103. {
  1104. // If child elements are clipped, no need to expand the rect
  1105. if (clipChildren_)
  1106. return IsInside(position, isScreen);
  1107. if (!isScreen)
  1108. position = ElementToScreen(position);
  1109. IntRect combined = GetCombinedScreenRect();
  1110. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  1111. position.y_ < combined.bottom_;
  1112. }
  1113. IntRect UIElement::GetCombinedScreenRect()
  1114. {
  1115. IntVector2 screenPosition(GetScreenPosition());
  1116. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  1117. if (!clipChildren_)
  1118. {
  1119. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1120. {
  1121. IntVector2 childPos = (*i)->GetScreenPosition();
  1122. const IntVector2& childSize = (*i)->GetSize();
  1123. if (childPos.x_ < combined.left_)
  1124. combined.left_ = childPos.x_;
  1125. if (childPos.y_ < combined.top_)
  1126. combined.top_ = childPos.y_;
  1127. if (childPos.x_ + childSize.x_ > combined.right_)
  1128. combined.right_ = childPos.x_ + childSize.x_;
  1129. if (childPos.y_ + childSize.y_ > combined.bottom_)
  1130. combined.bottom_ = childPos.y_ + childSize.y_;
  1131. }
  1132. }
  1133. return combined;
  1134. }
  1135. void UIElement::SortChildren()
  1136. {
  1137. if (sortChildren_ && sortOrderDirty_)
  1138. {
  1139. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1140. sortOrderDirty_ = false;
  1141. }
  1142. }
  1143. void UIElement::SetChildOffset(const IntVector2& offset)
  1144. {
  1145. if (offset != childOffset_)
  1146. {
  1147. childOffset_ = offset;
  1148. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1149. (*i)->MarkDirty();
  1150. }
  1151. }
  1152. void UIElement::SetHovering(bool enable)
  1153. {
  1154. hovering_ = enable;
  1155. }
  1156. void UIElement::SetTempVisible(bool enable)
  1157. {
  1158. visible_ = enable;
  1159. }
  1160. void UIElement::AdjustScissor(IntRect& currentScissor)
  1161. {
  1162. if (clipChildren_)
  1163. {
  1164. IntVector2 screenPos = GetScreenPosition();
  1165. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1166. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1167. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1168. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1169. if (currentScissor.right_ < currentScissor.left_)
  1170. currentScissor.right_ = currentScissor.left_;
  1171. if (currentScissor.bottom_ < currentScissor.top_)
  1172. currentScissor.bottom_ = currentScissor.top_;
  1173. }
  1174. }
  1175. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData, IntRect
  1176. currentScissor)
  1177. {
  1178. Vector2 floatOffset((float)offset.x_, (float)offset.y_);
  1179. unsigned initialSize = vertexData.Size();
  1180. GetBatches(batches, vertexData, currentScissor);
  1181. for (unsigned i = initialSize; i < vertexData.Size(); i += 6)
  1182. {
  1183. vertexData[i] += floatOffset.x_;
  1184. vertexData[i + 1] += floatOffset.y_;
  1185. }
  1186. AdjustScissor(currentScissor);
  1187. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1188. {
  1189. if ((*i)->IsVisible())
  1190. (*i)->GetBatchesWithOffset(offset, batches, vertexData, currentScissor);
  1191. }
  1192. }
  1193. UIElement* UIElement::GetElementEventSender() const
  1194. {
  1195. UIElement* element = const_cast<UIElement*>(this);
  1196. if (elementEventSender_)
  1197. return element;
  1198. while (element->parent_)
  1199. {
  1200. element = element->parent_;
  1201. if (element->elementEventSender_)
  1202. return element;
  1203. }
  1204. // If no predefined element event sender in the parental chain, return ultimate root element
  1205. return element;
  1206. }
  1207. void UIElement::MarkDirty()
  1208. {
  1209. positionDirty_ = true;
  1210. opacityDirty_ = true;
  1211. derivedColorDirty_ = true;
  1212. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1213. (*i)->MarkDirty();
  1214. }
  1215. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1216. {
  1217. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1218. {
  1219. UIElement* element = *i;
  1220. dest.Push(element);
  1221. if (!element->children_.Empty())
  1222. element->GetChildrenRecursive(dest);
  1223. }
  1224. }
  1225. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1226. {
  1227. int width = begin + end;
  1228. if (sizes.Empty())
  1229. return width;
  1230. for (unsigned i = 0; i < sizes.Size(); ++i)
  1231. {
  1232. // If calculating maximum size, and the default is specified, do not overflow it
  1233. if (sizes[i] == M_MAX_INT)
  1234. return M_MAX_INT;
  1235. width += sizes[i] + spacing;
  1236. }
  1237. // The last spacing is not needed
  1238. return width - spacing;
  1239. }
  1240. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1241. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1242. {
  1243. int numChildren = sizes.Size();
  1244. if (!numChildren)
  1245. return;
  1246. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1247. if (targetTotalSize < 0)
  1248. targetTotalSize = 0;
  1249. int targetChildSize = targetTotalSize / numChildren;
  1250. int remainder = targetTotalSize % numChildren;
  1251. float add = (float)remainder / numChildren;
  1252. float acc = 0.0f;
  1253. // Initial pass
  1254. for (int i = 0; i < numChildren; ++i)
  1255. {
  1256. int targetSize = targetChildSize;
  1257. if (remainder)
  1258. {
  1259. acc += add;
  1260. if (acc >= 0.5f)
  1261. {
  1262. acc -= 1.0f;
  1263. ++targetSize;
  1264. --remainder;
  1265. }
  1266. }
  1267. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1268. }
  1269. // Error correction passes
  1270. for (;;)
  1271. {
  1272. int actualTotalSize = 0;
  1273. for (int i = 0; i < numChildren; ++i)
  1274. actualTotalSize += sizes[i];
  1275. int error = targetTotalSize - actualTotalSize;
  1276. // Break if no error
  1277. if (!error)
  1278. break;
  1279. // Check which of the children can be resized to correct the error. If none, must break
  1280. PODVector<unsigned> resizable;
  1281. for (int i = 0; i < numChildren; ++i)
  1282. {
  1283. if (error < 0 && sizes[i] > minSizes[i])
  1284. resizable.Push(i);
  1285. else if (error > 0 && sizes[i] < maxSizes[i])
  1286. resizable.Push(i);
  1287. }
  1288. if (resizable.Empty())
  1289. break;
  1290. int numResizable = resizable.Size();
  1291. int errorPerChild = error / numResizable;
  1292. remainder = (abs(error)) % numResizable;
  1293. add = (float)remainder / numResizable;
  1294. acc = 0.0f;
  1295. for (int i = 0; i < numResizable; ++i)
  1296. {
  1297. unsigned index = resizable[i];
  1298. int targetSize = sizes[index] + errorPerChild;
  1299. if (remainder)
  1300. {
  1301. acc += add;
  1302. if (acc >= 0.5f)
  1303. {
  1304. acc -= 1.0f;
  1305. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1306. --remainder;
  1307. }
  1308. }
  1309. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1310. }
  1311. }
  1312. // Calculate final positions and store the minimum child element size
  1313. layoutMinSize_ = M_MAX_INT;
  1314. int position = begin;
  1315. for (int i = 0; i < numChildren; ++i)
  1316. {
  1317. positions[i] = position;
  1318. position += sizes[i] + spacing;
  1319. if (sizes[i] < layoutMinSize_)
  1320. layoutMinSize_ = sizes[i];
  1321. }
  1322. }
  1323. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1324. {
  1325. IntVector2 ret(IntVector2::ZERO);
  1326. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1327. switch (ha)
  1328. {
  1329. case HA_LEFT:
  1330. ret.x_ = layoutBorder_.left_;
  1331. break;
  1332. case HA_RIGHT:
  1333. ret.x_ = -layoutBorder_.right_;
  1334. break;
  1335. default:
  1336. break;
  1337. }
  1338. VerticalAlignment va = child->GetVerticalAlignment();
  1339. switch (va)
  1340. {
  1341. case VA_TOP:
  1342. ret.y_ = layoutBorder_.top_;
  1343. break;
  1344. case VA_BOTTOM:
  1345. ret.y_ = -layoutBorder_.bottom_;
  1346. break;
  1347. default:
  1348. break;
  1349. }
  1350. return ret;
  1351. }
  1352. void UIElement::Detach()
  1353. {
  1354. parent_ = 0;
  1355. MarkDirty();
  1356. }
  1357. }