1
0

LocalConsole.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.Reflection;
  31. using System.Text;
  32. using System.Text.RegularExpressions;
  33. using System.Threading;
  34. using System.IO;
  35. using Nini.Config;
  36. using log4net;
  37. namespace OpenSim.Framework.Console
  38. {
  39. /// <summary>
  40. /// A console that uses cursor control and color
  41. /// </summary>
  42. public class LocalConsole : CommandConsole
  43. {
  44. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  45. private string m_historyPath;
  46. private bool m_historyEnable;
  47. // private readonly object m_syncRoot = new object();
  48. private const string LOGLEVEL_NONE = "(none)";
  49. // Used to extract categories for colourization.
  50. private Regex m_categoryRegex
  51. = new Regex(
  52. @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)", RegexOptions.Singleline | RegexOptions.Compiled);
  53. private int m_cursorYPosition = -1;
  54. private int m_cursorXPosition = 0;
  55. private StringBuilder m_commandLine = new StringBuilder();
  56. private bool m_echo = true;
  57. private List<string> m_history = new List<string>();
  58. private static readonly ConsoleColor[] Colors = {
  59. // the dark colors don't seem to be visible on some black background terminals like putty :(
  60. //ConsoleColor.DarkBlue,
  61. //ConsoleColor.DarkGreen,
  62. //ConsoleColor.DarkCyan,
  63. //ConsoleColor.DarkMagenta,
  64. //ConsoleColor.DarkYellow,
  65. ConsoleColor.Gray,
  66. //ConsoleColor.DarkGray,
  67. ConsoleColor.Blue,
  68. ConsoleColor.Green,
  69. ConsoleColor.Cyan,
  70. ConsoleColor.Magenta,
  71. ConsoleColor.Yellow
  72. };
  73. private static ConsoleColor DeriveColor(string input)
  74. {
  75. // it is important to do Abs, hash values can be negative
  76. return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
  77. }
  78. public LocalConsole(string defaultPrompt, IConfig startupConfig = null) : base(defaultPrompt)
  79. {
  80. if (startupConfig == null) return;
  81. m_historyEnable = startupConfig.GetBoolean("ConsoleHistoryFileEnabled", false);
  82. if (!m_historyEnable)
  83. {
  84. m_log.Info("[LOCAL CONSOLE]: Persistent command line history from file is Disabled");
  85. return;
  86. }
  87. string m_historyFile = startupConfig.GetString("ConsoleHistoryFile", "OpenSimConsoleHistory.txt");
  88. int m_historySize = startupConfig.GetInt("ConsoleHistoryFileLines", 100);
  89. m_historyPath = Path.GetFullPath(Path.Combine(Util.configDir(), m_historyFile));
  90. m_log.InfoFormat("[LOCAL CONSOLE]: Persistent command line history is Enabled, up to {0} lines from file {1}", m_historySize, m_historyPath);
  91. if (File.Exists(m_historyPath))
  92. {
  93. using (StreamReader history_file = new StreamReader(m_historyPath))
  94. {
  95. string line;
  96. while ((line = history_file.ReadLine()) != null)
  97. {
  98. m_history.Add(line);
  99. }
  100. }
  101. if (m_history.Count > m_historySize)
  102. {
  103. while (m_history.Count > m_historySize)
  104. m_history.RemoveAt(0);
  105. using (StreamWriter history_file = new StreamWriter(m_historyPath))
  106. {
  107. foreach (string line in m_history)
  108. {
  109. history_file.WriteLine(line);
  110. }
  111. }
  112. }
  113. m_log.InfoFormat("[LOCAL CONSOLE]: Read {0} lines of command line history from file {1}", m_history.Count, m_historyPath);
  114. }
  115. else
  116. {
  117. m_log.InfoFormat("[LOCAL CONSOLE]: Creating new empty command line history file {0}", m_historyPath);
  118. File.Create(m_historyPath).Dispose();
  119. }
  120. }
  121. private void AddToHistory(string text)
  122. {
  123. while (m_history.Count >= 100)
  124. m_history.RemoveAt(0);
  125. m_history.Add(text);
  126. if (m_historyEnable)
  127. {
  128. File.AppendAllText(m_historyPath, text + Environment.NewLine);
  129. }
  130. }
  131. /// <summary>
  132. /// Set the cursor row.
  133. /// </summary>
  134. ///
  135. /// <param name="top">
  136. /// Row to set. If this is below 0, then the row is set to 0. If it is equal to the buffer height or greater
  137. /// then it is set to one less than the height.
  138. /// </param>
  139. /// <returns>
  140. /// The new cursor row.
  141. /// </returns>
  142. private int SetCursorTop(int top)
  143. {
  144. // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
  145. // to set a cursor row position with a currently invalid column, mono will throw an exception.
  146. // Therefore, we need to make sure that the column position is valid first.
  147. int left = System.Console.CursorLeft;
  148. if (left < 0)
  149. {
  150. System.Console.CursorLeft = 0;
  151. }
  152. else
  153. {
  154. int bufferWidth = System.Console.BufferWidth;
  155. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  156. if (bufferWidth > 0 && left >= bufferWidth)
  157. System.Console.CursorLeft = bufferWidth - 1;
  158. }
  159. if (top < 0)
  160. {
  161. top = 0;
  162. }
  163. else
  164. {
  165. int bufferHeight = System.Console.BufferHeight;
  166. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  167. if (bufferHeight > 0 && top >= bufferHeight)
  168. top = bufferHeight - 1;
  169. }
  170. System.Console.CursorTop = top;
  171. return top;
  172. }
  173. /// <summary>
  174. /// Set the cursor column.
  175. /// </summary>
  176. ///
  177. /// <param name="left">
  178. /// Column to set. If this is below 0, then the column is set to 0. If it is equal to the buffer width or greater
  179. /// then it is set to one less than the width.
  180. /// </param>
  181. /// <returns>
  182. /// The new cursor column.
  183. /// </returns>
  184. private int SetCursorLeft(int left)
  185. {
  186. // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
  187. // to set a cursor column position with a currently invalid row, mono will throw an exception.
  188. // Therefore, we need to make sure that the row position is valid first.
  189. int top = System.Console.CursorTop;
  190. if (top < 0)
  191. {
  192. System.Console.CursorTop = 0;
  193. }
  194. else
  195. {
  196. int bufferHeight = System.Console.BufferHeight;
  197. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  198. if (bufferHeight > 0 && top >= bufferHeight)
  199. System.Console.CursorTop = bufferHeight - 1;
  200. }
  201. if (left < 0)
  202. {
  203. left = 0;
  204. }
  205. else
  206. {
  207. int bufferWidth = System.Console.BufferWidth;
  208. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  209. if (bufferWidth > 0 && left >= bufferWidth)
  210. left = bufferWidth - 1;
  211. }
  212. System.Console.CursorLeft = left;
  213. return left;
  214. }
  215. private void Show()
  216. {
  217. lock (m_commandLine)
  218. {
  219. if (m_cursorYPosition == -1 || System.Console.BufferWidth == 0)
  220. return;
  221. int xc = prompt.Length + m_cursorXPosition;
  222. int new_x = xc % System.Console.BufferWidth;
  223. int new_y = m_cursorYPosition + xc / System.Console.BufferWidth;
  224. int end_y = m_cursorYPosition + (m_commandLine.Length + prompt.Length) / System.Console.BufferWidth;
  225. if (end_y >= System.Console.BufferHeight) // wrap
  226. {
  227. m_cursorYPosition--;
  228. new_y--;
  229. SetCursorLeft(0);
  230. SetCursorTop(System.Console.BufferHeight - 1);
  231. System.Console.WriteLine(" ");
  232. }
  233. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  234. SetCursorLeft(0);
  235. if (m_echo)
  236. System.Console.Write("{0}{1}", prompt, m_commandLine);
  237. else
  238. System.Console.Write("{0}", prompt);
  239. SetCursorTop(new_y);
  240. SetCursorLeft(new_x);
  241. }
  242. }
  243. public override void LockOutput()
  244. {
  245. Monitor.Enter(m_commandLine);
  246. try
  247. {
  248. if (m_cursorYPosition != -1)
  249. {
  250. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  251. System.Console.CursorLeft = 0;
  252. int count = m_commandLine.Length + prompt.Length;
  253. while (count-- > 0)
  254. System.Console.Write(" ");
  255. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  256. SetCursorLeft(0);
  257. }
  258. }
  259. catch (Exception)
  260. {
  261. }
  262. }
  263. public override void UnlockOutput()
  264. {
  265. if (m_cursorYPosition != -1)
  266. {
  267. m_cursorYPosition = System.Console.CursorTop;
  268. Show();
  269. }
  270. Monitor.Exit(m_commandLine);
  271. }
  272. private void WriteColorText(ConsoleColor color, string sender)
  273. {
  274. try
  275. {
  276. lock (this)
  277. {
  278. try
  279. {
  280. System.Console.ForegroundColor = color;
  281. System.Console.Write(sender);
  282. System.Console.ResetColor();
  283. }
  284. catch (ArgumentNullException)
  285. {
  286. // Some older systems dont support coloured text.
  287. System.Console.WriteLine(sender);
  288. }
  289. }
  290. }
  291. catch (ObjectDisposedException)
  292. {
  293. }
  294. }
  295. private void WriteLocalText(string text, string level)
  296. {
  297. string outText = text;
  298. if (level != LOGLEVEL_NONE)
  299. {
  300. MatchCollection matches = m_categoryRegex.Matches(text);
  301. if (matches.Count == 1)
  302. {
  303. outText = matches[0].Groups["End"].Value;
  304. System.Console.Write(matches[0].Groups["Front"].Value);
  305. System.Console.Write("[");
  306. WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
  307. matches[0].Groups["Category"].Value);
  308. System.Console.Write("]:");
  309. }
  310. else
  311. {
  312. outText = outText.Trim();
  313. }
  314. }
  315. if (level == "error")
  316. WriteColorText(ConsoleColor.Red, outText);
  317. else if (level == "warn")
  318. WriteColorText(ConsoleColor.Yellow, outText);
  319. else
  320. System.Console.Write(outText);
  321. System.Console.WriteLine();
  322. }
  323. public override void Output(string text)
  324. {
  325. Output(text, LOGLEVEL_NONE);
  326. }
  327. public override void Output(string text, string level)
  328. {
  329. FireOnOutput(text);
  330. lock (m_commandLine)
  331. {
  332. if (m_cursorYPosition == -1)
  333. {
  334. WriteLocalText(text, level);
  335. return;
  336. }
  337. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  338. SetCursorLeft(0);
  339. int count = m_commandLine.Length + prompt.Length;
  340. while (count-- > 0)
  341. System.Console.Write(" ");
  342. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  343. SetCursorLeft(0);
  344. WriteLocalText(text, level);
  345. m_cursorYPosition = System.Console.CursorTop;
  346. Show();
  347. }
  348. }
  349. private bool ContextHelp()
  350. {
  351. string[] words = Parser.Parse(m_commandLine.ToString());
  352. bool trailingSpace = m_commandLine.ToString().EndsWith(" ");
  353. // Allow ? through while typing a URI
  354. //
  355. if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
  356. return false;
  357. string[] opts = Commands.FindNextOption(words, trailingSpace);
  358. if (opts[0].StartsWith("Command help:"))
  359. Output(opts[0]);
  360. else
  361. Output(String.Format("Options: {0}", String.Join(" ", opts)));
  362. return true;
  363. }
  364. public override string ReadLine(string p, bool isCommand, bool e)
  365. {
  366. m_cursorXPosition = 0;
  367. prompt = p;
  368. m_echo = e;
  369. int historyLine = m_history.Count;
  370. SetCursorLeft(0); // Needed for mono
  371. System.Console.Write(" "); // Needed for mono
  372. lock (m_commandLine)
  373. {
  374. m_cursorYPosition = System.Console.CursorTop;
  375. m_commandLine.Remove(0, m_commandLine.Length);
  376. }
  377. while (true)
  378. {
  379. Show();
  380. ConsoleKeyInfo key = System.Console.ReadKey(true);
  381. char enteredChar = key.KeyChar;
  382. if (!Char.IsControl(enteredChar))
  383. {
  384. if (m_cursorXPosition >= 318)
  385. continue;
  386. if (enteredChar == '?' && isCommand)
  387. {
  388. if (ContextHelp())
  389. continue;
  390. }
  391. m_commandLine.Insert(m_cursorXPosition, enteredChar);
  392. m_cursorXPosition++;
  393. }
  394. else
  395. {
  396. switch (key.Key)
  397. {
  398. case ConsoleKey.Backspace:
  399. if (m_cursorXPosition == 0)
  400. break;
  401. m_commandLine.Remove(m_cursorXPosition-1, 1);
  402. m_cursorXPosition--;
  403. SetCursorLeft(0);
  404. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  405. if (m_echo)
  406. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  407. else
  408. System.Console.Write("{0}", prompt);
  409. break;
  410. case ConsoleKey.Delete:
  411. if (m_cursorXPosition == m_commandLine.Length)
  412. break;
  413. m_commandLine.Remove(m_cursorXPosition, 1);
  414. SetCursorLeft(0);
  415. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  416. if (m_echo)
  417. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  418. else
  419. System.Console.Write("{0}", prompt);
  420. break;
  421. case ConsoleKey.End:
  422. m_cursorXPosition = m_commandLine.Length;
  423. break;
  424. case ConsoleKey.Home:
  425. m_cursorXPosition = 0;
  426. break;
  427. case ConsoleKey.UpArrow:
  428. if (historyLine < 1)
  429. break;
  430. historyLine--;
  431. LockOutput();
  432. m_commandLine.Remove(0, m_commandLine.Length);
  433. m_commandLine.Append(m_history[historyLine]);
  434. m_cursorXPosition = m_commandLine.Length;
  435. UnlockOutput();
  436. break;
  437. case ConsoleKey.DownArrow:
  438. if (historyLine >= m_history.Count)
  439. break;
  440. historyLine++;
  441. LockOutput();
  442. if (historyLine == m_history.Count)
  443. {
  444. m_commandLine.Remove(0, m_commandLine.Length);
  445. }
  446. else
  447. {
  448. m_commandLine.Remove(0, m_commandLine.Length);
  449. m_commandLine.Append(m_history[historyLine]);
  450. }
  451. m_cursorXPosition = m_commandLine.Length;
  452. UnlockOutput();
  453. break;
  454. case ConsoleKey.LeftArrow:
  455. if (m_cursorXPosition > 0)
  456. m_cursorXPosition--;
  457. break;
  458. case ConsoleKey.RightArrow:
  459. if (m_cursorXPosition < m_commandLine.Length)
  460. m_cursorXPosition++;
  461. break;
  462. case ConsoleKey.Enter:
  463. SetCursorLeft(0);
  464. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  465. System.Console.WriteLine();
  466. //Show();
  467. lock (m_commandLine)
  468. {
  469. m_cursorYPosition = -1;
  470. }
  471. string commandLine = m_commandLine.ToString();
  472. if (isCommand)
  473. {
  474. string[] cmd = Commands.Resolve(Parser.Parse(commandLine));
  475. if (cmd.Length != 0)
  476. {
  477. int index;
  478. for (index=0 ; index < cmd.Length ; index++)
  479. {
  480. if (cmd[index].Contains(" "))
  481. cmd[index] = "\"" + cmd[index] + "\"";
  482. }
  483. AddToHistory(String.Join(" ", cmd));
  484. return String.Empty;
  485. }
  486. }
  487. // If we're not echoing to screen (e.g. a password) then we probably don't want it in history
  488. if (m_echo && commandLine != "")
  489. AddToHistory(commandLine);
  490. return commandLine;
  491. default:
  492. break;
  493. }
  494. }
  495. }
  496. }
  497. }
  498. }