UI.cpp 27 KB

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