Console.cpp 19 KB

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