UIElement.cpp 52 KB

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