ConsoleBase.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 OpenSim 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.IO;
  31. using System.Net;
  32. namespace OpenSim.Framework.Console
  33. {
  34. public class ConsoleBase
  35. {
  36. private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  37. private readonly object m_syncRoot = new object();
  38. public conscmd_callback m_cmdParser;
  39. public string m_componentName;
  40. public ConsoleBase(string componentname, conscmd_callback cmdparser)
  41. {
  42. m_componentName = componentname;
  43. m_cmdParser = cmdparser;
  44. System.Console.WriteLine("Creating new local console");
  45. m_log.Info("[" + m_componentName + "]: Started at " + DateTime.Now.ToString());
  46. }
  47. public void Close()
  48. {
  49. m_log.Info("[" + m_componentName + "]: Shutdown at " + DateTime.Now.ToString());
  50. }
  51. /// <summary>
  52. /// derive an ansi color from a string, ignoring the darker colors.
  53. /// This is used to help automatically bin component tags with colors
  54. /// in various print functions.
  55. /// </summary>
  56. /// <param name="input">arbitrary string for input</param>
  57. /// <returns>an ansii color</returns>
  58. private ConsoleColor DeriveColor(string input)
  59. {
  60. int colIdx = (input.ToUpper().GetHashCode() % 6) + 9;
  61. return (ConsoleColor) colIdx;
  62. }
  63. /// <summary>
  64. /// Sends a warning to the current console output
  65. /// </summary>
  66. /// <param name="format">The message to send</param>
  67. /// <param name="args">WriteLine-style message arguments</param>
  68. public void Warn(string format, params object[] args)
  69. {
  70. WriteNewLine(ConsoleColor.Yellow, format, args);
  71. }
  72. /// <summary>
  73. /// Sends a warning to the current console output
  74. /// </summary>
  75. /// <param name="sender">The module that sent this message</param>
  76. /// <param name="format">The message to send</param>
  77. /// <param name="args">WriteLine-style message arguments</param>
  78. public void Warn(string sender, string format, params object[] args)
  79. {
  80. WritePrefixLine(DeriveColor(sender), sender);
  81. WriteNewLine(ConsoleColor.Yellow, format, args);
  82. }
  83. /// <summary>
  84. /// Sends a notice to the current console output
  85. /// </summary>
  86. /// <param name="format">The message to send</param>
  87. /// <param name="args">WriteLine-style message arguments</param>
  88. public void Notice(string format, params object[] args)
  89. {
  90. WriteNewLine(ConsoleColor.White, format, args);
  91. }
  92. /// <summary>
  93. /// Sends a notice to the current console output
  94. /// </summary>
  95. /// <param name="sender">The module that sent this message</param>
  96. /// <param name="format">The message to send</param>
  97. /// <param name="args">WriteLine-style message arguments</param>
  98. public void Notice(string sender, string format, params object[] args)
  99. {
  100. WritePrefixLine(DeriveColor(sender), sender);
  101. WriteNewLine(ConsoleColor.White, format, args);
  102. }
  103. /// <summary>
  104. /// Sends an error to the current console output
  105. /// </summary>
  106. /// <param name="format">The message to send</param>
  107. /// <param name="args">WriteLine-style message arguments</param>
  108. public void Error(string format, params object[] args)
  109. {
  110. WriteNewLine(ConsoleColor.Red, format, args);
  111. }
  112. /// <summary>
  113. /// Sends an error to the current console output
  114. /// </summary>
  115. /// <param name="sender">The module that sent this message</param>
  116. /// <param name="format">The message to send</param>
  117. /// <param name="args">WriteLine-style message arguments</param>
  118. public void Error(string sender, string format, params object[] args)
  119. {
  120. WritePrefixLine(DeriveColor(sender), sender);
  121. Error(format, args);
  122. }
  123. /// <summary>
  124. /// Sends a status message to the current console output
  125. /// </summary>
  126. /// <param name="format">The message to send</param>
  127. /// <param name="args">WriteLine-style message arguments</param>
  128. public void Status(string format, params object[] args)
  129. {
  130. WriteNewLine(ConsoleColor.Blue, format, args);
  131. }
  132. /// <summary>
  133. /// Sends a status message to the current console output
  134. /// </summary>
  135. /// <param name="sender">The module that sent this message</param>
  136. /// <param name="format">The message to send</param>
  137. /// <param name="args">WriteLine-style message arguments</param>
  138. public void Status(string sender, string format, params object[] args)
  139. {
  140. WritePrefixLine(DeriveColor(sender), sender);
  141. WriteNewLine(ConsoleColor.Blue, format, args);
  142. }
  143. [Conditional("DEBUG")]
  144. public void Debug(string format, params object[] args)
  145. {
  146. WriteNewLine(ConsoleColor.Gray, format, args);
  147. }
  148. [Conditional("DEBUG")]
  149. public void Debug(string sender, string format, params object[] args)
  150. {
  151. WritePrefixLine(DeriveColor(sender), sender);
  152. WriteNewLine(ConsoleColor.Gray, format, args);
  153. }
  154. private void WriteNewLine(ConsoleColor color, string format, params object[] args)
  155. {
  156. try
  157. {
  158. lock (m_syncRoot)
  159. {
  160. try
  161. {
  162. if (color != ConsoleColor.White)
  163. System.Console.ForegroundColor = color;
  164. System.Console.WriteLine(format, args);
  165. System.Console.ResetColor();
  166. }
  167. catch (ArgumentNullException)
  168. {
  169. // Some older systems dont support coloured text.
  170. System.Console.WriteLine(format, args);
  171. }
  172. catch (FormatException)
  173. {
  174. System.Console.WriteLine(args);
  175. }
  176. }
  177. }
  178. catch (ObjectDisposedException)
  179. {
  180. }
  181. }
  182. private void WritePrefixLine(ConsoleColor color, string sender)
  183. {
  184. try
  185. {
  186. lock (m_syncRoot)
  187. {
  188. sender = sender.ToUpper();
  189. System.Console.WriteLine("[" + sender + "] ");
  190. System.Console.Write("[");
  191. try
  192. {
  193. System.Console.ForegroundColor = color;
  194. System.Console.Write(sender);
  195. System.Console.ResetColor();
  196. }
  197. catch (ArgumentNullException)
  198. {
  199. // Some older systems dont support coloured text.
  200. System.Console.WriteLine(sender);
  201. }
  202. System.Console.Write("] \t");
  203. }
  204. }
  205. catch (ObjectDisposedException)
  206. {
  207. }
  208. }
  209. public string ReadLine()
  210. {
  211. try
  212. {
  213. return System.Console.ReadLine();
  214. }
  215. catch (Exception e)
  216. {
  217. m_log.Error("[Console]: System.Console.ReadLine exception " + e.ToString());
  218. return String.Empty;
  219. }
  220. }
  221. public int Read()
  222. {
  223. return System.Console.Read();
  224. }
  225. public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue)
  226. {
  227. IPAddress address;
  228. string addressStr;
  229. while (true)
  230. {
  231. addressStr = CmdPrompt(prompt, defaultvalue);
  232. if (IPAddress.TryParse(addressStr, out address))
  233. {
  234. break;
  235. }
  236. else
  237. {
  238. m_log.Error("Illegal address. Please re-enter.");
  239. }
  240. }
  241. return address;
  242. }
  243. public uint CmdPromptIPPort(string prompt, string defaultvalue)
  244. {
  245. uint port;
  246. string portStr;
  247. while (true)
  248. {
  249. portStr = CmdPrompt(prompt, defaultvalue);
  250. if (uint.TryParse(portStr, out port))
  251. {
  252. if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort)
  253. {
  254. break;
  255. }
  256. }
  257. m_log.Error("Illegal address. Please re-enter.");
  258. }
  259. return port;
  260. }
  261. // Displays a prompt and waits for the user to enter a string, then returns that string
  262. // (Done with no echo and suitable for passwords - currently disabled)
  263. public string PasswdPrompt(string prompt)
  264. {
  265. // FIXME: Needs to be better abstracted
  266. System.Console.WriteLine(String.Format("{0}: ", prompt));
  267. //ConsoleColor oldfg = System.Console.ForegroundColor;
  268. //System.Console.ForegroundColor = System.Console.BackgroundColor;
  269. string temp = System.Console.ReadLine();
  270. //System.Console.ForegroundColor = oldfg;
  271. return temp;
  272. }
  273. // Displays a command prompt and waits for the user to enter a string, then returns that string
  274. public string CmdPrompt(string prompt)
  275. {
  276. System.Console.WriteLine(String.Format("{0}: ", prompt));
  277. return ReadLine();
  278. }
  279. // Displays a command prompt and returns a default value if the user simply presses enter
  280. public string CmdPrompt(string prompt, string defaultresponse)
  281. {
  282. string temp = CmdPrompt(String.Format("{0} [{1}]", prompt, defaultresponse));
  283. if (temp == String.Empty)
  284. {
  285. return defaultresponse;
  286. }
  287. else
  288. {
  289. return temp;
  290. }
  291. }
  292. // Displays a command prompt and returns a default value, user may only enter 1 of 2 options
  293. public string CmdPrompt(string prompt, string defaultresponse, string OptionA, string OptionB)
  294. {
  295. bool itisdone = false;
  296. string temp = CmdPrompt(prompt, defaultresponse);
  297. while (itisdone == false)
  298. {
  299. if ((temp == OptionA) || (temp == OptionB))
  300. {
  301. itisdone = true;
  302. }
  303. else
  304. {
  305. System.Console.WriteLine("Valid options are " + OptionA + " or " + OptionB);
  306. temp = CmdPrompt(prompt, defaultresponse);
  307. }
  308. }
  309. return temp;
  310. }
  311. // Runs a command with a number of parameters
  312. public Object RunCmd(string Cmd, string[] cmdparams)
  313. {
  314. m_cmdParser.RunCmd(Cmd, cmdparams);
  315. return null;
  316. }
  317. // Shows data about something
  318. public void ShowCommands(string ShowWhat)
  319. {
  320. m_cmdParser.Show(ShowWhat);
  321. }
  322. public void Prompt()
  323. {
  324. string tempstr = CmdPrompt(m_componentName + "# ");
  325. RunCommand(tempstr);
  326. }
  327. public void RunCommand(string command)
  328. {
  329. string[] tempstrarray;
  330. tempstrarray = command.Split(' ');
  331. string cmd = tempstrarray[0];
  332. Array.Reverse(tempstrarray);
  333. Array.Resize<string>(ref tempstrarray, tempstrarray.Length - 1);
  334. Array.Reverse(tempstrarray);
  335. string[] cmdparams = (string[]) tempstrarray;
  336. try
  337. {
  338. RunCmd(cmd, cmdparams);
  339. }
  340. catch (Exception e)
  341. {
  342. m_log.ErrorFormat("[Console]: Command [{0}] failed with exception {1}", command, e.ToString());
  343. }
  344. }
  345. public string LineInfo
  346. {
  347. get
  348. {
  349. string result = String.Empty;
  350. string stacktrace = Environment.StackTrace;
  351. List<string> lines = new List<string>(stacktrace.Split(new string[] {"at "}, StringSplitOptions.None));
  352. if (lines.Count > 4)
  353. {
  354. lines.RemoveRange(0, 4);
  355. string tmpLine = lines[0];
  356. int inIndex = tmpLine.IndexOf(" in ");
  357. if (inIndex > -1)
  358. {
  359. result = tmpLine.Substring(0, inIndex);
  360. int lineIndex = tmpLine.IndexOf(":line ");
  361. if (lineIndex > -1)
  362. {
  363. lineIndex += 6;
  364. result += ", line " + tmpLine.Substring(lineIndex, (tmpLine.Length - lineIndex) - 5);
  365. }
  366. }
  367. }
  368. return result;
  369. }
  370. }
  371. }
  372. }