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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc;
  18. import com.dmdirc.GlobalWindow.GlobalWindowManager;
  19. import com.dmdirc.commandline.CommandLineParser;
  20. import com.dmdirc.commandparser.CommandManager;
  21. import com.dmdirc.events.ClientOpenedEvent;
  22. import com.dmdirc.events.FeedbackNagEvent;
  23. import com.dmdirc.events.FirstRunEvent;
  24. import com.dmdirc.interfaces.CommandController.CommandDetails;
  25. import com.dmdirc.interfaces.ConnectionManager;
  26. import com.dmdirc.events.eventbus.EventBus;
  27. import com.dmdirc.interfaces.Migrator;
  28. import com.dmdirc.interfaces.SystemLifecycleComponent;
  29. import com.dmdirc.interfaces.config.IdentityController;
  30. import com.dmdirc.interfaces.ui.UIController;
  31. import com.dmdirc.logger.DMDircExceptionHandler;
  32. import com.dmdirc.logger.ModeAliasReporter;
  33. import com.dmdirc.logger.ProgramErrorAppender;
  34. import com.dmdirc.logger.ProgramErrorManager;
  35. import com.dmdirc.plugins.CorePluginExtractor;
  36. import com.dmdirc.plugins.PluginManager;
  37. import com.dmdirc.plugins.Service;
  38. import com.dmdirc.plugins.ServiceManager;
  39. import com.dmdirc.plugins.ServiceProvider;
  40. import com.dmdirc.ui.WarningDialog;
  41. import ch.qos.logback.classic.LoggerContext;
  42. import ch.qos.logback.classic.joran.JoranConfigurator;
  43. import ch.qos.logback.core.spi.ContextAware;
  44. import com.google.common.util.concurrent.ThreadFactoryBuilder;
  45. import java.awt.GraphicsEnvironment;
  46. import java.util.Collection;
  47. import java.util.HashSet;
  48. import java.util.List;
  49. import java.util.Set;
  50. import java.util.concurrent.Executors;
  51. import java.util.concurrent.TimeUnit;
  52. import javax.inject.Inject;
  53. import org.slf4j.Logger;
  54. import org.slf4j.LoggerFactory;
  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 command-line parser used for this instance. */
  67. private final CommandLineParser commandLineParser;
  68. /** The plugin manager the client will use. */
  69. private final PluginManager pluginManager;
  70. /** The extractor to use for core plugins. */
  71. private final CorePluginExtractor corePluginExtractor;
  72. /** The command manager to use. */
  73. private final CommandManager commandManager;
  74. /** The global window manager to use. */
  75. private final GlobalWindowManager globalWindowManager;
  76. /** The set of known lifecycle components. */
  77. private final Set<SystemLifecycleComponent> lifecycleComponents;
  78. /** The set of migrators to execute on startup. */
  79. private final Set<Migrator> migrators;
  80. /** The event bus to dispatch events on. */
  81. private final EventBus eventBus;
  82. /** The commands to load into the command manager. */
  83. private final Set<CommandDetails> commands;
  84. /** Mode alias reporter to use. */
  85. private final ModeAliasReporter reporter;
  86. private final ServiceManager serviceManager;
  87. private final ProgramErrorManager errorManager;
  88. static {
  89. // TODO: Can this go in a Dagger module?
  90. final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  91. final ContextAware configurator = new JoranConfigurator();
  92. configurator.setContext(context);
  93. context.reset();
  94. }
  95. /**
  96. * Creates a new instance of {@link Main}.
  97. */
  98. @Inject
  99. public Main(
  100. final IdentityController identityManager,
  101. final ConnectionManager connectionManager,
  102. final CommandLineParser commandLineParser,
  103. final PluginManager pluginManager,
  104. final CommandManager commandManager,
  105. final CorePluginExtractor corePluginExtractor,
  106. final GlobalWindowManager globalWindowManager,
  107. final Set<SystemLifecycleComponent> lifecycleComponents,
  108. final Set<Migrator> migrators,
  109. final EventBus eventBus,
  110. final Set<CommandDetails> commands,
  111. final ModeAliasReporter reporter,
  112. final ServiceManager serviceManager,
  113. final ProgramErrorManager errorManager) {
  114. this.identityManager = identityManager;
  115. this.connectionManager = connectionManager;
  116. this.commandLineParser = commandLineParser;
  117. this.pluginManager = pluginManager;
  118. this.corePluginExtractor = corePluginExtractor;
  119. this.commandManager = commandManager;
  120. this.globalWindowManager = globalWindowManager;
  121. this.lifecycleComponents = lifecycleComponents;
  122. this.migrators = migrators;
  123. this.eventBus = eventBus;
  124. this.commands = commands;
  125. this.reporter = reporter;
  126. this.serviceManager = serviceManager;
  127. this.errorManager = errorManager;
  128. }
  129. /**
  130. * Entry procedure.
  131. *
  132. * @param args the command line arguments
  133. */
  134. @SuppressWarnings("PMD.AvoidCatchingThrowable")
  135. public static void main(final String... args) {
  136. /* TODO: Make this not break reflection from plugins...
  137. try {
  138. Policy.setPolicy(new DMDircSecurityPolicy());
  139. System.setSecurityManager(new SecurityManager());
  140. } catch (SecurityException ex) {
  141. System.err.println("Unable to set security policy: " + ex.getMessage());
  142. ex.printStackTrace();
  143. }
  144. */
  145. try {
  146. final ClientModule clientModule = new ClientModule();
  147. final ObjectGraph graph = ObjectGraph.create(clientModule);
  148. clientModule.setObjectGraph(graph);
  149. final CommandLineParser parser = graph.get(CommandLineParser.class);
  150. parser.parse(args);
  151. graph.get(Main.class).init();
  152. } catch (Throwable ex) {
  153. System.err.println("Unable to set security policy: " + ex.getMessage());
  154. ex.printStackTrace();
  155. }
  156. }
  157. /**
  158. * Initialises the client.
  159. */
  160. public void init() {
  161. Thread.setDefaultUncaughtExceptionHandler(new DMDircExceptionHandler());
  162. setupLogback();
  163. migrators.stream().filter(Migrator::needsMigration).forEach(Migrator::migrate);
  164. commands.forEach(c -> commandManager.registerCommand(c.getCommand(), c.getInfo()));
  165. loadUIs(serviceManager);
  166. doFirstRun();
  167. lifecycleComponents.forEach(SystemLifecycleComponent::startUp);
  168. pluginManager.doAutoLoad();
  169. eventBus.publishAsync(new ClientOpenedEvent());
  170. eventBus.subscribe(reporter);
  171. commandLineParser.processArguments(connectionManager);
  172. globalWindowManager.init();
  173. }
  174. /**
  175. * Called when the UI has failed to initialise correctly. This method attempts to extract any
  176. * and all UI plugins bundled with the client, and requests a restart. If this has already been
  177. * attempted, it shows an error and exits.
  178. */
  179. private void handleMissingUI() {
  180. // Check to see if we have already tried this
  181. if (identityManager.getGlobalConfiguration().hasOptionBool("debug", "uiFixAttempted")) {
  182. System.out.println("DMDirc is unable to load any compatible UI plugins.");
  183. if (!GraphicsEnvironment.isHeadless()) {
  184. new WarningDialog(WarningDialog.NO_COMPAT_UIS_TITLE,
  185. WarningDialog.NO_RECOV_UIS).displayBlocking();
  186. }
  187. identityManager.getUserSettings().unsetOption("debug", "uiFixAttempted");
  188. System.exit(1);
  189. } else {
  190. // Try to extract the UIs again in case they changed between versions
  191. // and the user didn't update the UI plugin.
  192. corePluginExtractor.extractCorePlugins("ui_");
  193. System.out.println("DMDirc has updated the UI plugins and needs to restart.");
  194. if (!GraphicsEnvironment.isHeadless()) {
  195. new WarningDialog(WarningDialog.NO_COMPAT_UIS_TITLE,
  196. WarningDialog.NO_COMPAT_UIS_BODY).displayBlocking();
  197. }
  198. // Allow the rebooted DMDirc to know that we have attempted restarting.
  199. identityManager.getUserSettings().setOption("debug", "uiFixAttempted", "true");
  200. // Tell the launcher to restart!
  201. System.exit(42);
  202. }
  203. }
  204. /**
  205. * Attempts to find and activate a service which provides a UI that we can use.
  206. *
  207. * @param pm The plugin manager to use to load plugins
  208. */
  209. protected void loadUIs(final ServiceManager pm) {
  210. final List<Service> uis = pm.getServicesByType("ui");
  211. // First try: go for our desired service type
  212. uis.stream().filter(Service::activate).forEach(service -> {
  213. final ServiceProvider provider = service.getActiveProvider();
  214. final Object export = provider.getExportedService("getController").execute();
  215. if (export != null) {
  216. CONTROLLERS.add((UIController) export);
  217. }
  218. });
  219. if (CONTROLLERS.isEmpty()) {
  220. handleMissingUI();
  221. } else {
  222. // The fix worked!
  223. if (identityManager.getGlobalConfiguration().hasOptionBool("debug", "uiFixAttempted")) {
  224. identityManager.getUserSettings().unsetOption("debug", "uiFixAttempted");
  225. }
  226. }
  227. }
  228. /**
  229. * Executes the first run or migration wizards as required.
  230. */
  231. private void doFirstRun() {
  232. if (identityManager.getGlobalConfiguration().getOptionBool("general", "firstRun")) {
  233. identityManager.getUserSettings().setOption("general", "firstRun", "false");
  234. eventBus.publish(new FirstRunEvent());
  235. Executors.newSingleThreadScheduledExecutor(
  236. new ThreadFactoryBuilder().setNameFormat("feedback-nag-%d").build()).schedule(
  237. () -> eventBus.publishAsync(new FeedbackNagEvent()), 5, TimeUnit.MINUTES);
  238. }
  239. }
  240. private void setupLogback() {
  241. // TODO: Add a normal logging thing, with or without runtime switching.
  242. final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  243. final ProgramErrorAppender appender = new ProgramErrorAppender();
  244. appender.setProgramErrorManager(errorManager);
  245. appender.setContext(context);
  246. appender.setName("Error Logger");
  247. appender.start();
  248. final ch.qos.logback.classic.Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
  249. rootLogger.addAppender(appender);
  250. }
  251. }