LocalConsole.cs 17 KB

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