Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Main.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. * Copyright (c) 2006-2015 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.GlobalWindow.GlobalWindowManager;
  24. import com.dmdirc.actions.ActionManager;
  25. import com.dmdirc.actions.ColourActionComparison;
  26. import com.dmdirc.commandline.CommandLineParser;
  27. import com.dmdirc.commandparser.CommandManager;
  28. import com.dmdirc.events.ClientClosedEvent;
  29. import com.dmdirc.events.ClientOpenedEvent;
  30. import com.dmdirc.events.FeedbackNagEvent;
  31. import com.dmdirc.events.FirstRunEvent;
  32. import com.dmdirc.interfaces.CommandController.CommandDetails;
  33. import com.dmdirc.interfaces.ConnectionManager;
  34. import com.dmdirc.interfaces.Migrator;
  35. import com.dmdirc.interfaces.SystemLifecycleComponent;
  36. import com.dmdirc.interfaces.config.IdentityController;
  37. import com.dmdirc.interfaces.ui.UIController;
  38. import com.dmdirc.logger.DMDircExceptionHandler;
  39. import com.dmdirc.logger.ModeAliasReporter;
  40. import com.dmdirc.plugins.CorePluginExtractor;
  41. import com.dmdirc.plugins.PluginManager;
  42. import com.dmdirc.plugins.Service;
  43. import com.dmdirc.plugins.ServiceManager;
  44. import com.dmdirc.plugins.ServiceProvider;
  45. import com.dmdirc.ui.WarningDialog;
  46. import com.google.common.util.concurrent.ThreadFactoryBuilder;
  47. import java.awt.GraphicsEnvironment;
  48. import java.util.Collection;
  49. import java.util.HashSet;
  50. import java.util.List;
  51. import java.util.Set;
  52. import java.util.concurrent.Executors;
  53. import java.util.concurrent.TimeUnit;
  54. import javax.inject.Inject;
  55. import dagger.ObjectGraph;
  56. /**
  57. * Main class, handles initialisation.
  58. */
  59. public class Main {
  60. /** The UI to use for the client. */
  61. private final Collection<UIController> CONTROLLERS = new HashSet<>();
  62. /** The identity manager the client will use. */
  63. private final IdentityController identityManager;
  64. /** The server manager the client will use. */
  65. private final ConnectionManager connectionManager;
  66. /** The action manager the client will use. */
  67. private final ActionManager actionManager;
  68. /** The command-line parser used for this instance. */
  69. private final CommandLineParser commandLineParser;
  70. /** The plugin manager the client will use. */
  71. private final PluginManager pluginManager;
  72. /** The extractor to use for core plugins. */
  73. private final CorePluginExtractor corePluginExtractor;
  74. /** The command manager to use. */
  75. private final CommandManager commandManager;
  76. /** The global window manager to use. */
  77. private final GlobalWindowManager globalWindowManager;
  78. /** The colour-based action comparisons. */
  79. private final ColourActionComparison colourActionComparison;
  80. /** The set of known lifecycle components. */
  81. private final Set<SystemLifecycleComponent> lifecycleComponents;
  82. /** The set of migrators to execute on startup. */
  83. private final Set<Migrator> migrators;
  84. /** The event bus to dispatch events on. */
  85. private final DMDircMBassador eventBus;
  86. /** The commands to load into the command manager. */
  87. private final Set<CommandDetails> commands;
  88. /** Mode alias reporter to use. */
  89. private final ModeAliasReporter reporter;
  90. /**
  91. * Creates a new instance of {@link Main}.
  92. */
  93. @Inject
  94. public Main(
  95. final IdentityController identityManager,
  96. final ConnectionManager connectionManager,
  97. final ActionManager actionManager,
  98. final CommandLineParser commandLineParser,
  99. final PluginManager pluginManager,
  100. final CommandManager commandManager,
  101. final CorePluginExtractor corePluginExtractor,
  102. final GlobalWindowManager globalWindowManager,
  103. final ColourActionComparison colourActionComparison,
  104. final Set<SystemLifecycleComponent> lifecycleComponents,
  105. final Set<Migrator> migrators,
  106. final DMDircMBassador eventBus,
  107. final Set<CommandDetails> commands,
  108. final ModeAliasReporter reporter) {
  109. this.identityManager = identityManager;
  110. this.connectionManager = connectionManager;
  111. this.actionManager = actionManager;
  112. this.commandLineParser = commandLineParser;
  113. this.pluginManager = pluginManager;
  114. this.corePluginExtractor = corePluginExtractor;
  115. this.commandManager = commandManager;
  116. this.globalWindowManager = globalWindowManager;
  117. this.colourActionComparison = colourActionComparison;
  118. this.lifecycleComponents = lifecycleComponents;
  119. this.migrators = migrators;
  120. this.eventBus = eventBus;
  121. this.commands = commands;
  122. this.reporter = reporter;
  123. }
  124. /**
  125. * Entry procedure.
  126. *
  127. * @param args the command line arguments
  128. */
  129. @SuppressWarnings("PMD.AvoidCatchingThrowable")
  130. public static void main(final String... args) {
  131. /* TODO: Make this not break reflection from plugins...
  132. try {
  133. Policy.setPolicy(new DMDircSecurityPolicy());
  134. System.setSecurityManager(new SecurityManager());
  135. } catch (SecurityException ex) {
  136. System.err.println("Unable to set security policy: " + ex.getMessage());
  137. ex.printStackTrace();
  138. }
  139. */
  140. try {
  141. final ClientModule clientModule = new ClientModule();
  142. final ObjectGraph graph = ObjectGraph.create(clientModule);
  143. clientModule.setObjectGraph(graph);
  144. final CommandLineParser parser = graph.get(CommandLineParser.class);
  145. parser.parse(args);
  146. graph.get(Main.class).init();
  147. } catch (Throwable ex) {
  148. System.err.println("Unable to set security policy: " + ex.getMessage());
  149. ex.printStackTrace();
  150. }
  151. }
  152. /**
  153. * Initialises the client.
  154. */
  155. public void init() {
  156. Thread.setDefaultUncaughtExceptionHandler(new DMDircExceptionHandler(eventBus));
  157. migrators.stream().filter(Migrator::needsMigration).forEach(Migrator::migrate);
  158. commands.forEach(c -> commandManager.registerCommand(c.getCommand(), c.getInfo()));
  159. loadUIs(pluginManager);
  160. doFirstRun();
  161. lifecycleComponents.forEach(SystemLifecycleComponent::startUp);
  162. actionManager.initialise(colourActionComparison);
  163. pluginManager.doAutoLoad();
  164. actionManager.loadUserActions();
  165. eventBus.publishAsync(new ClientOpenedEvent());
  166. eventBus.subscribe(reporter);
  167. commandLineParser.processArguments(connectionManager);
  168. globalWindowManager.init();
  169. Runtime.getRuntime().addShutdownHook(new Thread(() -> {
  170. lifecycleComponents.forEach(SystemLifecycleComponent::shutDown);
  171. eventBus.publishAsync(new ClientClosedEvent());
  172. connectionManager.disconnectAll("Unexpected shutdown");
  173. identityManager.saveAll();
  174. }, "Shutdown thread"));
  175. }
  176. /**
  177. * Called when the UI has failed to initialise correctly. This method attempts to extract any
  178. * and all UI plugins bundled with the client, and requests a restart. If this has already been
  179. * attempted, it shows an error and exits.
  180. */
  181. private void handleMissingUI() {
  182. // Check to see if we have already tried this
  183. if (identityManager.getGlobalConfiguration().hasOptionBool("debug", "uiFixAttempted")) {
  184. System.out.println("DMDirc is unable to load any compatible UI plugins.");
  185. if (!GraphicsEnvironment.isHeadless()) {
  186. new WarningDialog(WarningDialog.NO_COMPAT_UIS_TITLE,
  187. WarningDialog.NO_RECOV_UIS).displayBlocking();
  188. }
  189. identityManager.getUserSettings().unsetOption("debug", "uiFixAttempted");
  190. System.exit(1);
  191. } else {
  192. // Try to extract the UIs again in case they changed between versions
  193. // and the user didn't update the UI plugin.
  194. corePluginExtractor.extractCorePlugins("ui_");
  195. System.out.println("DMDirc has updated the UI plugins and needs to restart.");
  196. if (!GraphicsEnvironment.isHeadless()) {
  197. new WarningDialog(WarningDialog.NO_COMPAT_UIS_TITLE,
  198. WarningDialog.NO_COMPAT_UIS_BODY).displayBlocking();
  199. }
  200. // Allow the rebooted DMDirc to know that we have attempted restarting.
  201. identityManager.getUserSettings().setOption("debug", "uiFixAttempted", "true");
  202. // Tell the launcher to restart!
  203. System.exit(42);
  204. }
  205. }
  206. /**
  207. * Attempts to find and activate a service which provides a UI that we can use.
  208. *
  209. * @param pm The plugin manager to use to load plugins
  210. */
  211. protected void loadUIs(final ServiceManager pm) {
  212. final List<Service> uis = pm.getServicesByType("ui");
  213. // First try: go for our desired service type
  214. uis.stream().filter(Service::activate).forEach(service -> {
  215. final ServiceProvider provider = service.getActiveProvider();
  216. final Object export = provider.getExportedService("getController").execute();
  217. if (export != null) {
  218. CONTROLLERS.add((UIController) export);
  219. }
  220. });
  221. if (CONTROLLERS.isEmpty()) {
  222. handleMissingUI();
  223. } else {
  224. // The fix worked!
  225. if (identityManager.getGlobalConfiguration().hasOptionBool("debug", "uiFixAttempted")) {
  226. identityManager.getUserSettings().unsetOption("debug", "uiFixAttempted");
  227. }
  228. }
  229. }
  230. /**
  231. * Executes the first run or migration wizards as required.
  232. */
  233. private void doFirstRun() {
  234. if (identityManager.getGlobalConfiguration().getOptionBool("general", "firstRun")) {
  235. identityManager.getUserSettings().setOption("general", "firstRun", "false");
  236. eventBus.publish(new FirstRunEvent());
  237. Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
  238. .setNameFormat("feedback-nag-%d").build()).schedule(
  239. () -> eventBus.publishAsync(new FeedbackNagEvent()), 5, TimeUnit.MINUTES);
  240. }
  241. }
  242. }