You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Main.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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;
  23. import com.dmdirc.actions.ActionManager;
  24. import com.dmdirc.actions.CoreActionType;
  25. import com.dmdirc.commandline.CommandLineParser;
  26. import com.dmdirc.commandparser.CommandManager;
  27. import com.dmdirc.config.ConfigManager;
  28. import com.dmdirc.config.IdentityManager;
  29. import com.dmdirc.config.InvalidIdentityFileException;
  30. import com.dmdirc.logger.DMDircExceptionHandler;
  31. import com.dmdirc.logger.ErrorLevel;
  32. import com.dmdirc.logger.Logger;
  33. import com.dmdirc.messages.MessageSinkManager;
  34. import com.dmdirc.plugins.PluginInfo;
  35. import com.dmdirc.plugins.PluginManager;
  36. import com.dmdirc.plugins.Service;
  37. import com.dmdirc.plugins.ServiceProvider;
  38. import com.dmdirc.ui.WarningDialog;
  39. import com.dmdirc.interfaces.ui.UIController;
  40. import com.dmdirc.ui.themes.ThemeManager;
  41. import com.dmdirc.updater.UpdateChecker;
  42. import com.dmdirc.updater.Version;
  43. import com.dmdirc.util.resourcemanager.ResourceManager;
  44. import java.awt.GraphicsEnvironment;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.text.SimpleDateFormat;
  48. import java.util.Collection;
  49. import java.util.Date;
  50. import java.util.HashSet;
  51. import java.util.List;
  52. import java.util.Map;
  53. import java.util.Timer;
  54. import java.util.TimerTask;
  55. import java.util.logging.Handler;
  56. import java.util.logging.Level;
  57. /**
  58. * Main class, handles initialisation.
  59. */
  60. public final class Main {
  61. /** Feedback nag delay. */
  62. private static final int FEEDBACK_DELAY = 30 * 60 * 1000;
  63. /** The UI to use for the client. */
  64. private static final Collection<UIController> CONTROLLERS = new HashSet<UIController>();
  65. /** The config dir to use for the client. */
  66. private static String configdir;
  67. /**
  68. * Prevents creation of main.
  69. */
  70. private Main() {
  71. }
  72. /**
  73. * Entry procedure.
  74. *
  75. * @param args the command line arguments
  76. */
  77. @SuppressWarnings("PMD.AvoidCatchingThrowable")
  78. public static void main(final String[] args) {
  79. try {
  80. init(args);
  81. } catch (Throwable ex) {
  82. Logger.appError(ErrorLevel.FATAL, "Exception while initialising",
  83. ex);
  84. }
  85. }
  86. /**
  87. * Initialises the client.
  88. *
  89. * @param args The command line arguments
  90. */
  91. private static void init(final String[] args) {
  92. Thread.setDefaultUncaughtExceptionHandler(new DMDircExceptionHandler());
  93. for (Handler handler : java.util.logging.Logger.getLogger("").getHandlers()) {
  94. handler.setLevel(Level.OFF); // Needs to be changed to enable debugging
  95. }
  96. // Enable finer debugging for specific components like so:
  97. //java.util.logging.Logger.getLogger("com.dmdirc.plugins").setLevel(Level.ALL);
  98. IdentityManager.loadVersion();
  99. final CommandLineParser clp = new CommandLineParser(args);
  100. try {
  101. IdentityManager.load();
  102. } catch (InvalidIdentityFileException iife) {
  103. handleInvalidConfigFile();
  104. }
  105. MessageSinkManager.getManager().loadDefaultSinks();
  106. final PluginManager pm = PluginManager.getPluginManager();
  107. checkBundledPlugins(pm, IdentityManager.getIdentityManager().getGlobalConfiguration());
  108. ThemeManager.loadThemes();
  109. clp.applySettings();
  110. CommandManager.getCommandManager().initCommands();
  111. for (String service : new String[]{"ui", "tabcompletion", "parser"}) {
  112. ensureExists(pm, service);
  113. }
  114. // The user may have an existing parser plugin (e.g. twitter) which
  115. // will satisfy the service existance check above, but will render the
  116. // client pretty useless, so we'll force IRC extraction for now.
  117. extractCorePlugins("parser_irc");
  118. pm.refreshPlugins();
  119. loadUIs(pm);
  120. doFirstRun();
  121. ActionManager.getActionManager().initialise();
  122. pm.doAutoLoad();
  123. ActionManager.getActionManager().loadUserActions();
  124. ActionManager.getActionManager().triggerEvent(
  125. CoreActionType.CLIENT_OPENED, null);
  126. UpdateChecker.init();
  127. clp.processArguments();
  128. GlobalWindow.init();
  129. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
  130. /** {@inheritDoc} */
  131. @Override
  132. public void run() {
  133. ActionManager.getActionManager().triggerEvent(
  134. CoreActionType.CLIENT_CLOSED, null);
  135. ServerManager.getServerManager().disconnectAll("Unexpected shutdown");
  136. IdentityManager.save();
  137. }
  138. }, "Shutdown thread"));
  139. }
  140. /**
  141. * Called when the UI has failed to initialise correctly. This method
  142. * attempts to extract any and all UI plugins bundled with the client, and
  143. * requests a restart. If this has already been attempted, it shows an error
  144. * and exits.
  145. */
  146. private static void handleMissingUI() {
  147. // Check to see if we have already tried this
  148. if (IdentityManager.getIdentityManager().getGlobalConfiguration().hasOptionBool("debug", "uiFixAttempted")) {
  149. System.out.println("DMDirc is unable to load any compatible UI plugins.");
  150. if (!GraphicsEnvironment.isHeadless()) {
  151. new WarningDialog(WarningDialog.NO_COMPAT_UIS_TITLE,
  152. WarningDialog.NO_RECOV_UIS).displayBlocking();
  153. }
  154. IdentityManager.getIdentityManager().getGlobalConfigIdentity().unsetOption("debug", "uiFixAttempted");
  155. System.exit(1);
  156. } else {
  157. // Try to extract the UIs again incase they changed between versions
  158. // and the user didn't update the UI plugin.
  159. extractCorePlugins("ui_");
  160. System.out.println("DMDirc has updated the UI plugins and needs to restart.");
  161. if (!GraphicsEnvironment.isHeadless()) {
  162. new WarningDialog(WarningDialog.NO_COMPAT_UIS_TITLE,
  163. WarningDialog.NO_COMPAT_UIS_BODY).displayBlocking();
  164. }
  165. // Allow the rebooted DMDirc to know that we have attempted restarting.
  166. IdentityManager.getConfigIdentity().setOption("debug", "uiFixAttempted", "true");
  167. // Tell the launcher to restart!
  168. System.exit(42);
  169. }
  170. }
  171. /**
  172. * Called when the global config cannot be loaded due to an error. This
  173. * method informs the user of the problem and installs a new default config
  174. * file, backing up the old one.
  175. */
  176. private static void handleInvalidConfigFile() {
  177. final String date = new SimpleDateFormat("yyyyMMddkkmmss").format(new Date());
  178. final String message = "DMDirc has detected that your config file "
  179. + "has become corrupted.<br><br>DMDirc will now backup "
  180. + "your current config and try restarting with a default "
  181. + "config.<br><br>Your old config will be saved as:<br>"
  182. + "dmdirc.config." + date;
  183. if (!GraphicsEnvironment.isHeadless()) {
  184. new WarningDialog("Invalid Config File", message).displayBlocking();
  185. }
  186. // Let command-line users know what is happening.
  187. System.out.println(message.replace("<br>", "\n"));
  188. final File configFile = new File(getConfigDir() + "dmdirc.config");
  189. final File newConfigFile = new File(getConfigDir() + "dmdirc.config." + date);
  190. if (configFile.renameTo(newConfigFile)) {
  191. try {
  192. IdentityManager.load();
  193. } catch (InvalidIdentityFileException iife2) {
  194. // This shouldn't happen!
  195. Logger.appError(ErrorLevel.FATAL, "Unable to load global config", iife2);
  196. }
  197. } else {
  198. final String newMessage = "DMDirc was unable to rename the "
  199. + "global config file and is unable to fix this issue.";
  200. if (!GraphicsEnvironment.isHeadless()) {
  201. new WarningDialog("Invalid Config File", newMessage).displayBlocking();
  202. }
  203. System.out.println(newMessage.replace("<br>", "\n"));
  204. System.exit(1);
  205. }
  206. }
  207. /**
  208. * Ensures that there is at least one provider of the specified
  209. * service type by extracting matching core plugins. Plugins must be named
  210. * so that their file name starts with the service type, and then an
  211. * underscore.
  212. *
  213. * @param pm The plugin manager to use to access services
  214. * @param serviceType The type of service that should exist
  215. */
  216. public static void ensureExists(final PluginManager pm, final String serviceType) {
  217. if (pm.getServicesByType(serviceType).isEmpty()) {
  218. extractCorePlugins(serviceType + "_");
  219. pm.refreshPlugins();
  220. }
  221. }
  222. /**
  223. * Checks whether the plugins bundled with this release of DMDirc are newer
  224. * than the plugins known by the specified {@link PluginManager}. If the
  225. * bundled plugins are newer, they are automatically extracted.
  226. *
  227. * @param pm The plugin manager to use to check plugins
  228. * @param config The configuration source for bundled versions
  229. */
  230. private static void checkBundledPlugins(final PluginManager pm, final ConfigManager config) {
  231. for (PluginInfo plugin : pm.getPluginInfos()) {
  232. if (config.hasOptionString("bundledplugins_versions", plugin.getMetaData().getName())) {
  233. final Version bundled = new Version(config.getOption("bundledplugins_versions",
  234. plugin.getMetaData().getName()));
  235. final Version installed = plugin.getMetaData().getVersion();
  236. if (installed.compareTo(bundled) < 0) {
  237. extractCorePlugins(plugin.getMetaData().getName());
  238. PluginManager.getPluginManager().reloadPlugin(plugin.getFilename());
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. * Attempts to find and activate a service which provides a UI that we
  245. * can use.
  246. *
  247. * @param pm The plugin manager to use to load plugins
  248. */
  249. protected static void loadUIs(final PluginManager pm) {
  250. final List<Service> uis = pm.getServicesByType("ui");
  251. // First try: go for our desired service type
  252. for (Service service : uis) {
  253. if (service.activate()) {
  254. final ServiceProvider provider = service.getActiveProvider();
  255. final Object export = provider.getExportedService("getController").execute();
  256. if (export != null) {
  257. CONTROLLERS.add((UIController) export);
  258. }
  259. }
  260. }
  261. if (CONTROLLERS.isEmpty()) {
  262. handleMissingUI();
  263. } else {
  264. // The fix worked!
  265. if (IdentityManager.getIdentityManager().getGlobalConfiguration().hasOptionBool("debug", "uiFixAttempted")) {
  266. IdentityManager.getConfigIdentity().unsetOption("debug", "uiFixAttempted");
  267. }
  268. }
  269. }
  270. /**
  271. * Executes the first run or migration wizards as required.
  272. */
  273. private static void doFirstRun() {
  274. if (IdentityManager.getIdentityManager().getGlobalConfiguration().getOptionBool("general", "firstRun")) {
  275. IdentityManager.getConfigIdentity().setOption("general", "firstRun", "false");
  276. for (UIController controller : CONTROLLERS) {
  277. controller.showFirstRunWizard();
  278. }
  279. new Timer().schedule(new TimerTask() {
  280. /** {@inheritDoc} */
  281. @Override
  282. public void run() {
  283. for (UIController controller : CONTROLLERS) {
  284. controller.showFeedbackNag();
  285. }
  286. }
  287. }, FEEDBACK_DELAY);
  288. }
  289. }
  290. /**
  291. * Quits the client nicely, with the default closing message.
  292. */
  293. public static void quit() {
  294. quit(0);
  295. }
  296. /**
  297. * Quits the client nicely, with the default closing message.
  298. *
  299. * @param exitCode This is the exit code that will be returned to the
  300. * operating system when the client exits
  301. */
  302. public static void quit(final int exitCode) {
  303. quit(IdentityManager.getIdentityManager().getGlobalConfiguration().getOption("general",
  304. "closemessage"), exitCode);
  305. }
  306. /**
  307. * Quits the client nicely.
  308. *
  309. * @param reason The quit reason to send
  310. */
  311. public static void quit(final String reason) {
  312. quit(reason, 0);
  313. }
  314. /**
  315. * Quits the client nicely.
  316. *
  317. * @param reason The quit reason to send
  318. * @param exitCode This is the exit code that will be returned to the
  319. * operating system when the client exits
  320. */
  321. public static void quit(final String reason, final int exitCode) {
  322. ServerManager.getServerManager().disconnectAll(reason);
  323. System.exit(exitCode);
  324. }
  325. /**
  326. * Retrieves the UI controller that's being used by the client.
  327. *
  328. * @return The client's UI controller
  329. * @deprecated Shouldn't be used. There may be multiple or no controllers.
  330. */
  331. @Deprecated
  332. public static UIController getUI() {
  333. return CONTROLLERS.iterator().next();
  334. }
  335. /**
  336. * Returns the application's config directory.
  337. *
  338. * @return configuration directory
  339. */
  340. public static String getConfigDir() {
  341. if (configdir == null) {
  342. initialiseConfigDir();
  343. }
  344. return configdir;
  345. }
  346. /**
  347. * Initialises the location of the configuration directory.
  348. */
  349. protected static void initialiseConfigDir() {
  350. final String fs = System.getProperty("file.separator");
  351. final String osName = System.getProperty("os.name");
  352. if (System.getenv("DMDIRC_HOME") != null) {
  353. configdir = System.getenv("DMDIRC_HOME");
  354. } else if (osName.startsWith("Mac OS")) {
  355. configdir = System.getProperty("user.home") + fs + "Library"
  356. + fs + "Preferences" + fs + "DMDirc" + fs;
  357. } else if (osName.startsWith("Windows")) {
  358. if (System.getenv("APPDATA") == null) {
  359. configdir = System.getProperty("user.home") + fs + "DMDirc" + fs;
  360. } else {
  361. configdir = System.getenv("APPDATA") + fs + "DMDirc" + fs;
  362. }
  363. } else {
  364. configdir = System.getProperty("user.home") + fs + ".DMDirc" + fs;
  365. final File testFile = new File(configdir);
  366. if (!testFile.exists()) {
  367. final String configHome = System.getenv("XDG_CONFIG_HOME");
  368. configdir = (configHome == null || configHome.isEmpty())
  369. ? System.getProperty("user.home") + fs + ".config" + fs
  370. : configHome;
  371. configdir += fs + "DMDirc" + fs;
  372. }
  373. }
  374. configdir = new File(configdir).getAbsolutePath() + fs;
  375. }
  376. /**
  377. * Sets the config directory for this client.
  378. *
  379. * @param newdir The new configuration directory
  380. */
  381. public static void setConfigDir(final String newdir) {
  382. configdir = newdir;
  383. }
  384. /**
  385. * Extracts plugins bundled with DMDirc to the user's profile's plugin
  386. * directory.
  387. *
  388. * @param prefix If non-null, only plugins whose file name starts with
  389. * this prefix will be extracted.
  390. */
  391. public static void extractCorePlugins(final String prefix) {
  392. final Map<String, byte[]> resources = ResourceManager.getResourceManager()
  393. .getResourcesStartingWithAsBytes("plugins");
  394. for (Map.Entry<String, byte[]> resource : resources.entrySet()) {
  395. try {
  396. final String resourceName = Main.getConfigDir() + "plugins"
  397. + resource.getKey().substring(7);
  398. if (prefix != null && !resource.getKey().substring(8).startsWith(prefix)) {
  399. continue;
  400. }
  401. final File newDir = new File(resourceName.substring(0,
  402. resourceName.lastIndexOf('/')) + "/");
  403. if (!newDir.exists()) {
  404. newDir.mkdirs();
  405. }
  406. final File newFile = new File(newDir,
  407. resourceName.substring(resourceName.lastIndexOf('/') + 1,
  408. resourceName.length()));
  409. if (!newFile.isDirectory()) {
  410. final PluginManager pm = PluginManager.getPluginManager();
  411. ResourceManager.getResourceManager().
  412. resourceToFile(resource.getValue(), newFile);
  413. final PluginInfo plugin = pm.getPluginInfo(newFile
  414. .getAbsolutePath().substring(pm.getDirectory().length()));
  415. if (plugin != null) {
  416. plugin.pluginUpdated();
  417. }
  418. }
  419. } catch (IOException ex) {
  420. Logger.userError(ErrorLevel.LOW, "Failed to extract plugins", ex);
  421. }
  422. }
  423. }
  424. }