Ignore:
Timestamp:
2016-08-25T23:21:10+02:00 (8 years ago)
Author:
Don-vip
Message:

fix #13318 - Clean up program startup (parameters, logging) - patch by michael2402 - gsoc-core

Location:
trunk/src/org/openstreetmap/josm/gui
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r10876 r10899  
    2525import java.security.Policy;
    2626import java.security.cert.CertificateException;
    27 import java.util.ArrayList;
    2827import java.util.Arrays;
    2928import java.util.Collection;
    30 import java.util.EnumMap;
    3129import java.util.List;
    3230import java.util.Locale;
    33 import java.util.Map;
     31import java.util.Optional;
    3432import java.util.Set;
    3533import java.util.TreeSet;
     34import java.util.logging.Level;
    3635
    3736import javax.swing.JOptionPane;
     
    4645import org.openstreetmap.josm.data.CustomConfigurator;
    4746import org.openstreetmap.josm.data.Version;
     47import org.openstreetmap.josm.gui.ProgramArguments.Option;
    4848import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
    4949import org.openstreetmap.josm.gui.download.DownloadDialog;
     
    6363import org.openstreetmap.josm.tools.HttpClient;
    6464import org.openstreetmap.josm.tools.I18n;
     65import org.openstreetmap.josm.tools.Logging;
    6566import org.openstreetmap.josm.tools.OsmUrlToBounds;
    6667import org.openstreetmap.josm.tools.PlatformHookWindows;
    6768import org.openstreetmap.josm.tools.Utils;
    6869import org.openstreetmap.josm.tools.WindowGeometry;
     70import org.openstreetmap.josm.tools.bugreport.BugReport;
    6971import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
    70 
    71 import gnu.getopt.Getopt;
    72 import gnu.getopt.LongOpt;
    7372
    7473/**
     
    171170
    172171    /**
    173      * JOSM command line options.
    174      * @see <a href="https://josm.openstreetmap.de/wiki/Help/CommandLineOptions">Help/CommandLineOptions</a>
    175      * @since 5279
    176      */
    177     public enum Option {
    178         /** --help|-h                                  Show this help */
    179         HELP(false),
    180         /** --version                                  Displays the JOSM version and exits */
    181         VERSION(false),
    182         /** --debug                                    Print debugging messages to console */
    183         DEBUG(false),
    184         /** --trace                                    Print detailed debugging messages to console */
    185         TRACE(false),
    186         /** --language=&lt;language&gt;                Set the language */
    187         LANGUAGE(true),
    188         /** --reset-preferences                        Reset the preferences to default */
    189         RESET_PREFERENCES(false),
    190         /** --load-preferences=&lt;url-to-xml&gt;      Changes preferences according to the XML file */
    191         LOAD_PREFERENCES(true),
    192         /** --set=&lt;key&gt;=&lt;value&gt;            Set preference key to value */
    193         SET(true),
    194         /** --geometry=widthxheight(+|-)x(+|-)y        Standard unix geometry argument */
    195         GEOMETRY(true),
    196         /** --no-maximize                              Do not launch in maximized mode */
    197         NO_MAXIMIZE(false),
    198         /** --maximize                                 Launch in maximized mode */
    199         MAXIMIZE(false),
    200         /** --download=minlat,minlon,maxlat,maxlon     Download the bounding box <br>
    201          *  --download=&lt;URL&gt;                     Download the location at the URL (with lat=x&amp;lon=y&amp;zoom=z) <br>
    202          *  --download=&lt;filename&gt;                Open a file (any file type that can be opened with File/Open) */
    203         DOWNLOAD(true),
    204         /** --downloadgps=minlat,minlon,maxlat,maxlon  Download the bounding box as raw GPS <br>
    205          *  --downloadgps=&lt;URL&gt;                  Download the location at the URL (with lat=x&amp;lon=y&amp;zoom=z) as raw GPS */
    206         DOWNLOADGPS(true),
    207         /** --selection=&lt;searchstring&gt;           Select with the given search */
    208         SELECTION(true),
    209         /** --offline=&lt;osm_api|josm_website|all&gt; Disable access to the given resource(s), delimited by comma */
    210         OFFLINE(true),
    211         /** --skip-plugins */
    212         SKIP_PLUGINS(false);
    213 
    214         private final String name;
    215         private final boolean requiresArg;
    216 
    217         Option(boolean requiresArgument) {
    218             this.name = name().toLowerCase(Locale.ENGLISH).replace('_', '-');
    219             this.requiresArg = requiresArgument;
    220         }
    221 
    222         /**
    223          * Replies the option name
    224          * @return The option name, in lowercase
    225          */
    226         public String getName() {
    227             return name;
    228         }
    229 
    230         /**
    231          * Determines if this option requires an argument.
    232          * @return {@code true} if this option requires an argument, {@code false} otherwise
    233          */
    234         public boolean requiresArgument() {
    235             return requiresArg;
    236         }
    237     }
    238 
    239     /**
    240      * Builds the command-line argument map.
    241      * @param args command-line arguments array
    242      * @return command-line argument map
    243      */
    244     public static Map<Option, Collection<String>> buildCommandLineArgumentMap(String ... args) {
    245 
    246         List<LongOpt> los = new ArrayList<>();
    247         for (Option o : Option.values()) {
    248             los.add(new LongOpt(o.getName(), o.requiresArgument() ? LongOpt.REQUIRED_ARGUMENT : LongOpt.NO_ARGUMENT, null, 0));
    249         }
    250 
    251         Getopt g = new Getopt("JOSM", args, "hv", los.toArray(new LongOpt[los.size()]));
    252 
    253         Map<Option, Collection<String>> argMap = new EnumMap<>(Option.class);
    254 
    255         int c;
    256         while ((c = g.getopt()) != -1) {
    257             Option opt;
    258             switch (c) {
    259                 case 'h':
    260                     opt = Option.HELP;
    261                     break;
    262                 case 'v':
    263                     opt = Option.VERSION;
    264                     break;
    265                 case 0:
    266                     opt = Option.values()[g.getLongind()];
    267                     break;
    268                 default:
    269                     opt = null;
    270             }
    271             if (opt != null) {
    272                 Collection<String> values = argMap.get(opt);
    273                 if (values == null) {
    274                     values = new ArrayList<>();
    275                     argMap.put(opt, values);
    276                 }
    277                 values.add(g.getOptarg());
    278             } else
    279                 throw new IllegalArgumentException("Invalid option: "+c);
    280         }
    281         // positional arguments are a shortcut for the --download ... option
    282         for (int i = g.getOptind(); i < args.length; ++i) {
    283             Collection<String> values = argMap.get(Option.DOWNLOAD);
    284             if (values == null) {
    285                 values = new ArrayList<>();
    286                 argMap.put(Option.DOWNLOAD, values);
    287             }
    288             values.add(args[i]);
    289         }
    290 
    291         return argMap;
    292     }
    293 
    294     /**
    295172     * Main application Startup
    296173     * @param argArray Command-line arguments
     
    300177
    301178        // construct argument table
    302         Map<Option, Collection<String>> args = null;
     179        ProgramArguments args = null;
    303180        try {
    304             args = buildCommandLineArgumentMap(argArray);
     181            args = new ProgramArguments(argArray);
    305182        } catch (IllegalArgumentException e) {
    306183            System.exit(1);
     
    308185        }
    309186
    310         final boolean languageGiven = args.containsKey(Option.LANGUAGE);
    311 
    312         if (languageGiven) {
    313             I18n.set(args.get(Option.LANGUAGE).iterator().next());
    314         }
    315 
    316         if (args.containsKey(Option.TRACE)) {
    317             // Enable JOSM debug level
    318             logLevel = 5;
    319             // Enable debug in OAuth signpost via system preference, but only at trace level
    320             Utils.updateSystemProperty("debug", "true");
    321             Main.info(tr("Enabled detailed debug level (trace)"));
    322         } else if (args.containsKey(Option.DEBUG)) {
    323             // Enable JOSM debug level
    324             logLevel = 4;
    325             Main.info(tr("Printing debugging messages to console"));
    326         }
     187        Level logLevel = args.getLogLevel();
     188        Logging.setLogLevel(logLevel);
     189        Main.info(tr("Log level is at ", logLevel));
     190
     191        Optional<String> language = args.getSingle(Option.LANGUAGE);
     192        I18n.set(language.orElse(null));
    327193
    328194        Policy.setPolicy(new Policy() {
     
    350216        Main.COMMAND_LINE_ARGS.addAll(Arrays.asList(argArray));
    351217
    352         if (args.containsKey(Option.VERSION)) {
     218        if (args.showVersion()) {
    353219            System.out.println(Version.getInstance().getAgentString());
    354220            System.exit(0);
    355         }
    356 
    357         boolean skipLoadingPlugins = false;
    358         if (args.containsKey(Option.SKIP_PLUGINS)) {
    359             skipLoadingPlugins = true;
    360             Main.info(tr("Plugin loading skipped"));
    361         }
    362 
    363         Main.pref.init(args.containsKey(Option.RESET_PREFERENCES));
    364 
    365         if (args.containsKey(Option.SET)) {
    366             for (String i : args.get(Option.SET)) {
    367                 String[] kv = i.split("=", 2);
    368                 Main.pref.put(kv[0], "null".equals(kv[1]) ? null : kv[1]);
    369             }
    370         }
    371 
    372         if (!languageGiven) {
    373             I18n.set(Main.pref.get("language", null));
    374         }
    375         Main.pref.updateSystemProperties();
    376 
    377         checkIPv6();
    378 
    379         // asking for help? show help and exit
    380         if (args.containsKey(Option.HELP)) {
     221        } else if (args.showHelp()) {
    381222            showHelp();
    382223            System.exit(0);
    383224        }
    384225
     226        boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
     227        if (skipLoadingPlugins) {
     228            Main.info(tr("Plugin loading skipped"));
     229        }
     230
     231        if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
     232            // Enable debug in OAuth signpost via system preference, but only at trace level
     233            Utils.updateSystemProperty("debug", "true");
     234            Main.info(tr("Enabled detailed debug level (trace)"));
     235        }
     236
     237        Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
     238
     239        args.getPreferencesToSet().forEach(Main.pref::put);
     240
     241        if (!language.isPresent()) {
     242            I18n.set(Main.pref.get("language", null));
     243        }
     244        Main.pref.updateSystemProperties();
     245
     246        checkIPv6();
     247
     248        // asking for help? show help and exit
     249        if (args.hasOption(Option.HELP)) {
     250            showHelp();
     251            System.exit(0);
     252        }
     253
    385254        processOffline(args);
    386255
     
    392261
    393262        WindowGeometry geometry = WindowGeometry.mainWindow("gui.geometry",
    394                 args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null,
    395                 !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
     263                args.getSingle(Option.GEOMETRY).orElse(null),
     264                !args.hasOption(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
    396265        final MainFrame mainFrame = new MainFrame(contentPanePrivate, mainPanel, geometry);
    397266        Main.parent = mainFrame;
    398267
    399         if (args.containsKey(Option.LOAD_PREFERENCES)) {
     268        if (args.hasOption(Option.LOAD_PREFERENCES)) {
    400269            CustomConfigurator.XMLCommandProcessor config = new CustomConfigurator.XMLCommandProcessor(Main.pref);
    401270            for (String i : args.get(Option.LOAD_PREFERENCES)) {
     
    404273                    config.openAndReadXML(is);
    405274                } catch (IOException ex) {
    406                     throw new RuntimeException(ex);
     275                    throw BugReport.intercept(ex).put("file", i);
    407276                }
    408277            }
     
    467336
    468337        boolean maximized = Main.pref.getBoolean("gui.maximized", false);
    469         if ((!args.containsKey(Option.NO_MAXIMIZE) && maximized) || args.containsKey(Option.MAXIMIZE)) {
     338        if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
    470339            mainFrame.setMaximized(true);
    471340        }
     
    525394    }
    526395
    527     private static void processOffline(Map<Option, Collection<String>> args) {
    528         if (args.containsKey(Option.OFFLINE)) {
    529             for (String s : args.get(Option.OFFLINE).iterator().next().split(",")) {
     396    private static void processOffline(ProgramArguments args) {
     397        for (String offlineNames : args.get(Option.OFFLINE)) {
     398            for (String s : offlineNames.split(",")) {
    530399                try {
    531400                    Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
     
    537406                }
    538407            }
    539             Set<OnlineResource> offline = Main.getOfflineResources();
    540             if (!offline.isEmpty()) {
    541                 Main.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
    542                         "JOSM is running in offline mode. These resources will not be available: {0}",
    543                         offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
    544             }
     408        }
     409        Set<OnlineResource> offline = Main.getOfflineResources();
     410        if (!offline.isEmpty()) {
     411            Main.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
     412                    "JOSM is running in offline mode. These resources will not be available: {0}",
     413                    offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
    545414        }
    546415    }
     
    597466    private static class GuiFinalizationWorker implements Runnable {
    598467
    599         private final Map<Option, Collection<String>> args;
     468        private final ProgramArguments args;
    600469        private final DefaultProxySelector proxySelector;
    601470
    602         GuiFinalizationWorker(Map<Option, Collection<String>> args, DefaultProxySelector proxySelector) {
     471        GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
    603472            this.args = args;
    604473            this.proxySelector = proxySelector;
Note: See TracChangeset for help on using the changeset viewer.