Commander.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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.Reflection;
  30. using System.Text;
  31. using log4net;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Environment.Interfaces;
  34. namespace OpenSim.Region.Environment.Modules.Framework
  35. {
  36. /// <summary>
  37. /// A single function call encapsulated in a class which enforces arguments when passing around as Object[]'s.
  38. /// Used for console commands and script API generation
  39. /// </summary>
  40. public class Command : ICommand
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. private List<CommandArgument> m_args = new List<CommandArgument>();
  44. private Action<object[]> m_command;
  45. private string m_help;
  46. private string m_name;
  47. public Command(string name, Action<Object[]> command, string help)
  48. {
  49. m_name = name;
  50. m_command = command;
  51. m_help = help;
  52. }
  53. #region ICommand Members
  54. public void AddArgument(string name, string helptext, string type)
  55. {
  56. m_args.Add(new CommandArgument(name, helptext, type));
  57. }
  58. public string Name
  59. {
  60. get { return m_name; }
  61. }
  62. public string Help
  63. {
  64. get { return m_help; }
  65. }
  66. public Dictionary<string, string> Arguments
  67. {
  68. get
  69. {
  70. Dictionary<string, string> tmp = new Dictionary<string, string>();
  71. foreach (CommandArgument arg in m_args)
  72. {
  73. tmp.Add(arg.Name, arg.ArgumentType);
  74. }
  75. return tmp;
  76. }
  77. }
  78. public void ShowConsoleHelp()
  79. {
  80. m_log.Info("== " + Name + " ==");
  81. m_log.Info(m_help);
  82. m_log.Info("= Parameters =");
  83. foreach (CommandArgument arg in m_args)
  84. {
  85. m_log.Info("* " + arg.Name + " (" + arg.ArgumentType + ")");
  86. m_log.Info("\t" + arg.HelpText);
  87. }
  88. }
  89. public void Run(Object[] args)
  90. {
  91. Object[] cleanArgs = new Object[m_args.Count];
  92. if (args.Length < cleanArgs.Length)
  93. {
  94. m_log.Error("Missing " + (cleanArgs.Length - args.Length) + " argument(s)");
  95. ShowConsoleHelp();
  96. return;
  97. }
  98. if (args.Length > cleanArgs.Length)
  99. {
  100. m_log.Error("Too many arguments for this command. Type '<module> <command> help' for help.");
  101. return;
  102. }
  103. int i = 0;
  104. foreach (Object arg in args)
  105. {
  106. if (string.IsNullOrEmpty(arg.ToString()))
  107. {
  108. m_log.Error("Empty arguments are not allowed");
  109. return;
  110. }
  111. try
  112. {
  113. switch (m_args[i].ArgumentType)
  114. {
  115. case "String":
  116. m_args[i].ArgumentValue = arg.ToString();
  117. break;
  118. case "Integer":
  119. m_args[i].ArgumentValue = Int32.Parse(arg.ToString());
  120. break;
  121. case "Double":
  122. m_args[i].ArgumentValue = Double.Parse(arg.ToString());
  123. break;
  124. case "Boolean":
  125. m_args[i].ArgumentValue = Boolean.Parse(arg.ToString());
  126. break;
  127. default:
  128. m_log.Error("Unknown desired type for argument " + m_args[i].Name + " on command " + m_name);
  129. break;
  130. }
  131. }
  132. catch (FormatException)
  133. {
  134. m_log.Error("Argument number " + (i + 1) +
  135. " (" + m_args[i].Name + ") must be a valid " +
  136. m_args[i].ArgumentType.ToLower() + ".");
  137. }
  138. cleanArgs[i] = m_args[i].ArgumentValue;
  139. i++;
  140. }
  141. m_command.Invoke(cleanArgs);
  142. }
  143. #endregion
  144. }
  145. /// <summary>
  146. /// A single command argument, contains name, type and at runtime, value.
  147. /// </summary>
  148. public class CommandArgument
  149. {
  150. private string m_help;
  151. private string m_name;
  152. private string m_type;
  153. private Object m_val;
  154. public CommandArgument(string name, string help, string type)
  155. {
  156. m_name = name;
  157. m_help = help;
  158. m_type = type;
  159. }
  160. public string Name
  161. {
  162. get { return m_name; }
  163. }
  164. public string HelpText
  165. {
  166. get { return m_help; }
  167. }
  168. public string ArgumentType
  169. {
  170. get { return m_type; }
  171. }
  172. public Object ArgumentValue
  173. {
  174. get { return m_val; }
  175. set { m_val = value; }
  176. }
  177. }
  178. /// <summary>
  179. /// A class to enable modules to register console and script commands, which enforces typing and valid input.
  180. /// </summary>
  181. public class Commander : ICommander
  182. {
  183. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  184. private Dictionary<string, ICommand> m_commands = new Dictionary<string, ICommand>();
  185. private string m_name;
  186. public Commander(string name)
  187. {
  188. m_name = name;
  189. }
  190. #region ICommander Members
  191. public void RegisterCommand(string commandName, ICommand command)
  192. {
  193. m_commands[commandName] = command;
  194. }
  195. /// <summary>
  196. /// Generates a runtime C# class which can be compiled and inserted via reflection to enable modules to register new script commands
  197. /// </summary>
  198. /// <returns>Returns C# source code to create a binding</returns>
  199. public string GenerateRuntimeAPI()
  200. {
  201. string classSrc = "\n\tpublic class " + m_name + " {\n";
  202. foreach (ICommand com in m_commands.Values)
  203. {
  204. classSrc += "\tpublic void " + EscapeRuntimeAPICommand(com.Name) + "( ";
  205. foreach (KeyValuePair<string, string> arg in com.Arguments)
  206. {
  207. classSrc += arg.Value + " " + Util.Md5Hash(arg.Key) + ",";
  208. }
  209. classSrc = classSrc.Remove(classSrc.Length - 1); // Delete the last comma
  210. classSrc += " )\n\t{\n";
  211. classSrc += "\t\tObject[] args = new Object[" + com.Arguments.Count.ToString() + "];\n";
  212. int i = 0;
  213. foreach (KeyValuePair<string, string> arg in com.Arguments)
  214. {
  215. classSrc += "\t\targs[" + i.ToString() + "] = " + Util.Md5Hash(arg.Key) + " " + ";\n";
  216. i++;
  217. }
  218. classSrc += "\t\tGetCommander(\"" + m_name + "\").Run(\"" + com.Name + "\", args);\n";
  219. classSrc += "\t}\n";
  220. }
  221. classSrc += "}\n";
  222. return classSrc;
  223. }
  224. /// <summary>
  225. /// Runs a specified function with attached arguments
  226. /// *** <b>DO NOT CALL DIRECTLY.</b> ***
  227. /// Call ProcessConsoleCommand instead if handling human input.
  228. /// </summary>
  229. /// <param name="function">The function name to call</param>
  230. /// <param name="args">The function parameters</param>
  231. public void Run(string function, object[] args)
  232. {
  233. m_commands[function].Run(args);
  234. }
  235. public void ProcessConsoleCommand(string function, string[] args)
  236. {
  237. if (m_commands.ContainsKey(function))
  238. {
  239. if (args.Length > 0 && args[0] == "help")
  240. {
  241. m_commands[function].ShowConsoleHelp();
  242. }
  243. else
  244. {
  245. m_commands[function].Run(args);
  246. }
  247. }
  248. else
  249. {
  250. if (function != "help")
  251. m_log.Error("Invalid command - No such command exists");
  252. if (function == "api")
  253. m_log.Info(GenerateRuntimeAPI());
  254. ShowConsoleHelp();
  255. }
  256. }
  257. #endregion
  258. private void ShowConsoleHelp()
  259. {
  260. m_log.Info("===" + m_name + "===");
  261. foreach (ICommand com in m_commands.Values)
  262. {
  263. m_log.Info("* " + com.Name + " - " + com.Help);
  264. }
  265. }
  266. private string EscapeRuntimeAPICommand(string command)
  267. {
  268. command = command.Replace('-', '_');
  269. StringBuilder tmp = new StringBuilder(command);
  270. tmp[0] = tmp[0].ToString().ToUpper().ToCharArray()[0];
  271. return tmp.ToString();
  272. }
  273. }
  274. }