UIElement.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268
  1. //
  2. // Copyright (c) 2008-2017 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 "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Container/HashSet.h"
  26. #include "../Container/Sort.h"
  27. #include "../IO/Log.h"
  28. #include "../Resource/ResourceCache.h"
  29. #include "../Scene/ObjectAnimation.h"
  30. #include "../UI/Cursor.h"
  31. #include "../UI/UI.h"
  32. #include "../UI/UIElement.h"
  33. #include "../UI/UIEvents.h"
  34. #include "../DebugNew.h"
  35. namespace Urho3D
  36. {
  37. const char* horizontalAlignments[] =
  38. {
  39. "Left",
  40. "Center",
  41. "Right",
  42. "Custom",
  43. nullptr
  44. };
  45. const char* verticalAlignments[] =
  46. {
  47. "Top",
  48. "Center",
  49. "Bottom",
  50. "Custom",
  51. nullptr
  52. };
  53. static const char* focusModes[] =
  54. {
  55. "NotFocusable",
  56. "ResetFocus",
  57. "Focusable",
  58. "FocusableDefocusable",
  59. nullptr
  60. };
  61. static const char* dragDropModes[] =
  62. {
  63. "Disabled",
  64. "Source",
  65. "Target",
  66. "SourceAndTarget",
  67. nullptr
  68. };
  69. static const char* layoutModes[] =
  70. {
  71. "Free",
  72. "Horizontal",
  73. "Vertical",
  74. nullptr
  75. };
  76. extern const char* UI_CATEGORY;
  77. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  78. {
  79. return lhs->GetPriority() < rhs->GetPriority();
  80. }
  81. XPathQuery UIElement::styleXPathQuery_("/elements/element[@type=$typeName]", "typeName:String");
  82. UIElement::UIElement(Context* context) :
  83. Animatable(context),
  84. parent_(nullptr),
  85. clipBorder_(IntRect::ZERO),
  86. priority_(0),
  87. bringToFront_(false),
  88. bringToBack_(true),
  89. clipChildren_(false),
  90. sortChildren_(true),
  91. useDerivedOpacity_(true),
  92. editable_(true),
  93. selected_(false),
  94. visible_(true),
  95. hovering_(false),
  96. internal_(false),
  97. focusMode_(FM_NOTFOCUSABLE),
  98. dragDropMode_(DD_DISABLED),
  99. layoutMode_(LM_FREE),
  100. layoutSpacing_(0),
  101. layoutBorder_(IntRect::ZERO),
  102. layoutFlexScale_(Vector2::ONE),
  103. resizeNestingLevel_(0),
  104. layoutNestingLevel_(0),
  105. layoutElementMaxSize_(0),
  106. indent_(0),
  107. indentSpacing_(16),
  108. position_(IntVector2::ZERO),
  109. positionDirty_(true),
  110. dragButtonCombo_(0),
  111. dragButtonCount_(0),
  112. size_(IntVector2::ZERO),
  113. minSize_(IntVector2::ZERO),
  114. maxSize_(M_MAX_INT, M_MAX_INT),
  115. childOffset_(IntVector2::ZERO),
  116. opacity_(1.0f),
  117. opacityDirty_(true),
  118. derivedColorDirty_(true),
  119. sortOrderDirty_(false),
  120. colorGradient_(false),
  121. traversalMode_(TM_BREADTH_FIRST),
  122. elementEventSender_(false),
  123. anchorMin_(Vector2::ZERO),
  124. anchorMax_(Vector2::ZERO),
  125. minOffset_(IntVector2::ZERO),
  126. maxOffset_(IntVector2::ZERO),
  127. enableAnchor_(false),
  128. pivot_(std::numeric_limits<float>::max(), std::numeric_limits<float>::max()),
  129. pivotSet_(false)
  130. {
  131. SetEnabled(false);
  132. }
  133. UIElement::~UIElement()
  134. {
  135. // If child elements have outside references, detach them
  136. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  137. {
  138. if (i->Refs() > 1)
  139. (*i)->Detach();
  140. }
  141. }
  142. void UIElement::RegisterObject(Context* context)
  143. {
  144. context->RegisterFactory<UIElement>(UI_CATEGORY);
  145. URHO3D_ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_FILE);
  146. URHO3D_ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  147. URHO3D_ACCESSOR_ATTRIBUTE("Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  148. URHO3D_ACCESSOR_ATTRIBUTE("Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  149. URHO3D_ACCESSOR_ATTRIBUTE("Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2(M_MAX_INT, M_MAX_INT), AM_FILE);
  150. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment,
  151. horizontalAlignments, HA_LEFT, AM_FILEREADONLY);
  152. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments,
  153. VA_TOP, AM_FILEREADONLY);
  154. URHO3D_ACCESSOR_ATTRIBUTE("Min Anchor", GetMinAnchor, SetMinAnchor, Vector2, Vector2::ZERO, AM_FILE);
  155. URHO3D_ACCESSOR_ATTRIBUTE("Max Anchor", GetMaxAnchor, SetMaxAnchor, Vector2, Vector2::ZERO, AM_FILE);
  156. URHO3D_ACCESSOR_ATTRIBUTE("Min Offset", GetMinOffset, SetMinOffset, IntVector2, IntVector2::ZERO, AM_FILE);
  157. URHO3D_ACCESSOR_ATTRIBUTE("Max Offset", GetMaxOffset, SetMaxOffset, IntVector2, IntVector2::ZERO, AM_FILE);
  158. URHO3D_ACCESSOR_ATTRIBUTE("Pivot", GetPivot, SetPivot, Vector2, Vector2(std::numeric_limits<float>::max(), std::numeric_limits<float>::max()), AM_FILE);
  159. URHO3D_ACCESSOR_ATTRIBUTE("Enable Anchor", GetEnableAnchor, SetEnableAnchor, bool, false, AM_FILE);
  160. URHO3D_ACCESSOR_ATTRIBUTE("Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  161. URHO3D_ACCESSOR_ATTRIBUTE("Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  162. URHO3D_ACCESSOR_ATTRIBUTE("Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  163. URHO3D_ACCESSOR_ATTRIBUTE("Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  164. URHO3D_ATTRIBUTE("Top Left Color", Color, color_[0], Color::WHITE, AM_FILE);
  165. URHO3D_ATTRIBUTE("Top Right Color", Color, color_[1], Color::WHITE, AM_FILE);
  166. URHO3D_ATTRIBUTE("Bottom Left Color", Color, color_[2], Color::WHITE, AM_FILE);
  167. URHO3D_ATTRIBUTE("Bottom Right Color", Color, color_[3], Color::WHITE, AM_FILE);
  168. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, false, AM_FILE);
  169. URHO3D_ACCESSOR_ATTRIBUTE("Is Editable", IsEditable, SetEditable, bool, true, AM_FILE);
  170. URHO3D_ACCESSOR_ATTRIBUTE("Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  171. URHO3D_ACCESSOR_ATTRIBUTE("Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  172. URHO3D_ACCESSOR_ATTRIBUTE("Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  173. URHO3D_ACCESSOR_ATTRIBUTE("Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  174. URHO3D_ACCESSOR_ATTRIBUTE("Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  175. URHO3D_ACCESSOR_ATTRIBUTE("Use Derived Opacity", GetUseDerivedOpacity, SetUseDerivedOpacity, bool, true, AM_FILE);
  176. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  177. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  178. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  179. URHO3D_ACCESSOR_ATTRIBUTE("Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  180. URHO3D_ACCESSOR_ATTRIBUTE("Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  181. URHO3D_ACCESSOR_ATTRIBUTE("Layout Flex Scale", GetLayoutFlexScale, SetLayoutFlexScale, Vector2, Vector2::ONE, AM_FILE);
  182. URHO3D_ACCESSOR_ATTRIBUTE("Indent", GetIndent, SetIndent, int, 0, AM_FILE);
  183. URHO3D_ACCESSOR_ATTRIBUTE("Indent Spacing", GetIndentSpacing, SetIndentSpacing, int, 16, AM_FILE);
  184. URHO3D_ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE);
  185. URHO3D_ATTRIBUTE("Tags", StringVector, tags_, Variant::emptyStringVector, AM_FILE);
  186. }
  187. void UIElement::ApplyAttributes()
  188. {
  189. colorGradient_ = false;
  190. derivedColorDirty_ = true;
  191. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  192. {
  193. if (color_[i] != color_[0])
  194. colorGradient_ = true;
  195. }
  196. }
  197. bool UIElement::LoadXML(const XMLElement& source, bool setInstanceDefault)
  198. {
  199. return LoadXML(source, nullptr, setInstanceDefault);
  200. }
  201. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile, bool setInstanceDefault)
  202. {
  203. // Get style override if defined
  204. String styleName = source.GetAttribute("style");
  205. // Apply the style first, if the style file is available
  206. if (styleFile)
  207. {
  208. // If not defined, use type name
  209. if (styleName.Empty())
  210. styleName = GetTypeName();
  211. SetStyle(styleName, styleFile);
  212. }
  213. // The 'style' attribute value in the style file cannot be equals to original's applied style to prevent infinite loop
  214. else if (!styleName.Empty() && styleName != appliedStyle_)
  215. {
  216. // Attempt to use the default style file
  217. styleFile = GetDefaultStyle();
  218. if (styleFile)
  219. {
  220. // Remember the original applied style
  221. String appliedStyle(appliedStyle_);
  222. SetStyle(styleName, styleFile);
  223. appliedStyle_ = appliedStyle;
  224. }
  225. }
  226. // Prevent updates while loading attributes
  227. DisableLayoutUpdate();
  228. // Then load rest of the attributes from the source
  229. if (!Animatable::LoadXML(source, setInstanceDefault))
  230. return false;
  231. unsigned nextInternalChild = 0;
  232. // Load child elements. Internal elements are not to be created as they already exist
  233. XMLElement childElem = source.GetChild("element");
  234. while (childElem)
  235. {
  236. bool internalElem = childElem.GetBool("internal");
  237. String typeName = childElem.GetAttribute("type");
  238. if (typeName.Empty())
  239. typeName = "UIElement";
  240. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  241. UIElement* child = nullptr;
  242. if (!internalElem)
  243. child = CreateChild(typeName, String::EMPTY, index);
  244. else
  245. {
  246. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  247. {
  248. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  249. {
  250. child = children_[i];
  251. nextInternalChild = i + 1;
  252. break;
  253. }
  254. }
  255. if (!child)
  256. URHO3D_LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  257. }
  258. if (child)
  259. {
  260. if (!styleFile)
  261. styleFile = GetDefaultStyle();
  262. if (!child->LoadXML(childElem, styleFile, setInstanceDefault))
  263. return false;
  264. }
  265. childElem = childElem.GetNext("element");
  266. }
  267. ApplyAttributes();
  268. EnableLayoutUpdate();
  269. UpdateLayout();
  270. return true;
  271. }
  272. UIElement* UIElement::LoadChildXML(const XMLElement& childElem, XMLFile* styleFile, bool setInstanceDefault)
  273. {
  274. bool internalElem = childElem.GetBool("internal");
  275. if (internalElem)
  276. {
  277. URHO3D_LOGERROR("Loading internal child element is not supported");
  278. return nullptr;
  279. }
  280. String typeName = childElem.GetAttribute("type");
  281. if (typeName.Empty())
  282. typeName = "UIElement";
  283. unsigned index = childElem.HasAttribute("index") ? childElem.GetUInt("index") : M_MAX_UNSIGNED;
  284. UIElement* child = CreateChild(typeName, String::EMPTY, index);
  285. if (child)
  286. {
  287. if (!styleFile)
  288. styleFile = GetDefaultStyle();
  289. if (!child->LoadXML(childElem, styleFile, setInstanceDefault))
  290. {
  291. RemoveChild(child, index);
  292. return nullptr;
  293. }
  294. }
  295. return child;
  296. }
  297. bool UIElement::SaveXML(XMLElement& dest) const
  298. {
  299. // Write type
  300. if (GetTypeName() != "UIElement")
  301. {
  302. if (!dest.SetString("type", GetTypeName()))
  303. return false;
  304. }
  305. // Write internal flag
  306. if (internal_)
  307. {
  308. if (!dest.SetBool("internal", internal_))
  309. return false;
  310. }
  311. // Write style
  312. if (!appliedStyle_.Empty() && appliedStyle_ != "UIElement")
  313. {
  314. if (!dest.SetAttribute("style", appliedStyle_))
  315. return false;
  316. }
  317. else if (internal_)
  318. {
  319. if (!dest.SetAttribute("style", "none"))
  320. return false;
  321. }
  322. // Write attributes
  323. if (!Animatable::SaveXML(dest))
  324. return false;
  325. // Write child elements
  326. for (unsigned i = 0; i < children_.Size(); ++i)
  327. {
  328. UIElement* element = children_[i];
  329. if (element->IsTemporary())
  330. continue;
  331. XMLElement childElem = dest.CreateChild("element");
  332. if (!element->SaveXML(childElem))
  333. return false;
  334. }
  335. // Filter UI-style and implicit attributes
  336. return FilterAttributes(dest);
  337. }
  338. void UIElement::Update(float timeStep)
  339. {
  340. }
  341. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  342. {
  343. // Reset hovering for next frame
  344. hovering_ = false;
  345. }
  346. void UIElement::GetDebugDrawBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  347. {
  348. UIBatch batch(this, BLEND_ALPHA, currentScissor, nullptr, &vertexData);
  349. int horizontalThickness = 1;
  350. int verticalThickness = 1;
  351. if (parent_)
  352. {
  353. switch (parent_->layoutMode_)
  354. {
  355. case LM_HORIZONTAL:
  356. verticalThickness += 2;
  357. break;
  358. case LM_VERTICAL:
  359. horizontalThickness += 2;
  360. break;
  361. default:
  362. break;
  363. }
  364. }
  365. batch.SetColor(Color::BLUE, true);
  366. // Left
  367. batch.AddQuad(0, 0, horizontalThickness, size_.y_, 0, 0);
  368. // Top
  369. batch.AddQuad(0, 0, size_.x_, verticalThickness, 0, 0);
  370. // Right
  371. batch.AddQuad(size_.x_ - horizontalThickness, 0, horizontalThickness, size_.y_, 0, 0);
  372. // Bottom
  373. batch.AddQuad(0, size_.y_ - verticalThickness, size_.x_, verticalThickness, 0, 0);
  374. UIBatch::AddOrMerge(batch, batches);
  375. }
  376. bool UIElement::IsWithinScissor(const IntRect& currentScissor)
  377. {
  378. if (!visible_)
  379. return false;
  380. const IntVector2& screenPos = GetScreenPosition();
  381. return screenPos.x_ < currentScissor.right_ && screenPos.x_ + GetWidth() > currentScissor.left_ &&
  382. screenPos.y_ < currentScissor.bottom_ && screenPos.y_ + GetHeight() > currentScissor.top_;
  383. }
  384. const IntVector2& UIElement::GetScreenPosition() const
  385. {
  386. if (positionDirty_)
  387. {
  388. IntVector2 pos = position_;
  389. const UIElement* parent = parent_;
  390. if (parent)
  391. {
  392. const IntVector2& parentScreenPos = parent->GetScreenPosition();
  393. pos.x_ += parentScreenPos.x_ + (int)Lerp(0.0f, (float)parent->size_.x_, anchorMin_.x_);
  394. pos.y_ += parentScreenPos.y_ + (int)Lerp(0.0f, (float)parent->size_.y_, anchorMin_.y_);
  395. pos.x_ -= (int)(size_.x_ * pivot_.x_);
  396. pos.y_ -= (int)(size_.y_ * pivot_.y_);
  397. pos += parent_->childOffset_;
  398. }
  399. screenPosition_ = pos;
  400. positionDirty_ = false;
  401. }
  402. return screenPosition_;
  403. }
  404. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  405. {
  406. hovering_ = true;
  407. }
  408. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers,
  409. Cursor* cursor)
  410. {
  411. dragButtonCombo_ = buttons;
  412. dragButtonCount_ = CountSetBits((unsigned)dragButtonCombo_);
  413. }
  414. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, const IntVector2& deltaPos, int buttons,
  415. int qualifiers, Cursor* cursor)
  416. {
  417. }
  418. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, int dragButtons, int buttons,
  419. Cursor* cursor)
  420. {
  421. dragButtonCombo_ = 0;
  422. dragButtonCount_ = 0;
  423. }
  424. void UIElement::OnDragCancel(const IntVector2& position, const IntVector2& screenPosition, int dragButtons, int buttons,
  425. Cursor* cursor)
  426. {
  427. dragButtonCombo_ = 0;
  428. dragButtonCount_ = 0;
  429. }
  430. bool UIElement::OnDragDropTest(UIElement* source)
  431. {
  432. return true;
  433. }
  434. bool UIElement::OnDragDropFinish(UIElement* source)
  435. {
  436. return true;
  437. }
  438. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  439. {
  440. return screenPosition - GetScreenPosition();
  441. }
  442. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  443. {
  444. return position + GetScreenPosition();
  445. }
  446. bool UIElement::LoadXML(Deserializer& source)
  447. {
  448. SharedPtr<XMLFile> xml(new XMLFile(context_));
  449. return xml->Load(source) && LoadXML(xml->GetRoot());
  450. }
  451. bool UIElement::SaveXML(Serializer& dest, const String& indentation) const
  452. {
  453. SharedPtr<XMLFile> xml(new XMLFile(context_));
  454. XMLElement rootElem = xml->CreateRoot("element");
  455. return SaveXML(rootElem) && xml->Save(dest, indentation);
  456. }
  457. bool UIElement::FilterAttributes(XMLElement& dest) const
  458. {
  459. // Filter UI styling attributes
  460. XMLFile* styleFile = GetDefaultStyle();
  461. if (styleFile)
  462. {
  463. String style = dest.GetAttribute("style");
  464. if (!style.Empty() && style != "none")
  465. {
  466. if (styleXPathQuery_.SetVariable("typeName", style))
  467. {
  468. XMLElement styleElem = GetDefaultStyle()->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  469. if (styleElem && !FilterUIStyleAttributes(dest, styleElem))
  470. return false;
  471. }
  472. }
  473. }
  474. // Filter implicit attributes
  475. if (!FilterImplicitAttributes(dest))
  476. {
  477. URHO3D_LOGERROR("Could not remove implicit attributes");
  478. return false;
  479. }
  480. return true;
  481. }
  482. void UIElement::SetName(const String& name)
  483. {
  484. name_ = name;
  485. using namespace NameChanged;
  486. VariantMap& eventData = GetEventDataMap();
  487. eventData[P_ELEMENT] = this;
  488. SendEvent(E_NAMECHANGED, eventData);
  489. }
  490. void UIElement::SetPosition(const IntVector2& position)
  491. {
  492. if (position != position_)
  493. {
  494. position_ = position;
  495. OnPositionSet(position);
  496. MarkDirty();
  497. using namespace Positioned;
  498. VariantMap& eventData = GetEventDataMap();
  499. eventData[P_ELEMENT] = this;
  500. eventData[P_X] = position.x_;
  501. eventData[P_Y] = position.y_;
  502. SendEvent(E_POSITIONED, eventData);
  503. }
  504. }
  505. void UIElement::SetPosition(int x, int y)
  506. {
  507. SetPosition(IntVector2(x, y));
  508. }
  509. void UIElement::SetSize(const IntVector2& size)
  510. {
  511. ++resizeNestingLevel_;
  512. IntVector2 oldSize = size_;
  513. IntVector2 validatedSize;
  514. IntVector2 effectiveMinSize = GetEffectiveMinSize();
  515. validatedSize.x_ = Clamp(size.x_, effectiveMinSize.x_, maxSize_.x_);
  516. validatedSize.y_ = Clamp(size.y_, effectiveMinSize.y_, maxSize_.y_);
  517. if (validatedSize != size_)
  518. {
  519. size_ = validatedSize;
  520. if (resizeNestingLevel_ == 1)
  521. {
  522. // Check if parent element's layout needs to be updated first
  523. if (parent_)
  524. parent_->UpdateLayout();
  525. IntVector2 delta = size_ - oldSize;
  526. MarkDirty();
  527. OnResize(size_, delta);
  528. UpdateLayout();
  529. using namespace Resized;
  530. VariantMap& eventData = GetEventDataMap();
  531. eventData[P_ELEMENT] = this;
  532. eventData[P_WIDTH] = size_.x_;
  533. eventData[P_HEIGHT] = size_.y_;
  534. eventData[P_DX] = delta.x_;
  535. eventData[P_DY] = delta.y_;
  536. SendEvent(E_RESIZED, eventData);
  537. }
  538. }
  539. --resizeNestingLevel_;
  540. }
  541. void UIElement::SetSize(int width, int height)
  542. {
  543. SetSize(IntVector2(width, height));
  544. }
  545. void UIElement::SetWidth(int width)
  546. {
  547. SetSize(IntVector2(width, size_.y_));
  548. }
  549. void UIElement::SetHeight(int height)
  550. {
  551. SetSize(IntVector2(size_.x_, height));
  552. }
  553. void UIElement::SetMinSize(const IntVector2& minSize)
  554. {
  555. minSize_.x_ = Max(minSize.x_, 0);
  556. minSize_.y_ = Max(minSize.y_, 0);
  557. SetSize(size_);
  558. }
  559. void UIElement::SetMinSize(int width, int height)
  560. {
  561. SetMinSize(IntVector2(width, height));
  562. }
  563. void UIElement::SetMinWidth(int width)
  564. {
  565. SetMinSize(IntVector2(width, minSize_.y_));
  566. }
  567. void UIElement::SetMinHeight(int height)
  568. {
  569. SetMinSize(IntVector2(minSize_.x_, height));
  570. }
  571. void UIElement::SetMaxSize(const IntVector2& maxSize)
  572. {
  573. maxSize_.x_ = Max(maxSize.x_, 0);
  574. maxSize_.y_ = Max(maxSize.y_, 0);
  575. SetSize(size_);
  576. }
  577. void UIElement::SetMaxSize(int width, int height)
  578. {
  579. SetMaxSize(IntVector2(width, height));
  580. }
  581. void UIElement::SetMaxWidth(int width)
  582. {
  583. SetMaxSize(IntVector2(width, maxSize_.y_));
  584. }
  585. void UIElement::SetMaxHeight(int height)
  586. {
  587. SetMaxSize(IntVector2(maxSize_.x_, height));
  588. }
  589. void UIElement::SetFixedSize(const IntVector2& size)
  590. {
  591. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  592. SetSize(size);
  593. }
  594. void UIElement::SetFixedSize(int width, int height)
  595. {
  596. SetFixedSize(IntVector2(width, height));
  597. }
  598. void UIElement::SetFixedWidth(int width)
  599. {
  600. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  601. SetWidth(width);
  602. }
  603. void UIElement::SetFixedHeight(int height)
  604. {
  605. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  606. SetHeight(height);
  607. }
  608. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  609. {
  610. SetHorizontalAlignment(hAlign);
  611. SetVerticalAlignment(vAlign);
  612. }
  613. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  614. {
  615. if (align != HA_LEFT && parent_ && parent_->GetLayoutMode() == LM_HORIZONTAL)
  616. {
  617. URHO3D_LOGWARNING("Forcing left alignment because parent element has horizontal layout");
  618. align = HA_LEFT;
  619. }
  620. Vector2 min = anchorMin_;
  621. Vector2 max = anchorMax_;
  622. float pivot = pivot_.x_;
  623. float anchorSize = max.x_ - min.x_;
  624. if (align == HA_CENTER)
  625. min.x_ = pivot = 0.5f;
  626. else if (align == HA_LEFT)
  627. min.x_ = pivot = 0.0f;
  628. else if (align == HA_RIGHT)
  629. min.x_ = pivot = 1.0f;
  630. max.x_ = enableAnchor_ ? (min.x_ + anchorSize) : min.x_;
  631. if (min.x_ != anchorMin_.x_ || max.x_ != anchorMax_.x_ || pivot != pivot_.x_)
  632. {
  633. anchorMin_.x_ = min.x_;
  634. anchorMax_.x_ = max.x_;
  635. pivot_.x_ = pivot;
  636. if (enableAnchor_)
  637. UpdateAnchoring();
  638. MarkDirty();
  639. }
  640. }
  641. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  642. {
  643. if (align != VA_TOP && parent_ && parent_->GetLayoutMode() == LM_VERTICAL)
  644. {
  645. URHO3D_LOGWARNING("Forcing top alignment because parent element has vertical layout");
  646. align = VA_TOP;
  647. }
  648. Vector2 min = anchorMin_;
  649. Vector2 max = anchorMax_;
  650. float pivot = pivot_.y_;
  651. float anchorSize = max.y_ - min.y_;
  652. if (align == VA_CENTER)
  653. min.y_ = pivot = 0.5f;
  654. else if (align == VA_TOP)
  655. min.y_ = pivot = 0.0f;
  656. else if (align == VA_BOTTOM)
  657. min.y_ = pivot = 1.0f;
  658. max.y_ = enableAnchor_ ? (min.y_ + anchorSize) : min.y_;
  659. if (min.y_ != anchorMin_.y_ || max.y_ != anchorMax_.y_ || pivot != pivot_.y_)
  660. {
  661. anchorMin_.y_ = min.y_;
  662. anchorMax_.y_ = max.y_;
  663. pivot_.y_ = pivot;
  664. if (enableAnchor_)
  665. UpdateAnchoring();
  666. MarkDirty();
  667. }
  668. }
  669. void UIElement::SetEnableAnchor(bool enable)
  670. {
  671. enableAnchor_ = enable;
  672. if (enableAnchor_)
  673. UpdateAnchoring();
  674. }
  675. void UIElement::SetMinOffset(const IntVector2& offset)
  676. {
  677. if (offset != minOffset_)
  678. {
  679. minOffset_ = offset;
  680. if (enableAnchor_)
  681. UpdateAnchoring();
  682. }
  683. }
  684. void UIElement::SetMaxOffset(const IntVector2& offset)
  685. {
  686. if (offset != maxOffset_)
  687. {
  688. maxOffset_ = offset;
  689. if (enableAnchor_)
  690. UpdateAnchoring();
  691. }
  692. }
  693. void UIElement::SetMinAnchor(const Vector2& anchor)
  694. {
  695. if (anchor != anchorMin_)
  696. {
  697. anchorMin_ = anchor;
  698. if (enableAnchor_)
  699. UpdateAnchoring();
  700. }
  701. }
  702. void UIElement::SetMinAnchor(float x, float y)
  703. {
  704. SetMinAnchor(Vector2(x, y));
  705. }
  706. void UIElement::SetMaxAnchor(const Vector2& anchor)
  707. {
  708. if (anchor != anchorMax_)
  709. {
  710. anchorMax_ = anchor;
  711. if (enableAnchor_)
  712. UpdateAnchoring();
  713. }
  714. }
  715. void UIElement::SetMaxAnchor(float x, float y)
  716. {
  717. SetMaxAnchor(Vector2(x, y));
  718. }
  719. void UIElement::SetPivot(const Vector2& pivot)
  720. {
  721. if (pivot != pivot_)
  722. {
  723. pivotSet_ = true;
  724. pivot_ = pivot;
  725. MarkDirty();
  726. }
  727. }
  728. void UIElement::SetPivot(float x, float y)
  729. {
  730. SetPivot(Vector2(x, y));
  731. }
  732. void UIElement::SetClipBorder(const IntRect& rect)
  733. {
  734. clipBorder_.left_ = Max(rect.left_, 0);
  735. clipBorder_.top_ = Max(rect.top_, 0);
  736. clipBorder_.right_ = Max(rect.right_, 0);
  737. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  738. }
  739. void UIElement::SetColor(const Color& color)
  740. {
  741. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  742. color_[i] = color;
  743. colorGradient_ = false;
  744. derivedColorDirty_ = true;
  745. }
  746. void UIElement::SetColor(Corner corner, const Color& color)
  747. {
  748. color_[corner] = color;
  749. colorGradient_ = false;
  750. derivedColorDirty_ = true;
  751. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  752. {
  753. if (i != corner && color_[i] != color_[corner])
  754. colorGradient_ = true;
  755. }
  756. }
  757. void UIElement::SetPriority(int priority)
  758. {
  759. if (priority_ == priority)
  760. return;
  761. priority_ = priority;
  762. if (parent_)
  763. parent_->sortOrderDirty_ = true;
  764. }
  765. void UIElement::SetOpacity(float opacity)
  766. {
  767. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  768. MarkDirty();
  769. }
  770. void UIElement::SetBringToFront(bool enable)
  771. {
  772. bringToFront_ = enable;
  773. }
  774. void UIElement::SetBringToBack(bool enable)
  775. {
  776. bringToBack_ = enable;
  777. }
  778. void UIElement::SetClipChildren(bool enable)
  779. {
  780. clipChildren_ = enable;
  781. }
  782. void UIElement::SetSortChildren(bool enable)
  783. {
  784. if (!sortChildren_ && enable)
  785. sortOrderDirty_ = true;
  786. sortChildren_ = enable;
  787. }
  788. void UIElement::SetUseDerivedOpacity(bool enable)
  789. {
  790. useDerivedOpacity_ = enable;
  791. }
  792. void UIElement::SetEnabled(bool enable)
  793. {
  794. enabled_ = enable;
  795. enabledPrev_ = enable;
  796. }
  797. void UIElement::SetDeepEnabled(bool enable)
  798. {
  799. enabled_ = enable;
  800. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  801. (*i)->SetDeepEnabled(enable);
  802. }
  803. void UIElement::ResetDeepEnabled()
  804. {
  805. enabled_ = enabledPrev_;
  806. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  807. (*i)->ResetDeepEnabled();
  808. }
  809. void UIElement::SetEnabledRecursive(bool enable)
  810. {
  811. enabled_ = enable;
  812. enabledPrev_ = enable;
  813. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  814. (*i)->SetEnabledRecursive(enable);
  815. }
  816. void UIElement::SetEditable(bool enable)
  817. {
  818. editable_ = enable;
  819. OnSetEditable();
  820. }
  821. void UIElement::SetFocusMode(FocusMode mode)
  822. {
  823. focusMode_ = mode;
  824. }
  825. void UIElement::SetFocus(bool enable)
  826. {
  827. // Invisible elements should not receive focus
  828. if (focusMode_ < FM_FOCUSABLE || !IsVisibleEffective())
  829. enable = false;
  830. UI* ui = GetSubsystem<UI>();
  831. // Can be null at exit time; no-op in that case
  832. if (!ui)
  833. return;
  834. if (enable)
  835. {
  836. if (ui->GetFocusElement() != this)
  837. ui->SetFocusElement(this);
  838. }
  839. else
  840. {
  841. if (ui->GetFocusElement() == this)
  842. ui->SetFocusElement(nullptr);
  843. }
  844. }
  845. void UIElement::SetSelected(bool enable)
  846. {
  847. selected_ = enable;
  848. }
  849. void UIElement::SetVisible(bool enable)
  850. {
  851. UI* ui = GetSubsystem<UI>();
  852. // Can be null at exit time; no-op in that case
  853. if (!ui)
  854. return;
  855. if (enable != visible_)
  856. {
  857. visible_ = enable;
  858. // Parent's layout may change as a result of visibility change
  859. if (parent_)
  860. parent_->UpdateLayout();
  861. using namespace VisibleChanged;
  862. VariantMap& eventData = GetEventDataMap();
  863. eventData[P_ELEMENT] = this;
  864. eventData[P_VISIBLE] = visible_;
  865. SendEvent(E_VISIBLECHANGED, eventData);
  866. // If the focus element becomes effectively hidden, clear focus
  867. if (!enable)
  868. {
  869. UIElement* focusElement = ui->GetFocusElement();
  870. if (focusElement && !focusElement->IsVisibleEffective())
  871. focusElement->SetFocus(false);
  872. }
  873. }
  874. }
  875. void UIElement::SetDragDropMode(unsigned mode)
  876. {
  877. dragDropMode_ = mode;
  878. }
  879. bool UIElement::SetStyle(const String& styleName, XMLFile* file)
  880. {
  881. // If empty style was requested, replace with type name
  882. String actualStyleName = !styleName.Empty() ? styleName : GetTypeName();
  883. appliedStyle_ = actualStyleName;
  884. if (styleName == "none")
  885. return true;
  886. if (!file)
  887. {
  888. file = GetDefaultStyle();
  889. if (!file)
  890. return false;
  891. }
  892. else
  893. {
  894. // If a custom style file specified, remember it
  895. defaultStyle_ = file;
  896. }
  897. // Remember the effectively applied style file, either custom or default
  898. appliedStyleFile_ = file;
  899. styleXPathQuery_.SetVariable("typeName", actualStyleName);
  900. XMLElement styleElem = file->GetRoot().SelectSinglePrepared(styleXPathQuery_);
  901. return styleElem && SetStyle(styleElem);
  902. }
  903. bool UIElement::SetStyle(const XMLElement& element)
  904. {
  905. appliedStyle_ = element.GetAttribute("type");
  906. // Consider style attribute values as instance-level attribute default values
  907. return LoadXML(element, true);
  908. }
  909. bool UIElement::SetStyleAuto(XMLFile* file)
  910. {
  911. return SetStyle(String::EMPTY, file);
  912. }
  913. void UIElement::SetDefaultStyle(XMLFile* style)
  914. {
  915. defaultStyle_ = style;
  916. }
  917. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  918. {
  919. layoutMode_ = mode;
  920. layoutSpacing_ = Max(spacing, 0);
  921. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  922. VerifyChildAlignment();
  923. UpdateLayout();
  924. }
  925. void UIElement::SetLayoutMode(LayoutMode mode)
  926. {
  927. layoutMode_ = mode;
  928. VerifyChildAlignment();
  929. UpdateLayout();
  930. }
  931. void UIElement::SetLayoutSpacing(int spacing)
  932. {
  933. layoutSpacing_ = Max(spacing, 0);
  934. UpdateLayout();
  935. }
  936. void UIElement::SetLayoutBorder(const IntRect& border)
  937. {
  938. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  939. UpdateLayout();
  940. }
  941. void UIElement::SetLayoutFlexScale(const Vector2& scale)
  942. {
  943. layoutFlexScale_ = Vector2(Max(scale.x_, 0.0f), Max(scale.y_, 0.0f));
  944. }
  945. void UIElement::SetIndent(int indent)
  946. {
  947. indent_ = indent;
  948. if (parent_)
  949. parent_->UpdateLayout();
  950. UpdateLayout();
  951. OnIndentSet();
  952. }
  953. void UIElement::SetIndentSpacing(int indentSpacing)
  954. {
  955. indentSpacing_ = Max(indentSpacing, 0);
  956. if (parent_)
  957. parent_->UpdateLayout();
  958. UpdateLayout();
  959. OnIndentSet();
  960. }
  961. void UIElement::UpdateLayout()
  962. {
  963. if (layoutNestingLevel_)
  964. return;
  965. // Prevent further updates while this update happens
  966. DisableLayoutUpdate();
  967. PODVector<int> positions;
  968. PODVector<int> sizes;
  969. PODVector<int> minSizes;
  970. PODVector<int> maxSizes;
  971. PODVector<float> flexScales;
  972. int baseIndentWidth = GetIndentWidth();
  973. if (layoutMode_ == LM_HORIZONTAL)
  974. {
  975. int minChildHeight = 0;
  976. for (unsigned i = 0; i < children_.Size(); ++i)
  977. {
  978. if (!children_[i]->IsVisible())
  979. continue;
  980. positions.Push(baseIndentWidth);
  981. unsigned indent = (unsigned)children_[i]->GetIndentWidth();
  982. sizes.Push(children_[i]->GetWidth() + indent);
  983. minSizes.Push(children_[i]->GetEffectiveMinSize().x_ + indent);
  984. maxSizes.Push(children_[i]->GetMaxWidth() + indent);
  985. flexScales.Push(children_[i]->GetLayoutFlexScale().x_);
  986. minChildHeight = Max(minChildHeight, children_[i]->GetEffectiveMinSize().y_);
  987. }
  988. CalculateLayout(positions, sizes, minSizes, maxSizes, flexScales, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  989. layoutSpacing_);
  990. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  991. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  992. int minWidth = CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  993. int minHeight = minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_;
  994. layoutMinSize_ = IntVector2(minWidth, minHeight);
  995. SetSize(width, height);
  996. // Validate the size before resizing child elements, in case of min/max limits
  997. width = size_.x_;
  998. height = size_.y_;
  999. unsigned j = 0;
  1000. for (unsigned i = 0; i < children_.Size(); ++i)
  1001. {
  1002. if (!children_[i]->IsVisible())
  1003. continue;
  1004. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  1005. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  1006. ++j;
  1007. }
  1008. }
  1009. else if (layoutMode_ == LM_VERTICAL)
  1010. {
  1011. int minChildWidth = 0;
  1012. for (unsigned i = 0; i < children_.Size(); ++i)
  1013. {
  1014. if (!children_[i]->IsVisible())
  1015. continue;
  1016. positions.Push(0);
  1017. sizes.Push(children_[i]->GetHeight());
  1018. minSizes.Push(children_[i]->GetEffectiveMinSize().y_);
  1019. maxSizes.Push(children_[i]->GetMaxHeight());
  1020. flexScales.Push(children_[i]->GetLayoutFlexScale().y_);
  1021. minChildWidth = Max(minChildWidth, children_[i]->GetEffectiveMinSize().x_ + children_[i]->GetIndentWidth());
  1022. }
  1023. CalculateLayout(positions, sizes, minSizes, maxSizes, flexScales, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  1024. layoutSpacing_);
  1025. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  1026. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  1027. int minHeight = CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  1028. int minWidth = minChildWidth + layoutBorder_.left_ + layoutBorder_.right_;
  1029. layoutMinSize_ = IntVector2(minWidth, minHeight);
  1030. SetSize(width, height);
  1031. width = size_.x_;
  1032. height = size_.y_;
  1033. unsigned j = 0;
  1034. for (unsigned i = 0; i < children_.Size(); ++i)
  1035. {
  1036. if (!children_[i]->IsVisible())
  1037. continue;
  1038. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_ + baseIndentWidth, positions[j]);
  1039. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  1040. ++j;
  1041. }
  1042. }
  1043. else
  1044. {
  1045. for (unsigned i = 0; i < children_.Size(); ++i)
  1046. {
  1047. if (children_[i]->GetEnableAnchor())
  1048. children_[i]->UpdateAnchoring();
  1049. }
  1050. }
  1051. using namespace LayoutUpdated;
  1052. VariantMap& eventData = GetEventDataMap();
  1053. eventData[P_ELEMENT] = this;
  1054. SendEvent(E_LAYOUTUPDATED, eventData);
  1055. EnableLayoutUpdate();
  1056. }
  1057. void UIElement::DisableLayoutUpdate()
  1058. {
  1059. ++layoutNestingLevel_;
  1060. }
  1061. void UIElement::EnableLayoutUpdate()
  1062. {
  1063. --layoutNestingLevel_;
  1064. }
  1065. void UIElement::BringToFront()
  1066. {
  1067. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  1068. UIElement* root = GetRoot();
  1069. // If element is detached from hierarchy, this must be a no-op
  1070. if (!root)
  1071. return;
  1072. UIElement* ptr = this;
  1073. while (ptr && ptr->GetParent() != root)
  1074. ptr = ptr->GetParent();
  1075. if (!ptr || !ptr->GetBringToFront())
  1076. return;
  1077. // Get the highest priority used by all other top level elements, assign that to the new front element
  1078. // and decrease others' priority where necessary. However, take into account only input-enabled
  1079. // elements and those which have the BringToBack flag set
  1080. HashSet<int> usedPriorities;
  1081. int maxPriority = M_MIN_INT;
  1082. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  1083. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  1084. {
  1085. UIElement* other = *i;
  1086. if (other->IsEnabled() && other->bringToBack_ && other != ptr)
  1087. {
  1088. int priority = other->GetPriority();
  1089. // M_MAX_INT is used by popups and tooltips. Disregard these to avoid an "arms race" with the priorities
  1090. if (priority == M_MAX_INT)
  1091. continue;
  1092. usedPriorities.Insert(priority);
  1093. maxPriority = Max(priority, maxPriority);
  1094. }
  1095. }
  1096. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  1097. {
  1098. ptr->SetPriority(maxPriority);
  1099. int minPriority = maxPriority;
  1100. while (usedPriorities.Contains(minPriority))
  1101. --minPriority;
  1102. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  1103. {
  1104. UIElement* other = *i;
  1105. int priority = other->GetPriority();
  1106. if (other->IsEnabled() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  1107. other->SetPriority(priority - 1);
  1108. }
  1109. }
  1110. }
  1111. UIElement* UIElement::CreateChild(StringHash type, const String& name, unsigned index)
  1112. {
  1113. // Check that creation succeeds and that the object in fact is a UI element
  1114. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  1115. if (!newElement)
  1116. {
  1117. URHO3D_LOGERROR("Could not create unknown UI element type " + type.ToString());
  1118. return nullptr;
  1119. }
  1120. if (!name.Empty())
  1121. newElement->SetName(name);
  1122. InsertChild(index, newElement);
  1123. return newElement;
  1124. }
  1125. void UIElement::AddChild(UIElement* element)
  1126. {
  1127. InsertChild(M_MAX_UNSIGNED, element);
  1128. }
  1129. void UIElement::InsertChild(unsigned index, UIElement* element)
  1130. {
  1131. // Check for illegal or redundant parent assignment
  1132. if (!element || element == this || element->parent_ == this)
  1133. return;
  1134. // Check for possible cyclic parent assignment
  1135. UIElement* parent = parent_;
  1136. while (parent)
  1137. {
  1138. if (parent == element)
  1139. return;
  1140. parent = parent->parent_;
  1141. }
  1142. // Add first, then remove from old parent, to ensure the element does not get deleted
  1143. if (index >= children_.Size())
  1144. children_.Push(SharedPtr<UIElement>(element));
  1145. else
  1146. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  1147. element->Remove();
  1148. if (sortChildren_)
  1149. sortOrderDirty_ = true;
  1150. element->parent_ = this;
  1151. element->MarkDirty();
  1152. // Apply style now if child element (and its children) has it defined
  1153. ApplyStyleRecursive(element);
  1154. VerifyChildAlignment();
  1155. UpdateLayout();
  1156. // Send change event
  1157. UIElement* root = GetRoot();
  1158. UIElement* sender = GetElementEventSender();
  1159. if (sender)
  1160. {
  1161. using namespace ElementAdded;
  1162. VariantMap& eventData = GetEventDataMap();
  1163. eventData[P_ROOT] = root;
  1164. eventData[P_PARENT] = this;
  1165. eventData[P_ELEMENT] = element;
  1166. sender->SendEvent(E_ELEMENTADDED, eventData);
  1167. }
  1168. }
  1169. void UIElement::RemoveChild(UIElement* element, unsigned index)
  1170. {
  1171. for (unsigned i = index; i < children_.Size(); ++i)
  1172. {
  1173. if (children_[i] == element)
  1174. {
  1175. // Send change event if not already being destroyed
  1176. UIElement* sender = Refs() > 0 ? GetElementEventSender() : nullptr;
  1177. if (sender)
  1178. {
  1179. using namespace ElementRemoved;
  1180. VariantMap& eventData = GetEventDataMap();
  1181. eventData[P_ROOT] = GetRoot();
  1182. eventData[P_PARENT] = this;
  1183. eventData[P_ELEMENT] = element;
  1184. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1185. }
  1186. element->Detach();
  1187. children_.Erase(i);
  1188. UpdateLayout();
  1189. return;
  1190. }
  1191. }
  1192. }
  1193. void UIElement::RemoveChildAtIndex(unsigned index)
  1194. {
  1195. if (index >= children_.Size())
  1196. return;
  1197. // Send change event if not already being destroyed
  1198. UIElement* sender = Refs() > 0 ? GetElementEventSender() : nullptr;
  1199. if (sender)
  1200. {
  1201. using namespace ElementRemoved;
  1202. VariantMap& eventData = GetEventDataMap();
  1203. eventData[P_ROOT] = GetRoot();
  1204. eventData[P_PARENT] = this;
  1205. eventData[P_ELEMENT] = children_[index];
  1206. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1207. }
  1208. children_[index]->Detach();
  1209. children_.Erase(index);
  1210. UpdateLayout();
  1211. }
  1212. void UIElement::RemoveAllChildren()
  1213. {
  1214. UIElement* root = GetRoot();
  1215. UIElement* sender = Refs() > 0 ? GetElementEventSender() : nullptr;
  1216. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End();)
  1217. {
  1218. // Send change event if not already being destroyed
  1219. if (sender)
  1220. {
  1221. using namespace ElementRemoved;
  1222. VariantMap& eventData = GetEventDataMap();
  1223. eventData[P_ROOT] = root;
  1224. eventData[P_PARENT] = this;
  1225. eventData[P_ELEMENT] = (*i).Get();
  1226. sender->SendEvent(E_ELEMENTREMOVED, eventData);
  1227. }
  1228. (*i++)->Detach();
  1229. }
  1230. children_.Clear();
  1231. UpdateLayout();
  1232. }
  1233. void UIElement::Remove()
  1234. {
  1235. if (parent_)
  1236. parent_->RemoveChild(this);
  1237. }
  1238. unsigned UIElement::FindChild(UIElement* element) const
  1239. {
  1240. Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Find(SharedPtr<UIElement>(element));
  1241. return i != children_.End() ? (unsigned)(i - children_.Begin()) : M_MAX_UNSIGNED;
  1242. }
  1243. void UIElement::SetParent(UIElement* parent, unsigned index)
  1244. {
  1245. if (parent)
  1246. parent->InsertChild(index, this);
  1247. }
  1248. void UIElement::SetVar(StringHash key, const Variant& value)
  1249. {
  1250. vars_[key] = value;
  1251. }
  1252. void UIElement::SetInternal(bool enable)
  1253. {
  1254. internal_ = enable;
  1255. }
  1256. void UIElement::SetTraversalMode(TraversalMode traversalMode)
  1257. {
  1258. traversalMode_ = traversalMode;
  1259. }
  1260. void UIElement::SetElementEventSender(bool flag)
  1261. {
  1262. elementEventSender_ = flag;
  1263. }
  1264. void UIElement::SetTags(const StringVector& tags)
  1265. {
  1266. RemoveAllTags();
  1267. AddTags(tags);
  1268. }
  1269. void UIElement::AddTag(const String& tag)
  1270. {
  1271. if (tag.Empty() || HasTag(tag))
  1272. return;
  1273. tags_.Push(tag);
  1274. }
  1275. void UIElement::AddTags(const String& tags, char separator)
  1276. {
  1277. StringVector tagVector = tags.Split(separator);
  1278. AddTags(tagVector);
  1279. }
  1280. void UIElement::AddTags(const StringVector& tags)
  1281. {
  1282. for (unsigned i = 0; i < tags.Size(); ++i)
  1283. AddTag(tags[i]);
  1284. }
  1285. bool UIElement::RemoveTag(const String& tag)
  1286. {
  1287. return tags_.Remove(tag);
  1288. }
  1289. void UIElement::RemoveAllTags()
  1290. {
  1291. tags_.Clear();
  1292. }
  1293. HorizontalAlignment UIElement::GetHorizontalAlignment() const
  1294. {
  1295. if (anchorMin_.x_ == 0.0f && anchorMax_.x_ == 0.0f && (!pivotSet_ || pivot_.x_ == 0.0f))
  1296. return HA_LEFT;
  1297. else if (anchorMin_.x_ == 0.5f && anchorMax_.x_ == 0.5f && (!pivotSet_ || pivot_.x_ == 0.5f))
  1298. return HA_CENTER;
  1299. else if (anchorMin_.x_ == 1.0f && anchorMax_.x_ == 1.0f && (!pivotSet_ || pivot_.x_ == 1.0f))
  1300. return HA_RIGHT;
  1301. return HA_CUSTOM;
  1302. }
  1303. VerticalAlignment UIElement::GetVerticalAlignment() const
  1304. {
  1305. if (anchorMin_.y_ == 0.0f && anchorMax_.y_ == 0.0f && (!pivotSet_ || pivot_.y_ == 0.0f))
  1306. return VA_TOP;
  1307. else if (anchorMin_.y_ == 0.5f && anchorMax_.y_ == 0.5f && (!pivotSet_ || pivot_.y_ == 0.5f))
  1308. return VA_CENTER;
  1309. else if (anchorMin_.y_ == 1.0f && anchorMax_.y_ == 1.0f && (!pivotSet_ || pivot_.y_ == 1.0f))
  1310. return VA_BOTTOM;
  1311. return VA_CUSTOM;
  1312. }
  1313. float UIElement::GetDerivedOpacity() const
  1314. {
  1315. if (!useDerivedOpacity_)
  1316. return opacity_;
  1317. if (opacityDirty_)
  1318. {
  1319. derivedOpacity_ = opacity_;
  1320. const UIElement* parent = parent_;
  1321. while (parent)
  1322. {
  1323. derivedOpacity_ *= parent->opacity_;
  1324. parent = parent->parent_;
  1325. }
  1326. opacityDirty_ = false;
  1327. }
  1328. return derivedOpacity_;
  1329. }
  1330. bool UIElement::HasFocus() const
  1331. {
  1332. UI* ui = GetSubsystem<UI>();
  1333. return ui ? ui->GetFocusElement() == this : false;
  1334. }
  1335. bool UIElement::IsVisibleEffective() const
  1336. {
  1337. bool visible = visible_;
  1338. const UIElement* element = parent_;
  1339. // Traverse the parent chain
  1340. while (visible && element)
  1341. {
  1342. visible &= element->visible_;
  1343. element = element->parent_;
  1344. }
  1345. return visible;
  1346. }
  1347. const String& UIElement::GetAppliedStyle() const
  1348. {
  1349. return appliedStyle_ == GetTypeName() ? String::EMPTY : appliedStyle_;
  1350. }
  1351. XMLFile* UIElement::GetDefaultStyle(bool recursiveUp) const
  1352. {
  1353. if (recursiveUp)
  1354. {
  1355. const UIElement* element = this;
  1356. while (element)
  1357. {
  1358. if (element->defaultStyle_)
  1359. return element->defaultStyle_;
  1360. element = element->parent_;
  1361. }
  1362. return nullptr;
  1363. }
  1364. else
  1365. return defaultStyle_;
  1366. }
  1367. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  1368. {
  1369. dest.Clear();
  1370. if (!recursive)
  1371. {
  1372. dest.Reserve(children_.Size());
  1373. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1374. dest.Push(*i);
  1375. }
  1376. else
  1377. GetChildrenRecursive(dest);
  1378. }
  1379. unsigned UIElement::GetNumChildren(bool recursive) const
  1380. {
  1381. if (!recursive)
  1382. return children_.Size();
  1383. else
  1384. {
  1385. unsigned allChildren = children_.Size();
  1386. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1387. allChildren += (*i)->GetNumChildren(true);
  1388. return allChildren;
  1389. }
  1390. }
  1391. UIElement* UIElement::GetChild(unsigned index) const
  1392. {
  1393. return index < children_.Size() ? children_[index] : nullptr;
  1394. }
  1395. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  1396. {
  1397. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1398. {
  1399. if ((*i)->name_ == name)
  1400. return *i;
  1401. if (recursive)
  1402. {
  1403. UIElement* element = (*i)->GetChild(name, true);
  1404. if (element)
  1405. return element;
  1406. }
  1407. }
  1408. return nullptr;
  1409. }
  1410. UIElement* UIElement::GetChild(const StringHash& key, const Variant& value, bool recursive) const
  1411. {
  1412. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1413. {
  1414. const Variant& varValue = (*i)->GetVar(key);
  1415. if (value != Variant::EMPTY ? varValue == value : varValue != Variant::EMPTY)
  1416. return *i;
  1417. if (recursive)
  1418. {
  1419. UIElement* element = (*i)->GetChild(key, value, true);
  1420. if (element)
  1421. return element;
  1422. }
  1423. }
  1424. return nullptr;
  1425. }
  1426. UIElement* UIElement::GetRoot() const
  1427. {
  1428. UIElement* root = parent_;
  1429. if (!root)
  1430. return nullptr;
  1431. while (root->GetParent())
  1432. root = root->GetParent();
  1433. return root;
  1434. }
  1435. const Color& UIElement::GetDerivedColor() const
  1436. {
  1437. if (derivedColorDirty_)
  1438. {
  1439. derivedColor_ = color_[C_TOPLEFT];
  1440. derivedColor_.a_ *= GetDerivedOpacity();
  1441. derivedColorDirty_ = false;
  1442. }
  1443. return derivedColor_;
  1444. }
  1445. const Variant& UIElement::GetVar(const StringHash& key) const
  1446. {
  1447. VariantMap::ConstIterator i = vars_.Find(key);
  1448. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1449. }
  1450. bool UIElement::HasTag(const String& tag) const
  1451. {
  1452. return tags_.Contains(tag);
  1453. }
  1454. void UIElement::GetChildrenWithTag(PODVector<UIElement*>& dest, const String& tag, bool recursive) const
  1455. {
  1456. dest.Clear();
  1457. if (!recursive)
  1458. {
  1459. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1460. {
  1461. UIElement* element = *i;
  1462. if (element->HasTag(tag))
  1463. dest.Push(element);
  1464. }
  1465. }
  1466. else
  1467. GetChildrenWithTagRecursive(dest, tag);
  1468. }
  1469. PODVector<UIElement*> UIElement::GetChildrenWithTag(const String& tag, bool recursive) const
  1470. {
  1471. PODVector<UIElement*> dest;
  1472. GetChildrenWithTag(dest, tag, recursive);
  1473. return dest;
  1474. }
  1475. void UIElement::GetChildrenWithTagRecursive(PODVector<UIElement*>& dest, const String& tag) const
  1476. {
  1477. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1478. {
  1479. UIElement* element = *i;
  1480. if (element->HasTag(tag))
  1481. dest.Push(element);
  1482. if (!element->children_.Empty())
  1483. element->GetChildrenWithTagRecursive(dest, tag);
  1484. }
  1485. }
  1486. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  1487. {
  1488. if (isScreen)
  1489. position = ScreenToElement(position);
  1490. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  1491. }
  1492. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  1493. {
  1494. // If child elements are clipped, no need to expand the rect
  1495. if (clipChildren_)
  1496. return IsInside(position, isScreen);
  1497. if (!isScreen)
  1498. position = ElementToScreen(position);
  1499. IntRect combined = GetCombinedScreenRect();
  1500. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  1501. position.y_ < combined.bottom_;
  1502. }
  1503. IntRect UIElement::GetCombinedScreenRect()
  1504. {
  1505. IntVector2 screenPosition(GetScreenPosition());
  1506. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  1507. if (!clipChildren_)
  1508. {
  1509. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1510. {
  1511. IntRect childCombined((*i)->GetCombinedScreenRect());
  1512. if (childCombined.left_ < combined.left_)
  1513. combined.left_ = childCombined.left_;
  1514. if (childCombined.right_ > combined.right_)
  1515. combined.right_ = childCombined.right_;
  1516. if (childCombined.top_ < combined.top_)
  1517. combined.top_ = childCombined.top_;
  1518. if (childCombined.bottom_ > combined.bottom_)
  1519. combined.bottom_ = childCombined.bottom_;
  1520. }
  1521. }
  1522. return combined;
  1523. }
  1524. void UIElement::SortChildren()
  1525. {
  1526. if (sortChildren_ && sortOrderDirty_)
  1527. {
  1528. // Only sort when there is no layout
  1529. /// \todo Order is not stable when children have same priorities
  1530. if (layoutMode_ == LM_FREE)
  1531. Sort(children_.Begin(), children_.End(), CompareUIElements);
  1532. sortOrderDirty_ = false;
  1533. }
  1534. }
  1535. void UIElement::SetChildOffset(const IntVector2& offset)
  1536. {
  1537. if (offset != childOffset_)
  1538. {
  1539. childOffset_ = offset;
  1540. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1541. (*i)->MarkDirty();
  1542. }
  1543. }
  1544. void UIElement::SetHovering(bool enable)
  1545. {
  1546. hovering_ = enable;
  1547. }
  1548. void UIElement::AdjustScissor(IntRect& currentScissor)
  1549. {
  1550. if (clipChildren_)
  1551. {
  1552. IntVector2 screenPos = GetScreenPosition();
  1553. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1554. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1555. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1556. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1557. if (currentScissor.right_ < currentScissor.left_)
  1558. currentScissor.right_ = currentScissor.left_;
  1559. if (currentScissor.bottom_ < currentScissor.top_)
  1560. currentScissor.bottom_ = currentScissor.top_;
  1561. }
  1562. }
  1563. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<float>& vertexData,
  1564. IntRect currentScissor)
  1565. {
  1566. Vector2 floatOffset((float)offset.x_, (float)offset.y_);
  1567. unsigned initialSize = vertexData.Size();
  1568. GetBatches(batches, vertexData, currentScissor);
  1569. for (unsigned i = initialSize; i < vertexData.Size(); i += 6)
  1570. {
  1571. vertexData[i] += floatOffset.x_;
  1572. vertexData[i + 1] += floatOffset.y_;
  1573. }
  1574. AdjustScissor(currentScissor);
  1575. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1576. {
  1577. if ((*i)->IsVisible())
  1578. (*i)->GetBatchesWithOffset(offset, batches, vertexData, currentScissor);
  1579. }
  1580. }
  1581. UIElement* UIElement::GetElementEventSender() const
  1582. {
  1583. UIElement* element = const_cast<UIElement*>(this);
  1584. if (elementEventSender_)
  1585. return element;
  1586. while (element->parent_)
  1587. {
  1588. element = element->parent_;
  1589. if (element->elementEventSender_)
  1590. return element;
  1591. }
  1592. // If no predefined element event sender in the parental chain, return ultimate root element
  1593. return element;
  1594. }
  1595. IntVector2 UIElement::GetEffectiveMinSize() const
  1596. {
  1597. if (IsFixedSize() || layoutMode_ == LM_FREE || layoutMinSize_ == IntVector2::ZERO)
  1598. return minSize_;
  1599. else
  1600. return IntVector2(Max(minSize_.x_, layoutMinSize_.x_), Max(minSize_.y_, layoutMinSize_.y_));
  1601. }
  1602. void UIElement::OnAttributeAnimationAdded()
  1603. {
  1604. if (attributeAnimationInfos_.Size() == 1)
  1605. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UIElement, HandlePostUpdate));
  1606. }
  1607. void UIElement::OnAttributeAnimationRemoved()
  1608. {
  1609. if (attributeAnimationInfos_.Empty())
  1610. UnsubscribeFromEvent(E_POSTUPDATE);
  1611. }
  1612. Animatable* UIElement::FindAttributeAnimationTarget(const String& name, String& outName)
  1613. {
  1614. Vector<String> names = name.Split('/');
  1615. // Only attribute name
  1616. if (names.Size() == 1)
  1617. {
  1618. outName = name;
  1619. return this;
  1620. }
  1621. else
  1622. {
  1623. // Name must in following format: "#0/#1/attribute"
  1624. UIElement* element = this;
  1625. for (unsigned i = 0; i < names.Size() - 1; ++i)
  1626. {
  1627. if (names[i].Front() != '#')
  1628. {
  1629. URHO3D_LOGERROR("Invalid name " + name);
  1630. return nullptr;
  1631. }
  1632. String name = names[i].Substring(1, names[i].Length() - 1);
  1633. char s = name.Front();
  1634. if (s >= '0' && s <= '9')
  1635. {
  1636. unsigned index = ToUInt(name);
  1637. element = element->GetChild(index);
  1638. }
  1639. else
  1640. {
  1641. element = element->GetChild(name, true);
  1642. }
  1643. if (!element)
  1644. {
  1645. URHO3D_LOGERROR("Could not find element by name " + name);
  1646. return nullptr;
  1647. }
  1648. }
  1649. outName = names.Back();
  1650. return element;
  1651. }
  1652. }
  1653. void UIElement::MarkDirty()
  1654. {
  1655. positionDirty_ = true;
  1656. opacityDirty_ = true;
  1657. derivedColorDirty_ = true;
  1658. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1659. (*i)->MarkDirty();
  1660. }
  1661. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name) const
  1662. {
  1663. static XPathQuery matchXPathQuery("./attribute[@name=$attributeName]", "attributeName:String");
  1664. if (!matchXPathQuery.SetVariable("attributeName", name))
  1665. return false;
  1666. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1667. return !removeElem || parent.RemoveChild(removeElem);
  1668. }
  1669. bool UIElement::RemoveChildXML(XMLElement& parent, const String& name, const String& value) const
  1670. {
  1671. static XPathQuery matchXPathQuery
  1672. ("./attribute[@name=$attributeName and @value=$attributeValue]", "attributeName:String, attributeValue:String");
  1673. if (!matchXPathQuery.SetVariable("attributeName", name))
  1674. return false;
  1675. if (!matchXPathQuery.SetVariable("attributeValue", value))
  1676. return false;
  1677. XMLElement removeElem = parent.SelectSinglePrepared(matchXPathQuery);
  1678. return !removeElem || parent.RemoveChild(removeElem);
  1679. }
  1680. bool UIElement::FilterUIStyleAttributes(XMLElement& dest, const XMLElement& styleElem) const
  1681. {
  1682. // Remove style attribute only when its value is identical to the value stored in style file
  1683. String style = styleElem.GetAttribute("style");
  1684. if (!style.Empty())
  1685. {
  1686. if (style == dest.GetAttribute("style"))
  1687. {
  1688. if (!dest.RemoveAttribute("style"))
  1689. {
  1690. URHO3D_LOGWARNING("Could not remove style attribute");
  1691. return false;
  1692. }
  1693. }
  1694. }
  1695. // Perform the same action recursively for internal child elements stored in style file
  1696. XMLElement childDest = dest.GetChild("element");
  1697. XMLElement childElem = styleElem.GetChild("element");
  1698. while (childDest && childElem)
  1699. {
  1700. if (!childElem.GetBool("internal"))
  1701. {
  1702. URHO3D_LOGERROR("Invalid style file, style element can only contain internal child elements");
  1703. return false;
  1704. }
  1705. if (!FilterUIStyleAttributes(childDest, childElem))
  1706. return false;
  1707. childDest = childDest.GetNext("element");
  1708. childElem = childElem.GetNext("element");
  1709. }
  1710. // Remove style attribute when it is the same as its type, however, if it is an internal element then replace it to "none" instead
  1711. if (!dest.GetAttribute("style").Empty() && dest.GetAttribute("style") == dest.GetAttribute("type"))
  1712. {
  1713. if (internal_)
  1714. {
  1715. if (!dest.SetAttribute("style", "none"))
  1716. return false;
  1717. }
  1718. else
  1719. {
  1720. if (!dest.RemoveAttribute("style"))
  1721. return false;
  1722. }
  1723. }
  1724. return true;
  1725. }
  1726. bool UIElement::FilterImplicitAttributes(XMLElement& dest) const
  1727. {
  1728. // Remove positioning and sizing attributes when they are under the influence of layout mode
  1729. if (layoutMode_ != LM_FREE && !IsFixedWidth() && !IsFixedHeight())
  1730. {
  1731. if (!RemoveChildXML(dest, "Min Size"))
  1732. return false;
  1733. }
  1734. if (parent_ && parent_->layoutMode_ != LM_FREE)
  1735. {
  1736. if (!RemoveChildXML(dest, "Position"))
  1737. return false;
  1738. if (!RemoveChildXML(dest, "Size"))
  1739. return false;
  1740. }
  1741. return true;
  1742. }
  1743. void UIElement::UpdateAnchoring()
  1744. {
  1745. if (parent_ && enableAnchor_)
  1746. {
  1747. IntVector2 newSize;
  1748. newSize.x_ = (int)(parent_->size_.x_ * Clamp(anchorMax_.x_ - anchorMin_.x_, 0.0f, 1.0f)) + maxOffset_.x_ - minOffset_.x_;
  1749. newSize.y_ = (int)(parent_->size_.y_ * Clamp(anchorMax_.y_ - anchorMin_.y_, 0.0f, 1.0f)) + maxOffset_.y_ - minOffset_.y_;
  1750. if (position_ != minOffset_)
  1751. SetPosition(minOffset_);
  1752. if (size_ != newSize)
  1753. SetSize(newSize);
  1754. }
  1755. }
  1756. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1757. {
  1758. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1759. {
  1760. UIElement* element = *i;
  1761. dest.Push(element);
  1762. if (!element->children_.Empty())
  1763. element->GetChildrenRecursive(dest);
  1764. }
  1765. }
  1766. void UIElement::ApplyStyleRecursive(UIElement* element)
  1767. {
  1768. // If child element style file changes as result of being (re)parented and it has a defined style, apply it now
  1769. if (!element->appliedStyle_.Empty() && element->appliedStyleFile_.Get() != element->GetDefaultStyle())
  1770. {
  1771. element->SetStyle(element->appliedStyle_);
  1772. for (Vector<SharedPtr<UIElement> >::ConstIterator i = element->children_.Begin(); i != element->children_.End(); ++i)
  1773. element->ApplyStyleRecursive(*i);
  1774. }
  1775. }
  1776. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1777. {
  1778. int width = begin + end;
  1779. if (sizes.Empty())
  1780. return width;
  1781. for (unsigned i = 0; i < sizes.Size(); ++i)
  1782. {
  1783. // If calculating maximum size, and the default is specified, do not overflow it
  1784. if (sizes[i] == M_MAX_INT)
  1785. return M_MAX_INT;
  1786. width += sizes[i] + spacing;
  1787. }
  1788. // The last spacing is not needed
  1789. return width - spacing;
  1790. }
  1791. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1792. const PODVector<int>& maxSizes, const PODVector<float>& flexScales, int targetSize, int begin, int end, int spacing)
  1793. {
  1794. unsigned numChildren = sizes.Size();
  1795. if (!numChildren)
  1796. return;
  1797. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1798. if (targetTotalSize < 0)
  1799. targetTotalSize = 0;
  1800. int targetChildSize = targetTotalSize / numChildren;
  1801. int remainder = targetTotalSize % numChildren;
  1802. float add = (float)remainder / numChildren;
  1803. float acc = 0.0f;
  1804. // Initial pass
  1805. for (unsigned i = 0; i < numChildren; ++i)
  1806. {
  1807. int targetSize = (int)(targetChildSize * flexScales[i]);
  1808. if (remainder)
  1809. {
  1810. acc += add;
  1811. if (acc >= 0.5f)
  1812. {
  1813. acc -= 1.0f;
  1814. ++targetSize;
  1815. --remainder;
  1816. }
  1817. }
  1818. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1819. }
  1820. // Error correction passes
  1821. for (;;)
  1822. {
  1823. int actualTotalSize = 0;
  1824. for (unsigned i = 0; i < numChildren; ++i)
  1825. actualTotalSize += sizes[i];
  1826. int error = targetTotalSize - actualTotalSize;
  1827. // Break if no error
  1828. if (!error)
  1829. break;
  1830. // Check which of the children can be resized to correct the error. If none, must break
  1831. PODVector<unsigned> resizable;
  1832. for (unsigned i = 0; i < numChildren; ++i)
  1833. {
  1834. if (error < 0 && sizes[i] > minSizes[i])
  1835. resizable.Push(i);
  1836. else if (error > 0 && sizes[i] < maxSizes[i])
  1837. resizable.Push(i);
  1838. }
  1839. if (resizable.Empty())
  1840. break;
  1841. int numResizable = resizable.Size();
  1842. int errorPerChild = error / numResizable;
  1843. remainder = (abs(error)) % numResizable;
  1844. add = (float)remainder / numResizable;
  1845. acc = 0.0f;
  1846. for (int i = 0; i < numResizable; ++i)
  1847. {
  1848. unsigned index = resizable[i];
  1849. int targetSize = sizes[index] + errorPerChild;
  1850. if (remainder)
  1851. {
  1852. acc += add;
  1853. if (acc >= 0.5f)
  1854. {
  1855. acc -= 1.0f;
  1856. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1857. --remainder;
  1858. }
  1859. }
  1860. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1861. }
  1862. }
  1863. // Calculate final positions and store the maximum child element size for optimizations
  1864. layoutElementMaxSize_ = 0;
  1865. int position = begin;
  1866. for (unsigned i = 0; i < numChildren; ++i)
  1867. {
  1868. positions[i] = position;
  1869. position += sizes[i] + spacing;
  1870. if (sizes[i] > layoutElementMaxSize_)
  1871. layoutElementMaxSize_ = sizes[i];
  1872. }
  1873. }
  1874. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1875. {
  1876. IntVector2 ret(IntVector2::ZERO);
  1877. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1878. switch (ha)
  1879. {
  1880. case HA_LEFT:
  1881. ret.x_ = layoutBorder_.left_;
  1882. break;
  1883. case HA_RIGHT:
  1884. ret.x_ = -layoutBorder_.right_;
  1885. break;
  1886. default:
  1887. break;
  1888. }
  1889. VerticalAlignment va = child->GetVerticalAlignment();
  1890. switch (va)
  1891. {
  1892. case VA_TOP:
  1893. ret.y_ = layoutBorder_.top_;
  1894. break;
  1895. case VA_BOTTOM:
  1896. ret.y_ = -layoutBorder_.bottom_;
  1897. break;
  1898. default:
  1899. break;
  1900. }
  1901. return ret;
  1902. }
  1903. void UIElement::Detach()
  1904. {
  1905. parent_ = nullptr;
  1906. MarkDirty();
  1907. }
  1908. void UIElement::VerifyChildAlignment()
  1909. {
  1910. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1911. {
  1912. // Reapply child alignments. If they are illegal compared to layout, they will be set left/top as neded
  1913. (*i)->SetHorizontalAlignment((*i)->GetHorizontalAlignment());
  1914. (*i)->SetVerticalAlignment((*i)->GetVerticalAlignment());
  1915. }
  1916. }
  1917. void UIElement::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1918. {
  1919. using namespace PostUpdate;
  1920. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1921. }
  1922. }