Console.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../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. const char* logStyles[] =
  46. {
  47. "ConsoleDebugText",
  48. "ConsoleInfoText",
  49. "ConsoleWarningText",
  50. "ConsoleErrorText",
  51. "ConsoleText"
  52. };
  53. Console::Console(Context* context) :
  54. Object(context),
  55. autoVisibleOnError_(false),
  56. historyRows_(DEFAULT_HISTORY_SIZE),
  57. historyPosition_(0),
  58. autoCompletePosition_(0),
  59. historyOrAutoCompleteChange_(false),
  60. printing_(false)
  61. {
  62. auto* ui = GetSubsystem<UI>();
  63. UIElement* uiRoot = ui->GetRoot();
  64. // By default prevent the automatic showing of the screen keyboard
  65. focusOnShow_ = !ui->GetUseScreenKeyboard();
  66. background_ = uiRoot->CreateChild<BorderImage>();
  67. background_->SetBringToBack(false);
  68. background_->SetClipChildren(true);
  69. background_->SetEnabled(true);
  70. background_->SetVisible(false); // Hide by default
  71. background_->SetPriority(200); // Show on top of the debug HUD
  72. background_->SetBringToBack(false);
  73. background_->SetLayout(LM_VERTICAL);
  74. rowContainer_ = background_->CreateChild<ListView>();
  75. rowContainer_->SetHighlightMode(HM_ALWAYS);
  76. rowContainer_->SetMultiselect(true);
  77. commandLine_ = background_->CreateChild<UIElement>();
  78. commandLine_->SetLayoutMode(LM_HORIZONTAL);
  79. commandLine_->SetLayoutSpacing(1);
  80. interpreters_ = commandLine_->CreateChild<DropDownList>();
  81. lineEdit_ = commandLine_->CreateChild<LineEdit>();
  82. lineEdit_->SetFocusMode(FM_FOCUSABLE); // Do not allow defocus with ESC
  83. closeButton_ = uiRoot->CreateChild<Button>();
  84. closeButton_->SetVisible(false);
  85. closeButton_->SetPriority(background_->GetPriority() + 1); // Show on top of console's background
  86. closeButton_->SetBringToBack(false);
  87. SetNumRows(DEFAULT_CONSOLE_ROWS);
  88. SubscribeToEvent(interpreters_, E_ITEMSELECTED, URHO3D_HANDLER(Console, HandleInterpreterSelected));
  89. SubscribeToEvent(lineEdit_, E_TEXTCHANGED, URHO3D_HANDLER(Console, HandleTextChanged));
  90. SubscribeToEvent(lineEdit_, E_TEXTFINISHED, URHO3D_HANDLER(Console, HandleTextFinished));
  91. SubscribeToEvent(lineEdit_, E_UNHANDLEDKEY, URHO3D_HANDLER(Console, HandleLineEditKey));
  92. SubscribeToEvent(closeButton_, E_RELEASED, URHO3D_HANDLER(Console, HandleCloseButtonPressed));
  93. SubscribeToEvent(uiRoot, E_RESIZED, URHO3D_HANDLER(Console, HandleRootElementResized));
  94. SubscribeToEvent(E_LOGMESSAGE, URHO3D_HANDLER(Console, HandleLogMessage));
  95. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(Console, HandlePostUpdate));
  96. }
  97. Console::~Console()
  98. {
  99. background_->Remove();
  100. closeButton_->Remove();
  101. }
  102. void Console::SetDefaultStyle(XMLFile* style)
  103. {
  104. if (!style)
  105. return;
  106. background_->SetDefaultStyle(style);
  107. background_->SetStyle("ConsoleBackground");
  108. rowContainer_->SetStyleAuto();
  109. for (unsigned i = 0; i < rowContainer_->GetNumItems(); ++i)
  110. rowContainer_->GetItem(i)->SetStyle("ConsoleText");
  111. interpreters_->SetStyleAuto();
  112. for (unsigned i = 0; i < interpreters_->GetNumItems(); ++i)
  113. interpreters_->GetItem(i)->SetStyle("ConsoleText");
  114. lineEdit_->SetStyle("ConsoleLineEdit");
  115. closeButton_->SetDefaultStyle(style);
  116. closeButton_->SetStyle("CloseButton");
  117. UpdateElements();
  118. }
  119. void Console::SetVisible(bool enable)
  120. {
  121. auto* input = GetSubsystem<Input>();
  122. auto* ui = GetSubsystem<UI>();
  123. Cursor* cursor = ui->GetCursor();
  124. background_->SetVisible(enable);
  125. closeButton_->SetVisible(enable);
  126. if (enable)
  127. {
  128. // Check if we have receivers for E_CONSOLECOMMAND every time here in case the handler is being added later dynamically
  129. bool hasInterpreter = PopulateInterpreter();
  130. commandLine_->SetVisible(hasInterpreter);
  131. if (hasInterpreter && focusOnShow_)
  132. ui->SetFocusElement(lineEdit_);
  133. // Ensure the background has no empty space when shown without the lineedit
  134. background_->SetHeight(background_->GetMinHeight());
  135. if (!cursor)
  136. {
  137. // Show OS mouse
  138. input->SetMouseMode(MM_FREE, true);
  139. input->SetMouseVisible(true, true);
  140. }
  141. input->SetMouseGrabbed(false, true);
  142. }
  143. else
  144. {
  145. rowContainer_->SetFocus(false);
  146. interpreters_->SetFocus(false);
  147. lineEdit_->SetFocus(false);
  148. if (!cursor)
  149. {
  150. // Restore OS mouse visibility
  151. input->ResetMouseMode();
  152. input->ResetMouseVisible();
  153. }
  154. input->ResetMouseGrabbed();
  155. }
  156. }
  157. void Console::Toggle()
  158. {
  159. SetVisible(!IsVisible());
  160. }
  161. void Console::SetNumBufferedRows(unsigned rows)
  162. {
  163. if (rows < displayedRows_)
  164. return;
  165. rowContainer_->DisableLayoutUpdate();
  166. int delta = rowContainer_->GetNumItems() - rows;
  167. if (delta > 0)
  168. {
  169. // We have more, remove oldest rows first
  170. for (int i = 0; i < delta; ++i)
  171. rowContainer_->RemoveItem((unsigned)0);
  172. }
  173. else
  174. {
  175. // We have less, add more rows at the top
  176. for (int i = 0; i > delta; --i)
  177. {
  178. auto* text = new Text(context_);
  179. // If style is already set, apply here to ensure proper height of the console when
  180. // amount of rows is changed
  181. if (background_->GetDefaultStyle())
  182. text->SetStyle("ConsoleText");
  183. rowContainer_->InsertItem(0, text);
  184. }
  185. }
  186. rowContainer_->EnsureItemVisibility(rowContainer_->GetItem(rowContainer_->GetNumItems() - 1));
  187. rowContainer_->EnableLayoutUpdate();
  188. rowContainer_->UpdateLayout();
  189. UpdateElements();
  190. }
  191. void Console::SetNumRows(unsigned rows)
  192. {
  193. if (!rows)
  194. return;
  195. displayedRows_ = rows;
  196. if (GetNumBufferedRows() < rows)
  197. SetNumBufferedRows(rows);
  198. UpdateElements();
  199. }
  200. void Console::SetNumHistoryRows(unsigned rows)
  201. {
  202. historyRows_ = rows;
  203. if (history_.Size() > rows)
  204. history_.Resize(rows);
  205. if (historyPosition_ > rows)
  206. historyPosition_ = rows;
  207. }
  208. void Console::SetFocusOnShow(bool enable)
  209. {
  210. focusOnShow_ = enable;
  211. }
  212. void Console::AddAutoComplete(const String& option)
  213. {
  214. // Sorted insertion
  215. Vector<String>::Iterator iter = UpperBound(autoComplete_.Begin(), autoComplete_.End(), option);
  216. if (!iter.ptr_)
  217. autoComplete_.Push(option);
  218. // Make sure it isn't a duplicate
  219. else if (iter == autoComplete_.Begin() || *(iter - 1) != option)
  220. autoComplete_.Insert(iter, option);
  221. }
  222. void Console::RemoveAutoComplete(const String& option)
  223. {
  224. // Erase and keep ordered
  225. autoComplete_.Erase(LowerBound(autoComplete_.Begin(), autoComplete_.End(), option));
  226. if (autoCompletePosition_ > autoComplete_.Size())
  227. autoCompletePosition_ = autoComplete_.Size();
  228. }
  229. void Console::UpdateElements()
  230. {
  231. int width = GetSubsystem<UI>()->GetRoot()->GetWidth();
  232. const IntRect& border = background_->GetLayoutBorder();
  233. const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
  234. rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
  235. rowContainer_->SetFixedHeight(
  236. displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
  237. (rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
  238. background_->SetFixedWidth(width);
  239. background_->SetHeight(background_->GetMinHeight());
  240. }
  241. XMLFile* Console::GetDefaultStyle() const
  242. {
  243. return background_->GetDefaultStyle(false);
  244. }
  245. bool Console::IsVisible() const
  246. {
  247. return background_ && background_->IsVisible();
  248. }
  249. unsigned Console::GetNumBufferedRows() const
  250. {
  251. return rowContainer_->GetNumItems();
  252. }
  253. void Console::CopySelectedRows() const
  254. {
  255. rowContainer_->CopySelectedItemsToClipboard();
  256. }
  257. const String& Console::GetHistoryRow(unsigned index) const
  258. {
  259. return index < history_.Size() ? history_[index] : String::EMPTY;
  260. }
  261. bool Console::PopulateInterpreter()
  262. {
  263. interpreters_->RemoveAllItems();
  264. EventReceiverGroup* group = context_->GetEventReceivers(E_CONSOLECOMMAND);
  265. if (!group || group->receivers_.Empty())
  266. return false;
  267. Vector<String> names;
  268. for (unsigned i = 0; i < group->receivers_.Size(); ++i)
  269. {
  270. Object* receiver = group->receivers_[i];
  271. if (receiver)
  272. names.Push(receiver->GetTypeName());
  273. }
  274. Sort(names.Begin(), names.End());
  275. unsigned selection = M_MAX_UNSIGNED;
  276. for (unsigned i = 0; i < names.Size(); ++i)
  277. {
  278. const String& name = names[i];
  279. if (name == commandInterpreter_)
  280. selection = i;
  281. auto* text = new Text(context_);
  282. text->SetStyle("ConsoleText");
  283. text->SetText(name);
  284. interpreters_->AddItem(text);
  285. }
  286. const IntRect& border = interpreters_->GetPopup()->GetLayoutBorder();
  287. interpreters_->SetMaxWidth(interpreters_->GetListView()->GetContentElement()->GetWidth() + border.left_ + border.right_);
  288. bool enabled = interpreters_->GetNumItems() > 1;
  289. interpreters_->SetEnabled(enabled);
  290. interpreters_->SetFocusMode(enabled ? FM_FOCUSABLE_DEFOCUSABLE : FM_NOTFOCUSABLE);
  291. if (selection == M_MAX_UNSIGNED)
  292. {
  293. selection = 0;
  294. commandInterpreter_ = names[selection];
  295. }
  296. interpreters_->SetSelection(selection);
  297. return true;
  298. }
  299. void Console::HandleInterpreterSelected(StringHash eventType, VariantMap& eventData)
  300. {
  301. commandInterpreter_ = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
  302. lineEdit_->SetFocus(true);
  303. }
  304. void Console::HandleTextChanged(StringHash eventType, VariantMap & eventData)
  305. {
  306. // Save the original line
  307. // Make sure the change isn't caused by auto complete or history
  308. if (!historyOrAutoCompleteChange_)
  309. autoCompleteLine_ = eventData[TextEntry::P_TEXT].GetString();
  310. historyOrAutoCompleteChange_ = false;
  311. }
  312. void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData)
  313. {
  314. using namespace TextFinished;
  315. String line = lineEdit_->GetText();
  316. if (!line.Empty())
  317. {
  318. // Send the command as an event for script subsystem
  319. using namespace ConsoleCommand;
  320. SendEvent(E_CONSOLECOMMAND,
  321. P_COMMAND, line,
  322. P_ID, static_cast<Text*>(interpreters_->GetSelectedItem())->GetText());
  323. // Make sure the line isn't the same as the last one
  324. if (history_.Empty() || line != history_.Back())
  325. {
  326. // Store to history, then clear the lineedit
  327. history_.Push(line);
  328. if (history_.Size() > historyRows_)
  329. history_.Erase(history_.Begin());
  330. }
  331. historyPosition_ = history_.Size(); // Reset
  332. autoCompletePosition_ = autoComplete_.Size(); // Reset
  333. currentRow_.Clear();
  334. lineEdit_->SetText(currentRow_);
  335. }
  336. }
  337. void Console::HandleLineEditKey(StringHash eventType, VariantMap& eventData)
  338. {
  339. if (!historyRows_)
  340. return;
  341. using namespace UnhandledKey;
  342. bool changed = false;
  343. switch (eventData[P_KEY].GetInt())
  344. {
  345. case KEY_UP:
  346. if (autoCompletePosition_ == 0)
  347. autoCompletePosition_ = autoComplete_.Size();
  348. if (autoCompletePosition_ < autoComplete_.Size())
  349. {
  350. // Search for auto completion that contains the contents of the line
  351. for (--autoCompletePosition_; autoCompletePosition_ != M_MAX_UNSIGNED; --autoCompletePosition_)
  352. {
  353. const String& current = autoComplete_[autoCompletePosition_];
  354. if (current.StartsWith(autoCompleteLine_))
  355. {
  356. historyOrAutoCompleteChange_ = true;
  357. lineEdit_->SetText(current);
  358. break;
  359. }
  360. }
  361. // If not found
  362. if (autoCompletePosition_ == M_MAX_UNSIGNED)
  363. {
  364. // Reset the position
  365. autoCompletePosition_ = autoComplete_.Size();
  366. // Reset history position
  367. historyPosition_ = history_.Size();
  368. }
  369. }
  370. // If no more auto complete options and history options left
  371. if (autoCompletePosition_ == autoComplete_.Size() && historyPosition_ > 0)
  372. {
  373. // If line text is not a history, save the current text value to be restored later
  374. if (historyPosition_ == history_.Size())
  375. currentRow_ = lineEdit_->GetText();
  376. // Use the previous option
  377. --historyPosition_;
  378. changed = true;
  379. }
  380. break;
  381. case KEY_DOWN:
  382. // If history options left
  383. if (historyPosition_ < history_.Size())
  384. {
  385. // Use the next option
  386. ++historyPosition_;
  387. changed = true;
  388. }
  389. else
  390. {
  391. // Loop over
  392. if (autoCompletePosition_ >= autoComplete_.Size())
  393. autoCompletePosition_ = 0;
  394. else
  395. ++autoCompletePosition_; // If not starting over, skip checking the currently found completion
  396. unsigned startPosition = autoCompletePosition_;
  397. // Search for auto completion that contains the contents of the line
  398. for (; autoCompletePosition_ < autoComplete_.Size(); ++autoCompletePosition_)
  399. {
  400. const String& current = autoComplete_[autoCompletePosition_];
  401. if (current.StartsWith(autoCompleteLine_))
  402. {
  403. historyOrAutoCompleteChange_ = true;
  404. lineEdit_->SetText(current);
  405. break;
  406. }
  407. }
  408. // Continue to search the complete range
  409. if (autoCompletePosition_ == autoComplete_.Size())
  410. {
  411. for (autoCompletePosition_ = 0; autoCompletePosition_ != startPosition; ++autoCompletePosition_)
  412. {
  413. const String& current = autoComplete_[autoCompletePosition_];
  414. if (current.StartsWith(autoCompleteLine_))
  415. {
  416. historyOrAutoCompleteChange_ = true;
  417. lineEdit_->SetText(current);
  418. break;
  419. }
  420. }
  421. }
  422. }
  423. break;
  424. default: break;
  425. }
  426. if (changed)
  427. {
  428. historyOrAutoCompleteChange_ = true;
  429. // Set text to history option
  430. if (historyPosition_ < history_.Size())
  431. lineEdit_->SetText(history_[historyPosition_]);
  432. else // restore the original line value before it was set to history values
  433. {
  434. lineEdit_->SetText(currentRow_);
  435. // Set the auto complete position according to the currentRow
  436. for (autoCompletePosition_ = 0; autoCompletePosition_ < autoComplete_.Size(); ++autoCompletePosition_)
  437. if (autoComplete_[autoCompletePosition_].StartsWith(currentRow_))
  438. break;
  439. }
  440. }
  441. }
  442. void Console::HandleCloseButtonPressed(StringHash eventType, VariantMap& eventData)
  443. {
  444. SetVisible(false);
  445. }
  446. void Console::HandleRootElementResized(StringHash eventType, VariantMap& eventData)
  447. {
  448. UpdateElements();
  449. }
  450. void Console::HandleLogMessage(StringHash eventType, VariantMap& eventData)
  451. {
  452. // If printing a log message causes more messages to be logged (error accessing font), disregard them
  453. if (printing_)
  454. return;
  455. using namespace LogMessage;
  456. int level = eventData[P_LEVEL].GetInt();
  457. // The message may be multi-line, so split to rows in that case
  458. Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
  459. for (unsigned i = 0; i < rows.Size(); ++i)
  460. pendingRows_.Push(MakePair(level, rows[i]));
  461. if (autoVisibleOnError_ && level == LOG_ERROR && !IsVisible())
  462. SetVisible(true);
  463. }
  464. void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  465. {
  466. // Ensure UI-elements are not detached
  467. if (!background_->GetParent())
  468. {
  469. auto* ui = GetSubsystem<UI>();
  470. UIElement* uiRoot = ui->GetRoot();
  471. uiRoot->AddChild(background_);
  472. uiRoot->AddChild(closeButton_);
  473. }
  474. if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
  475. return;
  476. printing_ = true;
  477. rowContainer_->DisableLayoutUpdate();
  478. Text* text = nullptr;
  479. for (unsigned i = 0; i < pendingRows_.Size(); ++i)
  480. {
  481. rowContainer_->RemoveItem((unsigned)0);
  482. text = new Text(context_);
  483. text->SetText(pendingRows_[i].second_);
  484. // Highlight console messages based on their type
  485. text->SetStyle(logStyles[pendingRows_[i].first_]);
  486. rowContainer_->AddItem(text);
  487. }
  488. pendingRows_.Clear();
  489. rowContainer_->EnsureItemVisibility(text);
  490. rowContainer_->EnableLayoutUpdate();
  491. rowContainer_->UpdateLayout();
  492. UpdateElements(); // May need to readjust the height due to scrollbar visibility changes
  493. printing_ = false;
  494. }
  495. }