Console.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. //
  2. // Copyright (c) 2008-2016 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 "../Engine/Console.h"
  26. #include "../Engine/EngineEvents.h"
  27. #include "../Graphics/Graphics.h"
  28. #include "../Input/Input.h"
  29. #include "../IO/IOEvents.h"
  30. #include "../IO/Log.h"
  31. #include "../Resource/ResourceCache.h"
  32. #include "../UI/DropDownList.h"
  33. #include "../UI/Font.h"
  34. #include "../UI/LineEdit.h"
  35. #include "../UI/ListView.h"
  36. #include "../UI/ScrollBar.h"
  37. #include "../UI/Text.h"
  38. #include "../UI/UI.h"
  39. #include "../UI/UIEvents.h"
  40. #include "../DebugNew.h"
  41. namespace Urho3D
  42. {
  43. static const int DEFAULT_CONSOLE_ROWS = 16;
  44. static const int DEFAULT_HISTORY_SIZE = 16;
  45. Console::Console(Context* context) :
  46. Object(context),
  47. autoVisibleOnError_(false),
  48. historyRows_(DEFAULT_HISTORY_SIZE),
  49. historyPosition_(0),
  50. printing_(false)
  51. {
  52. UI* ui = GetSubsystem<UI>();
  53. UIElement* uiRoot = ui->GetRoot();
  54. // By default prevent the automatic showing of the screen keyboard
  55. focusOnShow_ = !ui->GetUseScreenKeyboard();
  56. background_ = uiRoot->CreateChild<BorderImage>();
  57. background_->SetBringToBack(false);
  58. background_->SetClipChildren(true);
  59. background_->SetEnabled(true);
  60. background_->SetVisible(false); // Hide by default
  61. background_->SetPriority(200); // Show on top of the debug HUD
  62. background_->SetBringToBack(false);
  63. background_->SetLayout(LM_VERTICAL);
  64. rowContainer_ = background_->CreateChild<ListView>();
  65. rowContainer_->SetHighlightMode(HM_ALWAYS);
  66. rowContainer_->SetMultiselect(true);
  67. commandLine_ = background_->CreateChild<UIElement>();
  68. commandLine_->SetLayoutMode(LM_HORIZONTAL);
  69. commandLine_->SetLayoutSpacing(1);
  70. interpreters_ = commandLine_->CreateChild<DropDownList>();
  71. lineEdit_ = commandLine_->CreateChild<LineEdit>();
  72. lineEdit_->SetFocusMode(FM_FOCUSABLE); // Do not allow defocus with ESC
  73. closeButton_ = uiRoot->CreateChild<Button>();
  74. closeButton_->SetVisible(false);
  75. closeButton_->SetPriority(background_->GetPriority() + 1); // Show on top of console's background
  76. closeButton_->SetBringToBack(false);
  77. SetNumRows(DEFAULT_CONSOLE_ROWS);
  78. SubscribeToEvent(interpreters_, E_ITEMSELECTED, URHO3D_HANDLER(Console, HandleInterpreterSelected));
  79. SubscribeToEvent(lineEdit_, E_TEXTFINISHED, URHO3D_HANDLER(Console, HandleTextFinished));
  80. SubscribeToEvent(lineEdit_, E_UNHANDLEDKEY, URHO3D_HANDLER(Console, HandleLineEditKey));
  81. SubscribeToEvent(closeButton_, E_RELEASED, URHO3D_HANDLER(Console, HandleCloseButtonPressed));
  82. SubscribeToEvent(uiRoot, E_RESIZED, URHO3D_HANDLER(Console, HandleRootElementResized));
  83. SubscribeToEvent(E_LOGMESSAGE, URHO3D_HANDLER(Console, HandleLogMessage));
  84. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(Console, HandlePostUpdate));
  85. }
  86. Console::~Console()
  87. {
  88. background_->Remove();
  89. closeButton_->Remove();
  90. }
  91. void Console::SetDefaultStyle(XMLFile* style)
  92. {
  93. if (!style)
  94. return;
  95. background_->SetDefaultStyle(style);
  96. background_->SetStyle("ConsoleBackground");
  97. rowContainer_->SetStyleAuto();
  98. for (unsigned i = 0; i < rowContainer_->GetNumItems(); ++i)
  99. rowContainer_->GetItem(i)->SetStyle("ConsoleText");
  100. interpreters_->SetStyleAuto();
  101. for (unsigned i = 0; i < interpreters_->GetNumItems(); ++i)
  102. interpreters_->GetItem(i)->SetStyle("ConsoleText");
  103. lineEdit_->SetStyle("ConsoleLineEdit");
  104. closeButton_->SetDefaultStyle(style);
  105. closeButton_->SetStyle("CloseButton");
  106. UpdateElements();
  107. }
  108. void Console::SetVisible(bool enable)
  109. {
  110. Input* input = GetSubsystem<Input>();
  111. UI* ui = GetSubsystem<UI>();
  112. Cursor* cursor = ui->GetCursor();
  113. background_->SetVisible(enable);
  114. closeButton_->SetVisible(enable);
  115. if (enable)
  116. {
  117. // Check if we have receivers for E_CONSOLECOMMAND every time here in case the handler is being added later dynamically
  118. bool hasInterpreter = PopulateInterpreter();
  119. commandLine_->SetVisible(hasInterpreter);
  120. if (hasInterpreter && focusOnShow_)
  121. ui->SetFocusElement(lineEdit_);
  122. // Ensure the background has no empty space when shown without the lineedit
  123. background_->SetHeight(background_->GetMinHeight());
  124. if (!cursor)
  125. {
  126. // Show OS mouse
  127. input->SetMouseMode(MM_FREE, true);
  128. input->SetMouseVisible(true, true);
  129. }
  130. input->SetMouseGrabbed(false, true);
  131. }
  132. else
  133. {
  134. rowContainer_->SetFocus(false);
  135. interpreters_->SetFocus(false);
  136. lineEdit_->SetFocus(false);
  137. if (!cursor)
  138. {
  139. // Restore OS mouse visibility
  140. input->ResetMouseMode();
  141. input->ResetMouseVisible();
  142. }
  143. input->ResetMouseGrabbed();
  144. }
  145. }
  146. void Console::Toggle()
  147. {
  148. SetVisible(!IsVisible());
  149. }
  150. void Console::SetNumBufferedRows(unsigned rows)
  151. {
  152. if (rows < displayedRows_)
  153. return;
  154. rowContainer_->DisableLayoutUpdate();
  155. int delta = rowContainer_->GetNumItems() - rows;
  156. if (delta > 0)
  157. {
  158. // We have more, remove oldest rows first
  159. for (int i = 0; i < delta; ++i)
  160. rowContainer_->RemoveItem((unsigned)0);
  161. }
  162. else
  163. {
  164. // We have less, add more rows at the top
  165. for (int i = 0; i > delta; --i)
  166. {
  167. Text* text = new Text(context_);
  168. // If style is already set, apply here to ensure proper height of the console when
  169. // amount of rows is changed
  170. if (background_->GetDefaultStyle())
  171. text->SetStyle("ConsoleText");
  172. rowContainer_->InsertItem(0, text);
  173. }
  174. }
  175. rowContainer_->EnsureItemVisibility(rowContainer_->GetItem(rowContainer_->GetNumItems() - 1));
  176. rowContainer_->EnableLayoutUpdate();
  177. rowContainer_->UpdateLayout();
  178. UpdateElements();
  179. }
  180. void Console::SetNumRows(unsigned rows)
  181. {
  182. if (!rows)
  183. return;
  184. displayedRows_ = rows;
  185. if (GetNumBufferedRows() < rows)
  186. SetNumBufferedRows(rows);
  187. UpdateElements();
  188. }
  189. void Console::SetNumHistoryRows(unsigned rows)
  190. {
  191. historyRows_ = rows;
  192. if (history_.Size() > rows)
  193. history_.Resize(rows);
  194. if (historyPosition_ > rows)
  195. historyPosition_ = rows;
  196. }
  197. void Console::SetFocusOnShow(bool enable)
  198. {
  199. focusOnShow_ = enable;
  200. }
  201. void Console::UpdateElements()
  202. {
  203. int width = GetSubsystem<UI>()->GetRoot()->GetWidth();
  204. const IntRect& border = background_->GetLayoutBorder();
  205. const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
  206. rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
  207. rowContainer_->SetFixedHeight(
  208. displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
  209. (rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
  210. background_->SetFixedWidth(width);
  211. background_->SetHeight(background_->GetMinHeight());
  212. }
  213. XMLFile* Console::GetDefaultStyle() const
  214. {
  215. return background_->GetDefaultStyle(false);
  216. }
  217. bool Console::IsVisible() const
  218. {
  219. return background_ && background_->IsVisible();
  220. }
  221. unsigned Console::GetNumBufferedRows() const
  222. {
  223. return rowContainer_->GetNumItems();
  224. }
  225. void Console::CopySelectedRows() const
  226. {
  227. rowContainer_->CopySelectedItemsToClipboard();
  228. }
  229. const String& Console::GetHistoryRow(unsigned index) const
  230. {
  231. return index < history_.Size() ? history_[index] : String::EMPTY;
  232. }
  233. bool Console::PopulateInterpreter()
  234. {
  235. interpreters_->RemoveAllItems();
  236. HashSet<Object*>* receivers = context_->GetEventReceivers(E_CONSOLECOMMAND);
  237. if (!receivers || receivers->Empty())
  238. return false;
  239. Vector<String> names;
  240. for (HashSet<Object*>::ConstIterator iter = receivers->Begin(); iter != receivers->End(); ++iter)
  241. names.Push((*iter)->GetTypeName());
  242. Sort(names.Begin(), names.End());
  243. unsigned selection = M_MAX_UNSIGNED;
  244. for (unsigned i = 0; i < names.Size(); ++i)
  245. {
  246. const String& name = names[i];
  247. if (name == commandInterpreter_)
  248. selection = i;
  249. Text* text = new Text(context_);
  250. text->SetStyle("ConsoleText");
  251. text->SetText(name);
  252. interpreters_->AddItem(text);
  253. }
  254. const IntRect& border = interpreters_->GetPopup()->GetLayoutBorder();
  255. interpreters_->SetMaxWidth(interpreters_->GetListView()->GetContentElement()->GetWidth() + border.left_ + border.right_);
  256. bool enabled = interpreters_->GetNumItems() > 1;
  257. interpreters_->SetEnabled(enabled);
  258. interpreters_->SetFocusMode(enabled ? FM_FOCUSABLE_DEFOCUSABLE : FM_NOTFOCUSABLE);
  259. if (selection == M_MAX_UNSIGNED)
  260. {
  261. selection = 0;
  262. commandInterpreter_ = names[selection];
  263. }
  264. interpreters_->SetSelection(selection);
  265. return true;
  266. }
  267. void Console::HandleInterpreterSelected(StringHash eventType, VariantMap& eventData)
  268. {
  269. commandInterpreter_ = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
  270. lineEdit_->SetFocus(true);
  271. }
  272. void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData)
  273. {
  274. using namespace TextFinished;
  275. String line = lineEdit_->GetText();
  276. if (!line.Empty())
  277. {
  278. // Send the command as an event for script subsystem
  279. using namespace ConsoleCommand;
  280. #if URHO3D_CXX11
  281. SendEvent(E_CONSOLECOMMAND, P_COMMAND, line, P_ID, static_cast<Text*>(interpreters_->GetSelectedItem())->GetText());
  282. #else
  283. VariantMap& newEventData = GetEventDataMap();
  284. newEventData[P_COMMAND] = line;
  285. newEventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
  286. SendEvent(E_CONSOLECOMMAND, newEventData);
  287. #endif
  288. // Store to history, then clear the lineedit
  289. history_.Push(line);
  290. if (history_.Size() > historyRows_)
  291. history_.Erase(history_.Begin());
  292. historyPosition_ = history_.Size();
  293. currentRow_.Clear();
  294. lineEdit_->SetText(currentRow_);
  295. }
  296. }
  297. void Console::HandleLineEditKey(StringHash eventType, VariantMap& eventData)
  298. {
  299. if (!historyRows_)
  300. return;
  301. using namespace UnhandledKey;
  302. bool changed = false;
  303. switch (eventData[P_KEY].GetInt())
  304. {
  305. case KEY_UP:
  306. if (historyPosition_ > 0)
  307. {
  308. if (historyPosition_ == history_.Size())
  309. currentRow_ = lineEdit_->GetText();
  310. --historyPosition_;
  311. changed = true;
  312. }
  313. break;
  314. case KEY_DOWN:
  315. if (historyPosition_ < history_.Size())
  316. {
  317. ++historyPosition_;
  318. changed = true;
  319. }
  320. break;
  321. default: break;
  322. }
  323. if (changed)
  324. {
  325. if (historyPosition_ < history_.Size())
  326. lineEdit_->SetText(history_[historyPosition_]);
  327. else
  328. lineEdit_->SetText(currentRow_);
  329. }
  330. }
  331. void Console::HandleCloseButtonPressed(StringHash eventType, VariantMap& eventData)
  332. {
  333. SetVisible(false);
  334. }
  335. void Console::HandleRootElementResized(StringHash eventType, VariantMap& eventData)
  336. {
  337. UpdateElements();
  338. }
  339. void Console::HandleLogMessage(StringHash eventType, VariantMap& eventData)
  340. {
  341. // If printing a log message causes more messages to be logged (error accessing font), disregard them
  342. if (printing_)
  343. return;
  344. using namespace LogMessage;
  345. int level = eventData[P_LEVEL].GetInt();
  346. // The message may be multi-line, so split to rows in that case
  347. Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
  348. for (unsigned i = 0; i < rows.Size(); ++i)
  349. pendingRows_.Push(MakePair(level, rows[i]));
  350. if (autoVisibleOnError_ && level == LOG_ERROR && !IsVisible())
  351. SetVisible(true);
  352. }
  353. void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  354. {
  355. // Ensure UI-elements are not detached
  356. if (!background_->GetParent())
  357. {
  358. UI* ui = GetSubsystem<UI>();
  359. UIElement* uiRoot = ui->GetRoot();
  360. uiRoot->AddChild(background_);
  361. uiRoot->AddChild(closeButton_);
  362. }
  363. if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
  364. return;
  365. printing_ = true;
  366. rowContainer_->DisableLayoutUpdate();
  367. Text* text = 0;
  368. for (unsigned i = 0; i < pendingRows_.Size(); ++i)
  369. {
  370. rowContainer_->RemoveItem((unsigned)0);
  371. text = new Text(context_);
  372. text->SetText(pendingRows_[i].second_);
  373. // Make error message highlight
  374. text->SetStyle(pendingRows_[i].first_ == LOG_ERROR ? "ConsoleHighlightedText" : "ConsoleText");
  375. rowContainer_->AddItem(text);
  376. }
  377. pendingRows_.Clear();
  378. rowContainer_->EnsureItemVisibility(text);
  379. rowContainer_->EnableLayoutUpdate();
  380. rowContainer_->UpdateLayout();
  381. UpdateElements(); // May need to readjust the height due to scrollbar visibility changes
  382. printing_ = false;
  383. }
  384. }