Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

CommandLineParser.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*
  2. * Copyright (c) 2006-2011 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.commandline;
  23. import com.dmdirc.Main;
  24. import com.dmdirc.ServerManager;
  25. import com.dmdirc.commandparser.commands.global.NewServer;
  26. import com.dmdirc.config.IdentityManager;
  27. import com.dmdirc.logger.ErrorLevel;
  28. import com.dmdirc.logger.Logger;
  29. import com.dmdirc.updater.components.LauncherComponent;
  30. import com.dmdirc.util.resourcemanager.DMDircResourceManager;
  31. import java.io.File;
  32. import java.net.URI;
  33. import java.net.URISyntaxException;
  34. import java.rmi.RemoteException;
  35. import java.util.ArrayList;
  36. import java.util.List;
  37. /**
  38. * Parses command line arguments for the client.
  39. */
  40. public class CommandLineParser {
  41. /**
  42. * The arguments that the client supports, in groups of four, in the
  43. * following order: short option, long option, description, whether or not
  44. * the option takes an argument.
  45. */
  46. private static final Object[][] ARGUMENTS = new Object[][]{
  47. {'c', "connect", "Connect to the specified server", Boolean.TRUE},
  48. {'d', "directory", "Use the specified configuration directory", Boolean.TRUE},
  49. {'e', "existing", "Try to use an existing instance of DMDirc (use with -c)", Boolean.FALSE},
  50. {'h', "help", "Show command line options and exit", Boolean.FALSE},
  51. {'l', "launcher", "Specifies the version of DMDirc's launcher", Boolean.TRUE},
  52. {'p', "portable", "Enable portable mode", Boolean.FALSE},
  53. {'r', "disable-reporting", "Disable automatic error reporting", Boolean.FALSE},
  54. {'v', "version", "Display client version and exit", Boolean.FALSE},
  55. {'k', "check", "Check if an existing instance of DMDirc exists.", Boolean.FALSE},
  56. };
  57. /** A list of addresses to autoconnect to. */
  58. private final List<URI> addresses = new ArrayList<URI>();
  59. /** Whether to disable error reporting or not. */
  60. private boolean disablereporting;
  61. /** The version string passed for the launcher. */
  62. private String launcherVersion = "";
  63. /** The RMI server we're using. */
  64. private RemoteInterface server;
  65. /**
  66. * Creates a new instance of CommandLineParser.
  67. *
  68. * @param arguments The arguments to be parsed
  69. */
  70. public CommandLineParser(final String ... arguments) {
  71. boolean inArg = false;
  72. char previousArg = '.';
  73. for (String arg : arguments) {
  74. if (inArg) {
  75. processArgument(previousArg, arg);
  76. inArg = false;
  77. } else {
  78. if (arg.startsWith("--")) {
  79. previousArg = processLongArg(arg.substring(2));
  80. inArg = checkArgument(previousArg);
  81. } else if (arg.charAt(0) == '-') {
  82. previousArg = processShortArg(arg.substring(1));
  83. inArg = checkArgument(previousArg);
  84. } else {
  85. doUnknownArg("Unknown argument: " + arg);
  86. }
  87. }
  88. }
  89. if (inArg) {
  90. doUnknownArg("Missing parameter for argument: " + previousArg);
  91. }
  92. if (server != null) {
  93. try {
  94. server.connect(addresses);
  95. System.exit(0);
  96. } catch (RemoteException ex) {
  97. Logger.appError(ErrorLevel.MEDIUM,
  98. "Unable to execute remote connection", ex);
  99. }
  100. }
  101. RemoteServer.bind();
  102. }
  103. /**
  104. * Checks whether the specified arg type takes an argument. If it does,
  105. * this method returns true. If it doesn't, the method processes the
  106. * argument and returns false.
  107. *
  108. * @param argument The short code of the argument
  109. * @return True if the arg requires an argument, false otherwise
  110. */
  111. private boolean checkArgument(final char argument) {
  112. boolean needsArg = false;
  113. for (Object[] target : ARGUMENTS) {
  114. if ((Character) argument == target[0]) {
  115. needsArg = (Boolean) target[3];
  116. break;
  117. }
  118. }
  119. if (needsArg) {
  120. return true;
  121. } else {
  122. processArgument(argument, null);
  123. return false;
  124. }
  125. }
  126. /**
  127. * Processes the specified string as a single long argument.
  128. *
  129. * @param arg The string entered
  130. * @return The short form of the corresponding argument
  131. */
  132. private char processLongArg(final String arg) {
  133. for (Object[] target : ARGUMENTS) {
  134. if (arg.equalsIgnoreCase((String) target[1])) {
  135. return (Character) target[0];
  136. }
  137. }
  138. doUnknownArg("Unknown argument: " + arg);
  139. exit();
  140. return '.';
  141. }
  142. /**
  143. * Processes the specified string as a single short argument.
  144. *
  145. * @param arg The string entered
  146. * @return The short form of the corresponding argument
  147. */
  148. private char processShortArg(final String arg) {
  149. for (Object[] target : ARGUMENTS) {
  150. if (arg.equals(String.valueOf(target[0]))) {
  151. return (Character) target[0];
  152. }
  153. }
  154. doUnknownArg("Unknown argument: " + arg);
  155. exit();
  156. return '.';
  157. }
  158. /**
  159. * Processes the specified command-line argument.
  160. *
  161. * @param arg The short form of the argument used
  162. * @param param The (optional) string parameter for the option
  163. */
  164. private void processArgument(final char arg, final String param) {
  165. switch (arg) {
  166. case 'c':
  167. doConnect(param);
  168. break;
  169. case 'd':
  170. doDirectory(param);
  171. break;
  172. case 'e':
  173. doExisting();
  174. break;
  175. case 'k':
  176. doExistingCheck();
  177. break;
  178. case 'h':
  179. doHelp();
  180. break;
  181. case 'l':
  182. launcherVersion = param;
  183. break;
  184. case 'p':
  185. doDirectory(DMDircResourceManager.getCurrentWorkingDirectory());
  186. break;
  187. case 'r':
  188. disablereporting = true;
  189. break;
  190. case 'v':
  191. doVersion();
  192. break;
  193. default:
  194. // This really shouldn't ever happen, but we'll handle it nicely
  195. // anyway.
  196. doUnknownArg("Unknown argument: " + arg);
  197. break;
  198. }
  199. }
  200. /**
  201. * Informs the user that they entered an unknown argument, prints the
  202. * client help, and exits.
  203. *
  204. * @param message The message about the unknown argument to be displayed
  205. */
  206. private static void doUnknownArg(final String message) {
  207. System.out.println(message);
  208. System.out.println();
  209. doHelp();
  210. }
  211. /**
  212. * Exits DMDirc.
  213. */
  214. private static void exit() {
  215. System.exit(0);
  216. }
  217. /**
  218. * Handles the --connect argument.
  219. *
  220. * @param address The address the user told us to connect to
  221. */
  222. private void doConnect(final String address) {
  223. URI myAddress = null;
  224. try {
  225. myAddress = NewServer.getURI(address);
  226. addresses.add(myAddress);
  227. } catch (URISyntaxException ex) {
  228. doUnknownArg("Invalid address specified: " + ex.getMessage());
  229. }
  230. }
  231. /**
  232. * Handles the --existing argument.
  233. */
  234. private void doExisting() {
  235. server = RemoteServer.getServer();
  236. if (server == null) {
  237. System.err.println("Unable to connect to existing instance");
  238. }
  239. }
  240. /**
  241. * Handles the --check argument.
  242. */
  243. private static void doExistingCheck() {
  244. if (RemoteServer.getServer() == null) {
  245. System.out.println("Existing instance not found.");
  246. System.exit(1);
  247. } else {
  248. System.out.println("Existing instance found.");
  249. System.exit(0);
  250. }
  251. }
  252. /**
  253. * Sets the config directory to the one specified.
  254. *
  255. * @param dir The new config directory
  256. */
  257. private static void doDirectory(final String dir) {
  258. if (dir.endsWith(File.separator)) {
  259. Main.setConfigDir(dir);
  260. } else {
  261. Main.setConfigDir(dir + File.separator);
  262. }
  263. }
  264. /**
  265. * Prints out the client version and exits.
  266. */
  267. private static void doVersion() {
  268. System.out.println("DMDirc - a cross-platform, open-source IRC client.");
  269. System.out.println();
  270. System.out.println(" Version: " + IdentityManager.getIdentityManager()
  271. .getGlobalConfiguration().getOption("version", "version"));
  272. System.out.println(" Update channel: " + IdentityManager.getIdentityManager()
  273. .getGlobalConfiguration().getOption("updater", "channel"));
  274. exit();
  275. }
  276. /**
  277. * Prints out client help and exits.
  278. */
  279. private static void doHelp() {
  280. System.out.println("Usage: java -jar DMDirc.jar [options]");
  281. System.out.println();
  282. System.out.println("Valid options:");
  283. System.out.println();
  284. int maxLength = 0;
  285. for (Object[] arg : ARGUMENTS) {
  286. final String needsArg = ((Boolean) arg[3]) ? " <argument>" : "";
  287. if ((arg[1] + needsArg).length() > maxLength) {
  288. maxLength = (arg[1] + needsArg).length();
  289. }
  290. }
  291. for (Object[] arg : ARGUMENTS) {
  292. final String needsArg = ((Boolean) arg[3]) ? " <argument>" : "";
  293. final StringBuilder desc = new StringBuilder(maxLength + 1);
  294. desc.append(arg[1]);
  295. while (desc.length() < maxLength + 1) {
  296. desc.append(' ');
  297. }
  298. System.out.print(" -" + arg[0] + needsArg);
  299. System.out.println(" --" + desc + needsArg + " " + arg[2]);
  300. System.out.println();
  301. }
  302. exit();
  303. }
  304. /**
  305. * Applies any applicable settings to the config identity.
  306. */
  307. public void applySettings() {
  308. if (disablereporting) {
  309. IdentityManager.getConfigIdentity().setOption("temp", "noerrorreporting", true);
  310. }
  311. if (!launcherVersion.isEmpty()) {
  312. LauncherComponent.setLauncherInfo(launcherVersion);
  313. }
  314. }
  315. /**
  316. * Processes arguments once the client has been loaded properly.
  317. * This allows us to auto-connect to servers, etc.
  318. */
  319. public void processArguments() {
  320. for (URI address : addresses) {
  321. ServerManager.getServerManager().connectToAddress(address);
  322. }
  323. }
  324. }