UIElement.cpp 54 KB

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