UI.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "CheckBox.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "Cursor.h"
  28. #include "DropDownList.h"
  29. #include "FileSelector.h"
  30. #include "Font.h"
  31. #include "Graphics.h"
  32. #include "GraphicsEvents.h"
  33. #include "GraphicsImpl.h"
  34. #include "InputEvents.h"
  35. #include "LineEdit.h"
  36. #include "ListView.h"
  37. #include "Log.h"
  38. #include "Matrix4x3.h"
  39. #include "PixelShader.h"
  40. #include "Profiler.h"
  41. #include "ResourceCache.h"
  42. #include "ScrollBar.h"
  43. #include "Slider.h"
  44. #include "StringUtils.h"
  45. #include "Text.h"
  46. #include "Texture2D.h"
  47. #include "Time.h"
  48. #include "UI.h"
  49. #include "UIEvents.h"
  50. #include "VertexShader.h"
  51. #include "Window.h"
  52. #include <algorithm>
  53. #include "DebugNew.h"
  54. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  55. {
  56. return lhs->GetPriority() < rhs->GetPriority();
  57. }
  58. OBJECTTYPESTATIC(UI);
  59. UI::UI(Context* context) :
  60. Object(context),
  61. mouseButtons_(0),
  62. qualifiers_(0),
  63. initialized_(false)
  64. {
  65. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  66. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  67. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  68. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  69. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  70. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  71. SubscribeToEvent(E_CHAR, HANDLER(UI, HandleChar));
  72. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  73. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  74. // Try to initialize right now, but skip if screen mode is not yet set
  75. Initialize();
  76. }
  77. UI::~UI()
  78. {
  79. }
  80. void UI::SetCursor(Cursor* cursor)
  81. {
  82. // Remove old cursor (if any) and set new
  83. if (cursor_)
  84. {
  85. rootElement_->RemoveChild(cursor_);
  86. cursor_.Reset();
  87. }
  88. if (cursor)
  89. {
  90. rootElement_->AddChild(cursor);
  91. cursor_ = cursor;
  92. IntVector2 pos = cursor_->GetPosition();
  93. const IntVector2& rootSize = rootElement_->GetSize();
  94. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  95. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  96. cursor_->SetPosition(pos);
  97. }
  98. }
  99. void UI::SetFocusElement(UIElement* element)
  100. {
  101. using namespace FocusChanged;
  102. VariantMap eventData;
  103. eventData[P_ORIGINALELEMENT] = (void*)element;
  104. if (element)
  105. {
  106. // Return if already has focus
  107. if (element->HasFocus())
  108. return;
  109. // If element can not be focused, and does not reset the focus either, search toward the parent
  110. for (;;)
  111. {
  112. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  113. break;
  114. element = element->GetParent();
  115. // Return if did not find any parent element that changes the focus
  116. if (!element)
  117. return;
  118. }
  119. }
  120. std::vector<UIElement*> allChildren = rootElement_->GetChildren(true);
  121. // Go through all elements to clear the old focus
  122. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  123. {
  124. UIElement* other = *i;
  125. if ((other != element) && (other->HasFocus()))
  126. other->SetFocus(false);
  127. }
  128. if (element)
  129. element->SetFocus(true);
  130. eventData[P_ELEMENT] = (void*)element;
  131. SendEvent(E_FOCUSCHANGED, eventData);
  132. }
  133. void UI::Clear()
  134. {
  135. rootElement_->RemoveAllChildren();
  136. if (cursor_)
  137. rootElement_->AddChild(cursor_);
  138. }
  139. void UI::Update(float timeStep)
  140. {
  141. PROFILE(UpdateUI);
  142. if ((cursor_) && (cursor_->IsVisible()))
  143. {
  144. IntVector2 pos = cursor_->GetPosition();
  145. WeakPtr<UIElement> element(GetElementAt(pos));
  146. bool dragSource = (dragElement_) && ((dragElement_->GetDragDropMode() & DD_SOURCE) != 0);
  147. bool dragTarget = (element) && ((element->GetDragDropMode() & DD_TARGET) != 0);
  148. bool dragDropTest = (dragSource) && (dragTarget) && (element != dragElement_);
  149. // Hover effect
  150. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  151. if (element)
  152. {
  153. if ((!dragElement_) || (dragElement_ == element) || (dragDropTest))
  154. element->OnHover(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  155. }
  156. // Drag and drop test
  157. if (dragDropTest)
  158. {
  159. bool accept = element->OnDragDropTest(dragElement_);
  160. if (accept)
  161. {
  162. using namespace DragDropTest;
  163. VariantMap eventData;
  164. eventData[P_SOURCE] = (void*)dragElement_.GetPtr();
  165. eventData[P_TARGET] = (void*)element.GetPtr();
  166. eventData[P_ACCEPT] = accept;
  167. SendEvent(E_DRAGDROPTEST, eventData);
  168. accept = eventData[P_ACCEPT].GetBool();
  169. }
  170. cursor_->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  171. }
  172. else if (dragSource)
  173. cursor_->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  174. }
  175. // Defocus element now if should
  176. if (defocusElement_)
  177. {
  178. // Do nothing if the focus element changed in the meanwhile
  179. if (defocusElement_ == GetFocusElement())
  180. SetFocusElement(0);
  181. defocusElement_.Reset();
  182. }
  183. Update(timeStep, rootElement_);
  184. }
  185. void UI::RenderUpdate()
  186. {
  187. if ((!graphics_) || (graphics_->IsDeviceLost()))
  188. return;
  189. PROFILE(GetUIBatches);
  190. batches_.clear();
  191. quads_.clear();
  192. const IntVector2& rootSize = rootElement_->GetSize();
  193. GetBatches(rootElement_, IntRect(0, 0, rootSize.x_, rootSize.y_));
  194. // If no drag, reset cursor shape for next frame
  195. if ((cursor_) && (!dragElement_))
  196. cursor_->SetShape(CS_NORMAL);
  197. }
  198. void UI::Render()
  199. {
  200. PROFILE(RenderUI);
  201. if (!graphics_)
  202. return;
  203. Vector2 scale(2.0f, -2.0f);
  204. Vector2 offset(-1.0f, 1.0f);
  205. Matrix4 projection(Matrix4::IDENTITY);
  206. projection.m00_ = scale.x_;
  207. projection.m03_ = offset.x_;
  208. projection.m11_ = scale.y_;
  209. projection.m13_ = offset.y_;
  210. projection.m22_ = 1.0f;
  211. projection.m23_ = 0.0f;
  212. projection.m33_ = 1.0f;
  213. graphics_->ResetRenderTargets();
  214. graphics_->SetCullMode(CULL_CCW);
  215. graphics_->SetDepthTest(CMP_ALWAYS);
  216. graphics_->SetDepthWrite(false);
  217. graphics_->SetFillMode(FILL_SOLID);
  218. graphics_->SetStencilTest(false);
  219. graphics_->SetVertexShaderParameter(VSP_MODEL, Matrix4x3::IDENTITY);
  220. graphics_->SetVertexShaderParameter(VSP_VIEWPROJ, projection);
  221. graphics_->SetPixelShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  222. PixelShader* ps = 0;
  223. VertexShader* vs = 0;
  224. for (unsigned i = 0; i < batches_.size(); ++i)
  225. {
  226. // Choose shaders here so that UIBatch does not need to look up shaders each time
  227. if (!batches_[i].texture_)
  228. {
  229. ps = noTexturePS_;
  230. vs = noTextureVS_;
  231. }
  232. else
  233. {
  234. // If texture contains only an alpha channel, use the alpha pixel shader
  235. vs = diffTextureVS_;
  236. if (batches_[i].texture_->GetFormat() == D3DFMT_A8)
  237. ps = alphaTexturePS_;
  238. else
  239. ps = diffTexturePS_;
  240. }
  241. batches_[i].Draw(graphics_, vs, ps);
  242. }
  243. }
  244. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  245. {
  246. PROFILE(LoadUILayout);
  247. SharedPtr<UIElement> root;
  248. if (!file)
  249. {
  250. LOGERROR("Null UI layout XML file");
  251. return root;
  252. }
  253. LOGDEBUG("Loading UI layout " + file->GetName());
  254. XMLElement rootElem = file->GetRootElement("element");
  255. if (!rootElem)
  256. {
  257. LOGERROR("No root UI element in " + file->GetName());
  258. return root;
  259. }
  260. std::string type = rootElem.GetString("type");
  261. root = StaticCast<UIElement>(CreateObject(ShortStringHash(type)));
  262. if (!root)
  263. {
  264. LOGERROR("Could not create UI element " + type);
  265. return root;
  266. }
  267. root->SetName(rootElem.GetString("name"));
  268. std::string styleName = rootElem.HasAttribute("style") ? rootElem.GetString("style") : rootElem.GetString("type");
  269. // First set the base style from the style file if exists, then apply UI layout overrides
  270. if (styleFile)
  271. root->SetStyle(styleFile, styleName);
  272. root->SetStyle(rootElem);
  273. // Load rest of the elements recursively
  274. LoadLayout(root, rootElem, styleFile);
  275. return root;
  276. }
  277. void UI::SetClipBoardText(const std::string& text)
  278. {
  279. clipBoard_ = text;
  280. }
  281. UIElement* UI::GetElementAt(const IntVector2& position, bool activeOnly)
  282. {
  283. UIElement* result = 0;
  284. GetElementAt(result, rootElement_, position, activeOnly);
  285. return result;
  286. }
  287. UIElement* UI::GetElementAt(int x, int y, bool activeOnly)
  288. {
  289. return GetElementAt(IntVector2(x, y), activeOnly);
  290. }
  291. UIElement* UI::GetFocusElement() const
  292. {
  293. std::vector<UIElement*> allChildren = rootElement_->GetChildren(true);
  294. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  295. {
  296. if ((*i)->HasFocus())
  297. return *i;
  298. }
  299. return 0;
  300. }
  301. UIElement* UI::GetFrontElement() const
  302. {
  303. std::vector<UIElement*> rootChildren = rootElement_->GetChildren(false);
  304. int maxPriority = M_MIN_INT;
  305. UIElement* front = 0;
  306. for (unsigned i = 0; i < rootChildren.size(); ++i)
  307. {
  308. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  309. if ((!rootChildren[i]->IsActive()) || (!rootChildren[i]->IsVisible()) || (!rootChildren[i]->GetBringToBack()))
  310. continue;
  311. int priority = rootChildren[i]->GetPriority();
  312. if (priority > maxPriority)
  313. {
  314. maxPriority = priority;
  315. front = rootChildren[i];
  316. }
  317. }
  318. return front;
  319. }
  320. IntVector2 UI::GetCursorPosition()
  321. {
  322. if (!cursor_)
  323. return IntVector2::ZERO;
  324. else
  325. return cursor_->GetPosition();
  326. }
  327. void UI::Initialize()
  328. {
  329. Graphics* graphics = GetSubsystem<Graphics>();
  330. ResourceCache* cache = GetSubsystem<ResourceCache>();
  331. if ((!graphics) || (!graphics->IsInitialized()) || (!cache))
  332. return;
  333. PROFILE(InitUI);
  334. graphics_ = graphics;
  335. cache_ = cache;
  336. rootElement_ = new UIElement(context_);
  337. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  338. noTextureVS_ = cache->GetResource<VertexShader>("Shaders/SM2/Basic_VCol.vs2");
  339. diffTextureVS_ = cache->GetResource<VertexShader>("Shaders/SM2/Basic_DiffVCol.vs2");
  340. noTexturePS_ = cache->GetResource<PixelShader>("Shaders/SM2/Basic_VCol.ps2");
  341. diffTexturePS_ = cache->GetResource<PixelShader>("Shaders/SM2/Basic_DiffVCol.ps2");
  342. alphaTexturePS_ = cache->GetResource<PixelShader>("Shaders/SM2/Basic_AlphaVCol.ps2");
  343. LOGINFO("Initialized user interface");
  344. initialized_ = true;
  345. }
  346. void UI::Update(float timeStep, UIElement* element)
  347. {
  348. element->Update(timeStep);
  349. const std::vector<UIElement*> children = element->GetChildren();
  350. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  351. Update(timeStep, *i);
  352. }
  353. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  354. {
  355. // Set clipping scissor for child elements. No need to draw if zero size
  356. element->AdjustScissor(currentScissor);
  357. if ((currentScissor.left_ == currentScissor.right_) || (currentScissor.top_ == currentScissor.bottom_))
  358. return;
  359. std::vector<UIElement*> children = element->GetChildren();
  360. if (children.empty())
  361. return;
  362. std::sort(children.begin(), children.end(), CompareUIElements);
  363. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  364. // same renderstate
  365. std::vector<UIElement*>::const_iterator i = children.begin();
  366. if (element != rootElement_)
  367. {
  368. std::vector<UIElement*>::const_iterator j = i;
  369. int currentPriority = children.front()->GetPriority();
  370. while (i != children.end())
  371. {
  372. while ((j != children.end()) && ((*j)->GetPriority() == currentPriority))
  373. {
  374. if ((*j)->IsVisible())
  375. (*j)->GetBatches(batches_, quads_, currentScissor);
  376. ++j;
  377. }
  378. // Now recurse into the children
  379. while (i != j)
  380. {
  381. if ((*i)->IsVisible())
  382. GetBatches(*i, currentScissor);
  383. ++i;
  384. }
  385. if (i != children.end())
  386. currentPriority = (*i)->GetPriority();
  387. }
  388. }
  389. // On the root level draw each element and its children immediately after to avoid artifacts
  390. else
  391. {
  392. while (i != children.end())
  393. {
  394. if ((*i)->IsVisible())
  395. {
  396. (*i)->GetBatches(batches_, quads_, currentScissor);
  397. GetBatches(*i, currentScissor);
  398. }
  399. ++i;
  400. }
  401. }
  402. }
  403. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool activeOnly)
  404. {
  405. if (!current)
  406. return;
  407. // Get children from lowest priority to highest
  408. std::vector<UIElement*> children = current->GetChildren(false);
  409. std::sort(children.begin(), children.end(), CompareUIElements);
  410. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  411. {
  412. UIElement* element = *i;
  413. if ((element != cursor_.GetPtr()) && (element->IsVisible()))
  414. {
  415. if (element->IsInside(position, true))
  416. {
  417. // Store the current result, then recurse into its children. Because children
  418. // are sorted from lowest to highest priority, the topmost match should remain
  419. if ((element->IsActive()) || (!activeOnly))
  420. result = element;
  421. }
  422. if (element->IsInsideCombined(position, true))
  423. GetElementAt(result, element, position, activeOnly);
  424. }
  425. }
  426. }
  427. void UI::LoadLayout(UIElement* current, const XMLElement& elem, XMLFile* styleFile)
  428. {
  429. XMLElement childElem = elem.GetChildElement("element");
  430. while (childElem)
  431. {
  432. // Create element
  433. std::string type = childElem.GetString("type");
  434. SharedPtr<UIElement> child = StaticCast<UIElement>(CreateObject(ShortStringHash(type)));
  435. if (!child)
  436. {
  437. LOGERROR("Could not create UI element " + type);
  438. childElem = childElem.GetNextElement("element");
  439. continue;
  440. }
  441. child->SetName(childElem.GetString("name"));
  442. // Add to the hierarchy
  443. current->AddChild(child);
  444. // First set the base style from the style file if exists, then apply UI layout overrides
  445. std::string styleName = childElem.HasAttribute("style") ? childElem.GetString("style") : childElem.GetString("type");
  446. if (styleFile)
  447. child->SetStyle(styleFile, styleName);
  448. child->SetStyle(childElem);
  449. // Load the children recursively
  450. LoadLayout(child, childElem, styleFile);
  451. childElem = childElem.GetNextElement("element");
  452. }
  453. }
  454. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  455. {
  456. using namespace ScreenMode;
  457. if (!initialized_)
  458. Initialize();
  459. else
  460. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  461. }
  462. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  463. {
  464. using namespace MouseMove;
  465. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  466. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  467. if (cursor_)
  468. {
  469. const IntVector2& rootSize = rootElement_->GetSize();
  470. if (eventData[P_CLIPCURSOR].GetBool())
  471. {
  472. // When in confined cursor mode, move cursor only when visible
  473. if (cursor_->IsVisible())
  474. {
  475. IntVector2 pos = cursor_->GetPosition();
  476. pos.x_ += eventData[P_DX].GetInt();
  477. pos.y_ += eventData[P_DY].GetInt();
  478. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  479. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  480. cursor_->SetPosition(pos);
  481. }
  482. }
  483. else
  484. {
  485. // When in non-confined mode, move cursor always to ensure accurate position
  486. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  487. bool inside = (pos.x_ >= 0) && (pos.x_ < rootSize.x_) && (pos.y_ >= 0) && (pos.y_ < rootSize.y_);
  488. // Hide by moving completely outside if outside
  489. // (do not use SetVisible(), so that actual visibility remains under application control)
  490. if (pos.x_ < 0)
  491. pos.x_ = -cursor_->GetWidth() * 2;
  492. if (pos.x_ >= rootSize.x_)
  493. pos.x_ = rootSize.x_ + cursor_->GetWidth() * 2;
  494. if (pos.y_ < 0)
  495. pos.y_ = -cursor_->GetHeight() * 2;
  496. if (pos.y_ >= rootSize.y_)
  497. pos.y_ = rootSize.y_ + cursor_->GetHeight() * 2;
  498. cursor_->SetPosition(pos);
  499. // Do not drag when outside
  500. if (!inside)
  501. return;
  502. }
  503. if ((dragElement_) && (mouseButtons_))
  504. {
  505. IntVector2 pos = cursor_->GetPosition();
  506. if ((dragElement_->IsActive()) && (dragElement_->IsVisible()))
  507. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  508. else
  509. {
  510. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  511. dragElement_.Reset();
  512. }
  513. }
  514. }
  515. }
  516. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  517. {
  518. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  519. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  520. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  521. if ((cursor_) && (cursor_->IsVisible()))
  522. {
  523. IntVector2 pos = cursor_->GetPosition();
  524. WeakPtr<UIElement> element(GetElementAt(pos));
  525. if (element)
  526. {
  527. // Handle focusing & bringing to front
  528. if (button == MOUSEB_LEFT)
  529. {
  530. SetFocusElement(element);
  531. element->BringToFront();
  532. }
  533. // Handle click
  534. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  535. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  536. if ((element) && (!dragElement_) && (mouseButtons_ == MOUSEB_LEFT))
  537. {
  538. dragElement_ = element;
  539. element->OnDragStart(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  540. }
  541. }
  542. else
  543. {
  544. // If clicked over no element, or a disabled element, try to lose focus
  545. defocusElement_ = GetFocusElement();
  546. }
  547. using namespace UIMouseClick;
  548. VariantMap eventData;
  549. eventData[UIMouseClick::P_ELEMENT] = (void*)element.GetPtr();
  550. eventData[UIMouseClick::P_X] = pos.x_;
  551. eventData[UIMouseClick::P_Y] = pos.y_;
  552. eventData[UIMouseClick::P_BUTTON] = button;
  553. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  554. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  555. SendEvent(E_UIMOUSECLICK, eventData);
  556. }
  557. }
  558. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  559. {
  560. using namespace MouseButtonUp;
  561. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  562. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  563. if ((cursor_) && ((cursor_->IsVisible()) || (dragElement_)))
  564. {
  565. IntVector2 pos = cursor_->GetPosition();
  566. if ((dragElement_) && (!mouseButtons_))
  567. {
  568. if ((dragElement_->IsActive()) && (dragElement_->IsVisible()))
  569. {
  570. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  571. // Drag and drop finish
  572. bool dragSource = (dragElement_) && ((dragElement_->GetDragDropMode() & DD_SOURCE) != 0);
  573. if (dragSource)
  574. {
  575. WeakPtr<UIElement> target(GetElementAt(pos));
  576. bool dragTarget = (target) && ((target->GetDragDropMode() & DD_TARGET) != 0);
  577. bool dragDropFinish = (dragSource) && (dragTarget) && (target != dragElement_);
  578. if (dragDropFinish)
  579. {
  580. bool accept = target->OnDragDropFinish(dragElement_);
  581. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  582. if ((accept) && (dragElement_) && (target))
  583. {
  584. using namespace DragDropFinish;
  585. VariantMap eventData;
  586. eventData[P_SOURCE] = (void*)dragElement_.GetPtr();
  587. eventData[P_TARGET] = (void*)target.GetPtr();
  588. eventData[P_ACCEPT] = accept;
  589. SendEvent(E_DRAGDROPFINISH, eventData);
  590. }
  591. }
  592. }
  593. }
  594. dragElement_.Reset();
  595. }
  596. }
  597. }
  598. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  599. {
  600. using namespace MouseWheel;
  601. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  602. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  603. int delta = eventData[P_WHEEL].GetInt();
  604. UIElement* element = GetFocusElement();
  605. if (element)
  606. element->OnWheel(delta, mouseButtons_, qualifiers_);
  607. }
  608. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  609. {
  610. using namespace KeyDown;
  611. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  612. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  613. int key = eventData[P_KEY].GetInt();
  614. UIElement* element = GetFocusElement();
  615. if (element)
  616. {
  617. // Switch focus between focusable elements in the same top level window
  618. if (key == KEY_TAB)
  619. {
  620. UIElement* topLevel = element->GetParent();
  621. while ((topLevel) && (topLevel->GetParent() != rootElement_))
  622. topLevel = topLevel->GetParent();
  623. if (topLevel)
  624. {
  625. std::vector<UIElement*> children = topLevel->GetChildren(true);
  626. for (std::vector<UIElement*>::iterator i = children.begin(); i != children.end();)
  627. {
  628. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  629. i = children.erase(i);
  630. else
  631. ++i;
  632. }
  633. for (unsigned i = 0; i < children.size(); ++i)
  634. {
  635. if (children[i] == element)
  636. {
  637. UIElement* next = children[(i + 1) % children.size()];
  638. SetFocusElement(next);
  639. return;
  640. }
  641. }
  642. }
  643. }
  644. // Defocus the element
  645. else if ((key == KEY_ESC) && (element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE))
  646. defocusElement_ = element;
  647. // If none of the special keys, pass the key to the focused element
  648. else
  649. element->OnKey(key, mouseButtons_, qualifiers_);
  650. }
  651. }
  652. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  653. {
  654. using namespace Char;
  655. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  656. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  657. UIElement* element = GetFocusElement();
  658. if (element)
  659. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  660. }
  661. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  662. {
  663. if (initialized_)
  664. {
  665. using namespace PostUpdate;
  666. Update(eventData[P_TIMESTEP].GetFloat());
  667. }
  668. }
  669. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  670. {
  671. if (initialized_)
  672. RenderUpdate();
  673. }
  674. void RegisterUILibrary(Context* context)
  675. {
  676. Font::RegisterObject(context);
  677. UIElement::RegisterObject(context);
  678. BorderImage::RegisterObject(context);
  679. Button::RegisterObject(context);
  680. CheckBox::RegisterObject(context);
  681. Cursor::RegisterObject(context);
  682. Text::RegisterObject(context);
  683. Window::RegisterObject(context);
  684. LineEdit::RegisterObject(context);
  685. Slider::RegisterObject(context);
  686. ScrollBar::RegisterObject(context);
  687. ScrollView::RegisterObject(context);
  688. ListView::RegisterObject(context);
  689. Menu::RegisterObject(context);
  690. DropDownList::RegisterObject(context);
  691. FileSelector::RegisterObject(context);
  692. }