Console.cpp 14 KB

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