Console.cpp 19 KB

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