UI.cpp 27 KB

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