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