1
0

LocalConsole.cs 19 KB

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