LocalConsole.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. // A console that uses cursor control and color
  38. //
  39. public class LocalConsole : CommandConsole
  40. {
  41. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  42. // private readonly object m_syncRoot = new object();
  43. private int y = -1;
  44. private int cp = 0;
  45. private int h = 1;
  46. private StringBuilder cmdline = new StringBuilder();
  47. private bool echo = true;
  48. private List<string> history = new List<string>();
  49. private static readonly ConsoleColor[] Colors = {
  50. // the dark colors don't seem to be visible on some black background terminals like putty :(
  51. //ConsoleColor.DarkBlue,
  52. //ConsoleColor.DarkGreen,
  53. //ConsoleColor.DarkCyan,
  54. //ConsoleColor.DarkMagenta,
  55. //ConsoleColor.DarkYellow,
  56. ConsoleColor.Gray,
  57. //ConsoleColor.DarkGray,
  58. ConsoleColor.Blue,
  59. ConsoleColor.Green,
  60. ConsoleColor.Cyan,
  61. ConsoleColor.Magenta,
  62. ConsoleColor.Yellow
  63. };
  64. private static ConsoleColor DeriveColor(string input)
  65. {
  66. // it is important to do Abs, hash values can be negative
  67. return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
  68. }
  69. public LocalConsole(string defaultPrompt) : base(defaultPrompt)
  70. {
  71. }
  72. private void AddToHistory(string text)
  73. {
  74. while (history.Count >= 100)
  75. history.RemoveAt(0);
  76. history.Add(text);
  77. }
  78. private int SetCursorTop(int top)
  79. {
  80. if (top >= 0 && top < System.Console.BufferHeight)
  81. {
  82. System.Console.CursorTop = top;
  83. return top;
  84. }
  85. else
  86. {
  87. return System.Console.CursorTop;
  88. }
  89. }
  90. private int SetCursorLeft(int left)
  91. {
  92. if (left >= 0 && left < System.Console.BufferWidth)
  93. {
  94. System.Console.CursorLeft = left;
  95. return left;
  96. }
  97. else
  98. {
  99. return System.Console.CursorLeft;
  100. }
  101. }
  102. private void Show()
  103. {
  104. lock (cmdline)
  105. {
  106. if (y == -1 || System.Console.BufferWidth == 0)
  107. return;
  108. int xc = prompt.Length + cp;
  109. int new_x = xc % System.Console.BufferWidth;
  110. int new_y = y + xc / System.Console.BufferWidth;
  111. int end_y = y + (cmdline.Length + prompt.Length) / System.Console.BufferWidth;
  112. if (end_y / System.Console.BufferWidth >= h)
  113. h++;
  114. if (end_y >= System.Console.BufferHeight) // wrap
  115. {
  116. y--;
  117. new_y--;
  118. System.Console.CursorLeft = 0;
  119. System.Console.CursorTop = System.Console.BufferHeight-1;
  120. System.Console.WriteLine(" ");
  121. }
  122. y=SetCursorTop(y);
  123. System.Console.CursorLeft = 0;
  124. if (echo)
  125. System.Console.Write("{0}{1}", prompt, cmdline);
  126. else
  127. System.Console.Write("{0}", prompt);
  128. SetCursorLeft(new_x);
  129. SetCursorTop(new_y);
  130. }
  131. }
  132. public override void LockOutput()
  133. {
  134. Monitor.Enter(cmdline);
  135. try
  136. {
  137. if (y != -1)
  138. {
  139. y = SetCursorTop(y);
  140. System.Console.CursorLeft = 0;
  141. int count = cmdline.Length + prompt.Length;
  142. while (count-- > 0)
  143. System.Console.Write(" ");
  144. y = SetCursorTop(y);
  145. System.Console.CursorLeft = 0;
  146. }
  147. }
  148. catch (Exception)
  149. {
  150. }
  151. }
  152. public override void UnlockOutput()
  153. {
  154. if (y != -1)
  155. {
  156. y = System.Console.CursorTop;
  157. Show();
  158. }
  159. Monitor.Exit(cmdline);
  160. }
  161. private void WriteColorText(ConsoleColor color, string sender)
  162. {
  163. try
  164. {
  165. lock (this)
  166. {
  167. try
  168. {
  169. System.Console.ForegroundColor = color;
  170. System.Console.Write(sender);
  171. System.Console.ResetColor();
  172. }
  173. catch (ArgumentNullException)
  174. {
  175. // Some older systems dont support coloured text.
  176. System.Console.WriteLine(sender);
  177. }
  178. }
  179. }
  180. catch (ObjectDisposedException)
  181. {
  182. }
  183. }
  184. private void WriteLocalText(string text, string level)
  185. {
  186. string regex = @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)";
  187. Regex RE = new Regex(regex, RegexOptions.Multiline);
  188. MatchCollection matches = RE.Matches(text);
  189. string outText = text;
  190. if (matches.Count == 1)
  191. {
  192. outText = matches[0].Groups["End"].Value;
  193. System.Console.Write(matches[0].Groups["Front"].Value);
  194. System.Console.Write("[");
  195. WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
  196. matches[0].Groups["Category"].Value);
  197. System.Console.Write("]:");
  198. }
  199. if (level == "error")
  200. WriteColorText(ConsoleColor.Red, outText);
  201. else if (level == "warn")
  202. WriteColorText(ConsoleColor.Yellow, outText);
  203. else
  204. System.Console.Write(outText);
  205. System.Console.WriteLine();
  206. }
  207. public override void Output(string text)
  208. {
  209. Output(text, "normal");
  210. }
  211. public override void Output(string text, string level)
  212. {
  213. lock (cmdline)
  214. {
  215. if (y == -1)
  216. {
  217. WriteLocalText(text, level);
  218. return;
  219. }
  220. y = SetCursorTop(y);
  221. System.Console.CursorLeft = 0;
  222. int count = cmdline.Length + prompt.Length;
  223. while (count-- > 0)
  224. System.Console.Write(" ");
  225. y = SetCursorTop(y);
  226. System.Console.CursorLeft = 0;
  227. WriteLocalText(text, level);
  228. y = System.Console.CursorTop;
  229. Show();
  230. }
  231. }
  232. private bool ContextHelp()
  233. {
  234. string[] words = Parser.Parse(cmdline.ToString());
  235. bool trailingSpace = cmdline.ToString().EndsWith(" ");
  236. // Allow ? through while typing a URI
  237. //
  238. if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
  239. return false;
  240. string[] opts = Commands.FindNextOption(words, trailingSpace);
  241. if (opts[0].StartsWith("Command help:"))
  242. Output(opts[0]);
  243. else
  244. Output(String.Format("Options: {0}", String.Join(" ", opts)));
  245. return true;
  246. }
  247. public override string ReadLine(string p, bool isCommand, bool e)
  248. {
  249. h = 1;
  250. cp = 0;
  251. prompt = p;
  252. echo = e;
  253. int historyLine = history.Count;
  254. System.Console.CursorLeft = 0; // Needed for mono
  255. System.Console.Write(" "); // Needed for mono
  256. lock (cmdline)
  257. {
  258. y = System.Console.CursorTop;
  259. cmdline.Remove(0, cmdline.Length);
  260. }
  261. while (true)
  262. {
  263. Show();
  264. ConsoleKeyInfo key = System.Console.ReadKey(true);
  265. char c = key.KeyChar;
  266. if (!Char.IsControl(c))
  267. {
  268. if (cp >= 318)
  269. continue;
  270. if (c == '?' && isCommand)
  271. {
  272. if (ContextHelp())
  273. continue;
  274. }
  275. cmdline.Insert(cp, c);
  276. cp++;
  277. }
  278. else
  279. {
  280. switch (key.Key)
  281. {
  282. case ConsoleKey.Backspace:
  283. if (cp == 0)
  284. break;
  285. cmdline.Remove(cp-1, 1);
  286. cp--;
  287. System.Console.CursorLeft = 0;
  288. y = SetCursorTop(y);
  289. System.Console.Write("{0}{1} ", prompt, cmdline);
  290. break;
  291. case ConsoleKey.End:
  292. cp = cmdline.Length;
  293. break;
  294. case ConsoleKey.Home:
  295. cp = 0;
  296. break;
  297. case ConsoleKey.UpArrow:
  298. if (historyLine < 1)
  299. break;
  300. historyLine--;
  301. LockOutput();
  302. cmdline.Remove(0, cmdline.Length);
  303. cmdline.Append(history[historyLine]);
  304. cp = cmdline.Length;
  305. UnlockOutput();
  306. break;
  307. case ConsoleKey.DownArrow:
  308. if (historyLine >= history.Count)
  309. break;
  310. historyLine++;
  311. LockOutput();
  312. if (historyLine == history.Count)
  313. {
  314. cmdline.Remove(0, cmdline.Length);
  315. }
  316. else
  317. {
  318. cmdline.Remove(0, cmdline.Length);
  319. cmdline.Append(history[historyLine]);
  320. }
  321. cp = cmdline.Length;
  322. UnlockOutput();
  323. break;
  324. case ConsoleKey.LeftArrow:
  325. if (cp > 0)
  326. cp--;
  327. break;
  328. case ConsoleKey.RightArrow:
  329. if (cp < cmdline.Length)
  330. cp++;
  331. break;
  332. case ConsoleKey.Enter:
  333. System.Console.CursorLeft = 0;
  334. y = SetCursorTop(y);
  335. System.Console.WriteLine("{0}{1}", prompt, cmdline);
  336. lock (cmdline)
  337. {
  338. y = -1;
  339. }
  340. if (isCommand)
  341. {
  342. string[] cmd = Commands.Resolve(Parser.Parse(cmdline.ToString()));
  343. if (cmd.Length != 0)
  344. {
  345. int i;
  346. for (i=0 ; i < cmd.Length ; i++)
  347. {
  348. if (cmd[i].Contains(" "))
  349. cmd[i] = "\"" + cmd[i] + "\"";
  350. }
  351. AddToHistory(String.Join(" ", cmd));
  352. return String.Empty;
  353. }
  354. }
  355. AddToHistory(cmdline.ToString());
  356. return cmdline.ToString();
  357. default:
  358. break;
  359. }
  360. }
  361. }
  362. }
  363. }
  364. }