LocalConsole.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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 log4net;
  35. namespace OpenSim.Framework.Console
  36. {
  37. /// <summary>
  38. /// A console that uses cursor control and color
  39. /// </summary>
  40. public class LocalConsole : CommandConsole
  41. {
  42. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. // private readonly object m_syncRoot = new object();
  44. private const string LOGLEVEL_NONE = "(none)";
  45. // Used to extract categories for colourization.
  46. private Regex m_categoryRegex
  47. = new Regex(
  48. @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)", RegexOptions.Singleline | RegexOptions.Compiled);
  49. private int m_cursorYPosition = -1;
  50. private int m_cursorXPosition = 0;
  51. private StringBuilder m_commandLine = new StringBuilder();
  52. private bool m_echo = true;
  53. private List<string> m_history = new List<string>();
  54. private static readonly ConsoleColor[] Colors = {
  55. // the dark colors don't seem to be visible on some black background terminals like putty :(
  56. //ConsoleColor.DarkBlue,
  57. //ConsoleColor.DarkGreen,
  58. //ConsoleColor.DarkCyan,
  59. //ConsoleColor.DarkMagenta,
  60. //ConsoleColor.DarkYellow,
  61. ConsoleColor.Gray,
  62. //ConsoleColor.DarkGray,
  63. ConsoleColor.Blue,
  64. ConsoleColor.Green,
  65. ConsoleColor.Cyan,
  66. ConsoleColor.Magenta,
  67. ConsoleColor.Yellow
  68. };
  69. private static ConsoleColor DeriveColor(string input)
  70. {
  71. // it is important to do Abs, hash values can be negative
  72. return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
  73. }
  74. public LocalConsole(string defaultPrompt) : base(defaultPrompt)
  75. {
  76. }
  77. private void AddToHistory(string text)
  78. {
  79. while (m_history.Count >= 100)
  80. m_history.RemoveAt(0);
  81. m_history.Add(text);
  82. }
  83. /// <summary>
  84. /// Set the cursor row.
  85. /// </summary>
  86. ///
  87. /// <param name="top">
  88. /// 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
  89. /// then it is set to one less than the height.
  90. /// </param>
  91. /// <returns>
  92. /// The new cursor row.
  93. /// </returns>
  94. private int SetCursorTop(int top)
  95. {
  96. // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
  97. // to set a cursor row position with a currently invalid column, mono will throw an exception.
  98. // Therefore, we need to make sure that the column position is valid first.
  99. int left = System.Console.CursorLeft;
  100. if (left < 0)
  101. {
  102. System.Console.CursorLeft = 0;
  103. }
  104. else
  105. {
  106. int bufferWidth = System.Console.BufferWidth;
  107. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  108. if (bufferWidth > 0 && left >= bufferWidth)
  109. System.Console.CursorLeft = bufferWidth - 1;
  110. }
  111. if (top < 0)
  112. {
  113. top = 0;
  114. }
  115. else
  116. {
  117. int bufferHeight = System.Console.BufferHeight;
  118. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  119. if (bufferHeight > 0 && top >= bufferHeight)
  120. top = bufferHeight - 1;
  121. }
  122. System.Console.CursorTop = top;
  123. return top;
  124. }
  125. /// <summary>
  126. /// Set the cursor column.
  127. /// </summary>
  128. ///
  129. /// <param name="left">
  130. /// 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
  131. /// then it is set to one less than the width.
  132. /// </param>
  133. /// <returns>
  134. /// The new cursor column.
  135. /// </returns>
  136. private int SetCursorLeft(int left)
  137. {
  138. // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
  139. // to set a cursor column position with a currently invalid row, mono will throw an exception.
  140. // Therefore, we need to make sure that the row position is valid first.
  141. int top = System.Console.CursorTop;
  142. if (top < 0)
  143. {
  144. System.Console.CursorTop = 0;
  145. }
  146. else
  147. {
  148. int bufferHeight = System.Console.BufferHeight;
  149. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  150. if (bufferHeight > 0 && top >= bufferHeight)
  151. System.Console.CursorTop = bufferHeight - 1;
  152. }
  153. if (left < 0)
  154. {
  155. left = 0;
  156. }
  157. else
  158. {
  159. int bufferWidth = System.Console.BufferWidth;
  160. // On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
  161. if (bufferWidth > 0 && left >= bufferWidth)
  162. left = bufferWidth - 1;
  163. }
  164. System.Console.CursorLeft = left;
  165. return left;
  166. }
  167. private void Show()
  168. {
  169. lock (m_commandLine)
  170. {
  171. if (m_cursorYPosition == -1 || System.Console.BufferWidth == 0)
  172. return;
  173. int xc = prompt.Length + m_cursorXPosition;
  174. int new_x = xc % System.Console.BufferWidth;
  175. int new_y = m_cursorYPosition + xc / System.Console.BufferWidth;
  176. int end_y = m_cursorYPosition + (m_commandLine.Length + prompt.Length) / System.Console.BufferWidth;
  177. if (end_y >= System.Console.BufferHeight) // wrap
  178. {
  179. m_cursorYPosition--;
  180. new_y--;
  181. SetCursorLeft(0);
  182. SetCursorTop(System.Console.BufferHeight - 1);
  183. System.Console.WriteLine(" ");
  184. }
  185. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  186. SetCursorLeft(0);
  187. if (m_echo)
  188. System.Console.Write("{0}{1}", prompt, m_commandLine);
  189. else
  190. System.Console.Write("{0}", prompt);
  191. SetCursorTop(new_y);
  192. SetCursorLeft(new_x);
  193. }
  194. }
  195. public override void LockOutput()
  196. {
  197. Monitor.Enter(m_commandLine);
  198. try
  199. {
  200. if (m_cursorYPosition != -1)
  201. {
  202. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  203. System.Console.CursorLeft = 0;
  204. int count = m_commandLine.Length + prompt.Length;
  205. while (count-- > 0)
  206. System.Console.Write(" ");
  207. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  208. SetCursorLeft(0);
  209. }
  210. }
  211. catch (Exception)
  212. {
  213. }
  214. }
  215. public override void UnlockOutput()
  216. {
  217. if (m_cursorYPosition != -1)
  218. {
  219. m_cursorYPosition = System.Console.CursorTop;
  220. Show();
  221. }
  222. Monitor.Exit(m_commandLine);
  223. }
  224. private void WriteColorText(ConsoleColor color, string sender)
  225. {
  226. try
  227. {
  228. lock (this)
  229. {
  230. try
  231. {
  232. System.Console.ForegroundColor = color;
  233. System.Console.Write(sender);
  234. System.Console.ResetColor();
  235. }
  236. catch (ArgumentNullException)
  237. {
  238. // Some older systems dont support coloured text.
  239. System.Console.WriteLine(sender);
  240. }
  241. }
  242. }
  243. catch (ObjectDisposedException)
  244. {
  245. }
  246. }
  247. private void WriteLocalText(string text, string level)
  248. {
  249. string outText = text;
  250. if (level != LOGLEVEL_NONE)
  251. {
  252. MatchCollection matches = m_categoryRegex.Matches(text);
  253. if (matches.Count == 1)
  254. {
  255. outText = matches[0].Groups["End"].Value;
  256. System.Console.Write(matches[0].Groups["Front"].Value);
  257. System.Console.Write("[");
  258. WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
  259. matches[0].Groups["Category"].Value);
  260. System.Console.Write("]:");
  261. }
  262. else
  263. {
  264. outText = outText.Trim();
  265. }
  266. }
  267. if (level == "error")
  268. WriteColorText(ConsoleColor.Red, outText);
  269. else if (level == "warn")
  270. WriteColorText(ConsoleColor.Yellow, outText);
  271. else
  272. System.Console.Write(outText);
  273. System.Console.WriteLine();
  274. }
  275. public override void Output(string text)
  276. {
  277. Output(text, LOGLEVEL_NONE);
  278. }
  279. public override void Output(string text, string level)
  280. {
  281. FireOnOutput(text);
  282. lock (m_commandLine)
  283. {
  284. if (m_cursorYPosition == -1)
  285. {
  286. WriteLocalText(text, level);
  287. return;
  288. }
  289. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  290. SetCursorLeft(0);
  291. int count = m_commandLine.Length + prompt.Length;
  292. while (count-- > 0)
  293. System.Console.Write(" ");
  294. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  295. SetCursorLeft(0);
  296. WriteLocalText(text, level);
  297. m_cursorYPosition = System.Console.CursorTop;
  298. Show();
  299. }
  300. }
  301. private bool ContextHelp()
  302. {
  303. string[] words = Parser.Parse(m_commandLine.ToString());
  304. bool trailingSpace = m_commandLine.ToString().EndsWith(" ");
  305. // Allow ? through while typing a URI
  306. //
  307. if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
  308. return false;
  309. string[] opts = Commands.FindNextOption(words, trailingSpace);
  310. if (opts[0].StartsWith("Command help:"))
  311. Output(opts[0]);
  312. else
  313. Output(String.Format("Options: {0}", String.Join(" ", opts)));
  314. return true;
  315. }
  316. public override string ReadLine(string p, bool isCommand, bool e)
  317. {
  318. m_cursorXPosition = 0;
  319. prompt = p;
  320. m_echo = e;
  321. int historyLine = m_history.Count;
  322. SetCursorLeft(0); // Needed for mono
  323. System.Console.Write(" "); // Needed for mono
  324. lock (m_commandLine)
  325. {
  326. m_cursorYPosition = System.Console.CursorTop;
  327. m_commandLine.Remove(0, m_commandLine.Length);
  328. }
  329. while (true)
  330. {
  331. Show();
  332. ConsoleKeyInfo key = System.Console.ReadKey(true);
  333. char enteredChar = key.KeyChar;
  334. if (!Char.IsControl(enteredChar))
  335. {
  336. if (m_cursorXPosition >= 318)
  337. continue;
  338. if (enteredChar == '?' && isCommand)
  339. {
  340. if (ContextHelp())
  341. continue;
  342. }
  343. m_commandLine.Insert(m_cursorXPosition, enteredChar);
  344. m_cursorXPosition++;
  345. }
  346. else
  347. {
  348. switch (key.Key)
  349. {
  350. case ConsoleKey.Backspace:
  351. if (m_cursorXPosition == 0)
  352. break;
  353. m_commandLine.Remove(m_cursorXPosition-1, 1);
  354. m_cursorXPosition--;
  355. SetCursorLeft(0);
  356. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  357. if (m_echo)
  358. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  359. else
  360. System.Console.Write("{0}", prompt);
  361. break;
  362. case ConsoleKey.Delete:
  363. if (m_cursorXPosition == m_commandLine.Length)
  364. break;
  365. m_commandLine.Remove(m_cursorXPosition, 1);
  366. SetCursorLeft(0);
  367. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  368. if (m_echo)
  369. System.Console.Write("{0}{1} ", prompt, m_commandLine);
  370. else
  371. System.Console.Write("{0}", prompt);
  372. break;
  373. case ConsoleKey.End:
  374. m_cursorXPosition = m_commandLine.Length;
  375. break;
  376. case ConsoleKey.Home:
  377. m_cursorXPosition = 0;
  378. break;
  379. case ConsoleKey.UpArrow:
  380. if (historyLine < 1)
  381. break;
  382. historyLine--;
  383. LockOutput();
  384. m_commandLine.Remove(0, m_commandLine.Length);
  385. m_commandLine.Append(m_history[historyLine]);
  386. m_cursorXPosition = m_commandLine.Length;
  387. UnlockOutput();
  388. break;
  389. case ConsoleKey.DownArrow:
  390. if (historyLine >= m_history.Count)
  391. break;
  392. historyLine++;
  393. LockOutput();
  394. if (historyLine == m_history.Count)
  395. {
  396. m_commandLine.Remove(0, m_commandLine.Length);
  397. }
  398. else
  399. {
  400. m_commandLine.Remove(0, m_commandLine.Length);
  401. m_commandLine.Append(m_history[historyLine]);
  402. }
  403. m_cursorXPosition = m_commandLine.Length;
  404. UnlockOutput();
  405. break;
  406. case ConsoleKey.LeftArrow:
  407. if (m_cursorXPosition > 0)
  408. m_cursorXPosition--;
  409. break;
  410. case ConsoleKey.RightArrow:
  411. if (m_cursorXPosition < m_commandLine.Length)
  412. m_cursorXPosition++;
  413. break;
  414. case ConsoleKey.Enter:
  415. SetCursorLeft(0);
  416. m_cursorYPosition = SetCursorTop(m_cursorYPosition);
  417. System.Console.WriteLine();
  418. //Show();
  419. lock (m_commandLine)
  420. {
  421. m_cursorYPosition = -1;
  422. }
  423. string commandLine = m_commandLine.ToString();
  424. if (isCommand)
  425. {
  426. string[] cmd = Commands.Resolve(Parser.Parse(commandLine));
  427. if (cmd.Length != 0)
  428. {
  429. int index;
  430. for (index=0 ; index < cmd.Length ; index++)
  431. {
  432. if (cmd[index].Contains(" "))
  433. cmd[index] = "\"" + cmd[index] + "\"";
  434. }
  435. AddToHistory(String.Join(" ", cmd));
  436. return String.Empty;
  437. }
  438. }
  439. // If we're not echoing to screen (e.g. a password) then we probably don't want it in history
  440. if (m_echo && commandLine != "")
  441. AddToHistory(commandLine);
  442. return commandLine;
  443. default:
  444. break;
  445. }
  446. }
  447. }
  448. }
  449. }
  450. }