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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Copyright (c) 2006-2012 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.interfaces.ui.UIController;
  31. import com.dmdirc.logger.DMDircExceptionHandler;
  32. import com.dmdirc.logger.ErrorLevel;
  33. import com.dmdirc.logger.Logger;
  34. import com.dmdirc.messages.MessageSinkManager;
  35. import com.dmdirc.plugins.PluginInfo;
  36. import com.dmdirc.plugins.PluginManager;
  37. import com.dmdirc.plugins.Service;
  38. import com.dmdirc.plugins.ServiceProvider;
  39. import com.dmdirc.ui.WarningDialog;
  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.getIdentityManager().loadVersionIdentity();
  99. final CommandLineParser clp = new CommandLineParser(args);
  100. try {
  101. IdentityManager.getIdentityManager().initialise();
  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.getIdentityManager().saveAll();
  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.getIdentityManager().getGlobalConfigIdentity()
  167. .setOption("debug", "uiFixAttempted", "true");
  168. // Tell the launcher to restart!
  169. System.exit(42);
  170. }
  171. }
  172. /**
  173. * Called when the global config cannot be loaded due to an error. This
  174. * method informs the user of the problem and installs a new default config
  175. * file, backing up the old one.
  176. */
  177. private static void handleInvalidConfigFile() {
  178. final String date = new SimpleDateFormat("yyyyMMddkkmmss").format(new Date());
  179. final String message = "DMDirc has detected that your config file "
  180. + "has become corrupted.<br><br>DMDirc will now backup "
  181. + "your current config and try restarting with a default "
  182. + "config.<br><br>Your old config will be saved as:<br>"
  183. + "dmdirc.config." + date;
  184. if (!GraphicsEnvironment.isHeadless()) {
  185. new WarningDialog("Invalid Config File", message).displayBlocking();
  186. }
  187. // Let command-line users know what is happening.
  188. System.out.println(message.replace("<br>", "\n"));
  189. final File configFile = new File(getConfigDir() + "dmdirc.config");
  190. final File newConfigFile = new File(getConfigDir() + "dmdirc.config." + date);
  191. if (configFile.renameTo(newConfigFile)) {
  192. try {
  193. IdentityManager.getIdentityManager().initialise();
  194. } catch (InvalidIdentityFileException iife2) {
  195. // This shouldn't happen!
  196. Logger.appError(ErrorLevel.FATAL, "Unable to load global config", iife2);
  197. }
  198. } else {
  199. final String newMessage = "DMDirc was unable to rename the "
  200. + "global config file and is unable to fix this issue.";
  201. if (!GraphicsEnvironment.isHeadless()) {
  202. new WarningDialog("Invalid Config File", newMessage).displayBlocking();
  203. }
  204. System.out.println(newMessage.replace("<br>", "\n"));
  205. System.exit(1);
  206. }
  207. }
  208. /**
  209. * Ensures that there is at least one provider of the specified
  210. * service type by extracting matching core plugins. Plugins must be named
  211. * so that their file name starts with the service type, and then an
  212. * underscore.
  213. *
  214. * @param pm The plugin manager to use to access services
  215. * @param serviceType The type of service that should exist
  216. */
  217. public static void ensureExists(final PluginManager pm, final String serviceType) {
  218. if (pm.getServicesByType(serviceType).isEmpty()) {
  219. extractCorePlugins(serviceType + "_");
  220. pm.refreshPlugins();
  221. }
  222. }
  223. /**
  224. * Checks whether the plugins bundled with this release of DMDirc are newer
  225. * than the plugins known by the specified {@link PluginManager}. If the
  226. * bundled plugins are newer, they are automatically extracted.
  227. *
  228. * @param pm The plugin manager to use to check plugins
  229. * @param config The configuration source for bundled versions
  230. */
  231. private static void checkBundledPlugins(final PluginManager pm, final ConfigManager config) {
  232. for (PluginInfo plugin : pm.getPluginInfos()) {
  233. if (config.hasOptionString("bundledplugins_versions", plugin.getMetaData().getName())) {
  234. final Version bundled = new Version(config.getOption("bundledplugins_versions",
  235. plugin.getMetaData().getName()));
  236. final Version installed = plugin.getMetaData().getVersion();
  237. if (installed.compareTo(bundled) < 0) {
  238. extractCorePlugins(plugin.getMetaData().getName());
  239. PluginManager.getPluginManager().reloadPlugin(plugin.getFilename());
  240. }
  241. }
  242. }
  243. }
  244. /**
  245. * Attempts to find and activate a service which provides a UI that we
  246. * can use.
  247. *
  248. * @param pm The plugin manager to use to load plugins
  249. */
  250. protected static void loadUIs(final PluginManager pm) {
  251. final List<Service> uis = pm.getServicesByType("ui");
  252. // First try: go for our desired service type
  253. for (Service service : uis) {
  254. if (service.activate()) {
  255. final ServiceProvider provider = service.getActiveProvider();
  256. final Object export = provider.getExportedService("getController").execute();
  257. if (export != null) {
  258. CONTROLLERS.add((UIController) export);
  259. }
  260. }
  261. }
  262. if (CONTROLLERS.isEmpty()) {
  263. handleMissingUI();
  264. } else {
  265. // The fix worked!
  266. if (IdentityManager.getIdentityManager().getGlobalConfiguration()
  267. .hasOptionBool("debug", "uiFixAttempted")) {
  268. IdentityManager.getIdentityManager().getGlobalConfigIdentity()
  269. .unsetOption("debug", "uiFixAttempted");
  270. }
  271. }
  272. }
  273. /**
  274. * Executes the first run or migration wizards as required.
  275. */
  276. private static void doFirstRun() {
  277. if (IdentityManager.getIdentityManager().getGlobalConfiguration().getOptionBool("general", "firstRun")) {
  278. IdentityManager.getIdentityManager().getGlobalConfigIdentity().setOption("general", "firstRun", "false");
  279. for (UIController controller : CONTROLLERS) {
  280. controller.showFirstRunWizard();
  281. }
  282. new Timer().schedule(new TimerTask() {
  283. /** {@inheritDoc} */
  284. @Override
  285. public void run() {
  286. for (UIController controller : CONTROLLERS) {
  287. controller.showFeedbackNag();
  288. }
  289. }
  290. }, FEEDBACK_DELAY);
  291. }
  292. }
  293. /**
  294. * Quits the client nicely, with the default closing message.
  295. */
  296. public static void quit() {
  297. quit(0);
  298. }
  299. /**
  300. * Quits the client nicely, with the default closing message.
  301. *
  302. * @param exitCode This is the exit code that will be returned to the
  303. * operating system when the client exits
  304. */
  305. public static void quit(final int exitCode) {
  306. quit(IdentityManager.getIdentityManager().getGlobalConfiguration().getOption("general",
  307. "closemessage"), exitCode);
  308. }
  309. /**
  310. * Quits the client nicely.
  311. *
  312. * @param reason The quit reason to send
  313. */
  314. public static void quit(final String reason) {
  315. quit(reason, 0);
  316. }
  317. /**
  318. * Quits the client nicely.
  319. *
  320. * @param reason The quit reason to send
  321. * @param exitCode This is the exit code that will be returned to the
  322. * operating system when the client exits
  323. */
  324. public static void quit(final String reason, final int exitCode) {
  325. ServerManager.getServerManager().disconnectAll(reason);
  326. System.exit(exitCode);
  327. }
  328. /**
  329. * Retrieves the UI controller that's being used by the client.
  330. *
  331. * @return The client's UI controller
  332. * @deprecated Shouldn't be used. There may be multiple or no controllers.
  333. */
  334. @Deprecated
  335. public static UIController getUI() {
  336. return CONTROLLERS.iterator().next();
  337. }
  338. /**
  339. * Returns the application's config directory.
  340. *
  341. * @return configuration directory
  342. */
  343. public static String getConfigDir() {
  344. if (configdir == null) {
  345. initialiseConfigDir();
  346. }
  347. return configdir;
  348. }
  349. /**
  350. * Initialises the location of the configuration directory.
  351. */
  352. protected static void initialiseConfigDir() {
  353. final String fs = System.getProperty("file.separator");
  354. final String osName = System.getProperty("os.name");
  355. if (System.getenv("DMDIRC_HOME") != null) {
  356. configdir = System.getenv("DMDIRC_HOME");
  357. } else if (osName.startsWith("Mac OS")) {
  358. configdir = System.getProperty("user.home") + fs + "Library"
  359. + fs + "Preferences" + fs + "DMDirc" + fs;
  360. } else if (osName.startsWith("Windows")) {
  361. if (System.getenv("APPDATA") == null) {
  362. configdir = System.getProperty("user.home") + fs + "DMDirc" + fs;
  363. } else {
  364. configdir = System.getenv("APPDATA") + fs + "DMDirc" + fs;
  365. }
  366. } else {
  367. configdir = System.getProperty("user.home") + fs + ".DMDirc" + fs;
  368. final File testFile = new File(configdir);
  369. if (!testFile.exists()) {
  370. final String configHome = System.getenv("XDG_CONFIG_HOME");
  371. configdir = (configHome == null || configHome.isEmpty())
  372. ? System.getProperty("user.home") + fs + ".config" + fs
  373. : configHome;
  374. configdir += fs + "DMDirc" + fs;
  375. }
  376. }
  377. configdir = new File(configdir).getAbsolutePath() + fs;
  378. }
  379. /**
  380. * Sets the config directory for this client.
  381. *
  382. * @param newdir The new configuration directory
  383. */
  384. public static void setConfigDir(final String newdir) {
  385. configdir = newdir;
  386. }
  387. /**
  388. * Extracts plugins bundled with DMDirc to the user's profile's plugin
  389. * directory.
  390. *
  391. * @param prefix If non-null, only plugins whose file name starts with
  392. * this prefix will be extracted.
  393. */
  394. public static void extractCorePlugins(final String prefix) {
  395. final Map<String, byte[]> resources = ResourceManager.getResourceManager()
  396. .getResourcesStartingWithAsBytes("plugins");
  397. for (Map.Entry<String, byte[]> resource : resources.entrySet()) {
  398. try {
  399. final String resourceName = Main.getConfigDir() + "plugins"
  400. + resource.getKey().substring(7);
  401. if (prefix != null && !resource.getKey().substring(8).startsWith(prefix)) {
  402. continue;
  403. }
  404. final File newDir = new File(resourceName.substring(0,
  405. resourceName.lastIndexOf('/')) + "/");
  406. if (!newDir.exists()) {
  407. newDir.mkdirs();
  408. }
  409. final File newFile = new File(newDir,
  410. resourceName.substring(resourceName.lastIndexOf('/') + 1,
  411. resourceName.length()));
  412. if (!newFile.isDirectory()) {
  413. final PluginManager pm = PluginManager.getPluginManager();
  414. ResourceManager.getResourceManager().
  415. resourceToFile(resource.getValue(), newFile);
  416. final PluginInfo plugin = pm.getPluginInfo(newFile
  417. .getAbsolutePath().substring(pm.getDirectory().length()));
  418. if (plugin != null) {
  419. plugin.pluginUpdated();
  420. }
  421. }
  422. } catch (IOException ex) {
  423. Logger.userError(ErrorLevel.LOW, "Failed to extract plugins", ex);
  424. }
  425. }
  426. }
  427. }