Changeset 12633 in josm


Ignore:
Timestamp:
2017-08-24T12:09:39+02:00 (7 years ago)
Author:
Don-vip
Message:

see #15182 - move GUI program arguments management from Main to gui.MainApplication

Location:
trunk
Files:
1 added
5 edited

Legend:

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

    r12631 r12633  
    66import java.awt.Component;
    77import java.awt.GraphicsEnvironment;
    8 import java.io.File;
    98import java.io.IOException;
    109import java.lang.ref.WeakReference;
    11 import java.net.URI;
    12 import java.net.URISyntaxException;
    1310import java.net.URL;
    1411import java.text.MessageFormat;
     
    2522import java.util.Objects;
    2623import java.util.Set;
    27 import java.util.StringTokenizer;
    2824import java.util.concurrent.Callable;
    2925import java.util.concurrent.ExecutionException;
     
    3531import javax.swing.InputMap;
    3632import javax.swing.JComponent;
    37 import javax.swing.JOptionPane;
    3833import javax.swing.KeyStroke;
    3934import javax.swing.LookAndFeel;
     
    4237
    4338import org.openstreetmap.josm.actions.JosmAction;
    44 import org.openstreetmap.josm.actions.OpenFileAction;
    45 import org.openstreetmap.josm.actions.OpenLocationAction;
    46 import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
    47 import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
    48 import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
    49 import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
    5039import org.openstreetmap.josm.actions.mapmode.DrawAction;
    51 import org.openstreetmap.josm.actions.search.SearchAction;
    5240import org.openstreetmap.josm.data.Bounds;
    5341import org.openstreetmap.josm.data.Preferences;
     
    5543import org.openstreetmap.josm.data.cache.JCSCacheManager;
    5644import org.openstreetmap.josm.data.coor.CoordinateFormat;
    57 import org.openstreetmap.josm.data.coor.LatLon;
    5845import org.openstreetmap.josm.data.osm.DataSet;
    5946import org.openstreetmap.josm.data.osm.OsmPrimitive;
     
    6552import org.openstreetmap.josm.gui.MapFrame;
    6653import org.openstreetmap.josm.gui.MapFrameListener;
    67 import org.openstreetmap.josm.gui.ProgramArguments;
    68 import org.openstreetmap.josm.gui.ProgramArguments.Option;
    6954import org.openstreetmap.josm.gui.io.SaveLayersDialog;
    7055import org.openstreetmap.josm.gui.layer.MainLayerManager;
     
    8671import org.openstreetmap.josm.tools.JosmRuntimeException;
    8772import org.openstreetmap.josm.tools.Logging;
    88 import org.openstreetmap.josm.tools.OsmUrlToBounds;
    8973import org.openstreetmap.josm.tools.PlatformHook;
    9074import org.openstreetmap.josm.tools.PlatformHookOsx;
     
    841825
    842826    /**
    843      * Handle command line instructions after GUI has been initialized.
    844      * @param args program arguments
    845      * @return the list of submitted tasks
    846      */
    847     protected static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
    848         List<Future<?>> tasks = new ArrayList<>();
    849         List<File> fileList = new ArrayList<>();
    850         for (String s : args.get(Option.DOWNLOAD)) {
    851             tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
    852         }
    853         if (!fileList.isEmpty()) {
    854             tasks.add(OpenFileAction.openFiles(fileList, true));
    855         }
    856         for (String s : args.get(Option.DOWNLOADGPS)) {
    857             tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
    858         }
    859         final Collection<String> selectionArguments = args.get(Option.SELECTION);
    860         if (!selectionArguments.isEmpty()) {
    861             tasks.add(Main.worker.submit(() -> {
    862                 for (String s : selectionArguments) {
    863                     SearchAction.search(s, SearchAction.SearchMode.add);
    864                 }
    865             }));
    866         }
    867         return tasks;
    868     }
    869 
    870     /**
    871827     * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
    872828     * If there are some unsaved data layers, asks first for user confirmation.
     
    914870            ImageProvider.shutdown(true);
    915871        }
    916     }
    917 
    918     /**
    919      * The type of a command line parameter, to be used in switch statements.
    920      * @see #paramType
    921      */
    922     enum DownloadParamType {
    923         httpUrl {
    924             @Override
    925             List<Future<?>> download(String s, Collection<File> fileList) {
    926                 return new OpenLocationAction().openUrl(false, s);
    927             }
    928 
    929             @Override
    930             List<Future<?>> downloadGps(String s) {
    931                 final Bounds b = OsmUrlToBounds.parse(s);
    932                 if (b == null) {
    933                     JOptionPane.showMessageDialog(
    934                             Main.parent,
    935                             tr("Ignoring malformed URL: \"{0}\"", s),
    936                             tr("Warning"),
    937                             JOptionPane.WARNING_MESSAGE
    938                     );
    939                     return Collections.emptyList();
    940                 }
    941                 return downloadFromParamBounds(true, b);
    942             }
    943         }, fileUrl {
    944             @Override
    945             List<Future<?>> download(String s, Collection<File> fileList) {
    946                 File f = null;
    947                 try {
    948                     f = new File(new URI(s));
    949                 } catch (URISyntaxException e) {
    950                     Logging.warn(e);
    951                     JOptionPane.showMessageDialog(
    952                             Main.parent,
    953                             tr("Ignoring malformed file URL: \"{0}\"", s),
    954                             tr("Warning"),
    955                             JOptionPane.WARNING_MESSAGE
    956                     );
    957                 }
    958                 if (f != null) {
    959                     fileList.add(f);
    960                 }
    961                 return Collections.emptyList();
    962             }
    963         }, bounds {
    964 
    965             /**
    966              * Download area specified on the command line as bounds string.
    967              * @param rawGps Flag to download raw GPS tracks
    968              * @param s The bounds parameter
    969              * @return the complete download task (including post-download handler), or {@code null}
    970              */
    971             private List<Future<?>> downloadFromParamBounds(final boolean rawGps, String s) {
    972                 final StringTokenizer st = new StringTokenizer(s, ",");
    973                 if (st.countTokens() == 4) {
    974                     return Main.downloadFromParamBounds(rawGps, new Bounds(
    975                             new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())),
    976                             new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))
    977                     ));
    978                 }
    979                 return Collections.emptyList();
    980             }
    981 
    982             @Override
    983             List<Future<?>> download(String param, Collection<File> fileList) {
    984                 return downloadFromParamBounds(false, param);
    985             }
    986 
    987             @Override
    988             List<Future<?>> downloadGps(String param) {
    989                 return downloadFromParamBounds(true, param);
    990             }
    991         }, fileName {
    992             @Override
    993             List<Future<?>> download(String s, Collection<File> fileList) {
    994                 fileList.add(new File(s));
    995                 return Collections.emptyList();
    996             }
    997         };
    998 
    999         /**
    1000          * Performs the download
    1001          * @param param represents the object to be downloaded
    1002          * @param fileList files which shall be opened, should be added to this collection
    1003          * @return the download task, or {@code null}
    1004          */
    1005         abstract List<Future<?>> download(String param, Collection<File> fileList);
    1006 
    1007         /**
    1008          * Performs the GPS download
    1009          * @param param represents the object to be downloaded
    1010          * @return the download task, or {@code null}
    1011          */
    1012         List<Future<?>> downloadGps(String param) {
    1013             if (!GraphicsEnvironment.isHeadless()) {
    1014                 JOptionPane.showMessageDialog(
    1015                         Main.parent,
    1016                         tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
    1017                         tr("Warning"),
    1018                         JOptionPane.WARNING_MESSAGE
    1019                 );
    1020             }
    1021             return Collections.emptyList();
    1022         }
    1023 
    1024         /**
    1025          * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
    1026          *
    1027          * @param s A parameter string
    1028          * @return The guessed parameter type
    1029          */
    1030         static DownloadParamType paramType(String s) {
    1031             if (s.startsWith("http:") || s.startsWith("https:")) return DownloadParamType.httpUrl;
    1032             if (s.startsWith("file:")) return DownloadParamType.fileUrl;
    1033             String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
    1034             if (s.matches(coorPattern + "(," + coorPattern + "){3}")) return DownloadParamType.bounds;
    1035             // everything else must be a file name
    1036             return DownloadParamType.fileName;
    1037         }
    1038     }
    1039 
    1040     /**
    1041      * Download area specified as Bounds value.
    1042      * @param rawGps Flag to download raw GPS tracks
    1043      * @param b The bounds value
    1044      * @return the complete download task (including post-download handler)
    1045      */
    1046     private static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
    1047         DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
    1048         // asynchronously launch the download task ...
    1049         Future<?> future = task.download(true, b, null);
    1050         // ... and the continuation when the download is finished (this will wait for the download to finish)
    1051         return Collections.singletonList(Main.worker.submit(new PostDownloadHandler(task, future)));
    1052872    }
    1053873
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r12631 r12633  
    3636import java.util.TreeSet;
    3737import java.util.concurrent.Callable;
     38import java.util.concurrent.Future;
    3839import java.util.logging.Level;
    3940import java.util.stream.Collectors;
     
    4950import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
    5051import org.openstreetmap.josm.Main;
     52import org.openstreetmap.josm.actions.OpenFileAction;
    5153import org.openstreetmap.josm.actions.PreferencesAction;
    5254import org.openstreetmap.josm.actions.RestartAction;
     55import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
     56import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
     57import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
     58import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
    5359import org.openstreetmap.josm.actions.mapmode.DrawAction;
     60import org.openstreetmap.josm.actions.search.SearchAction;
    5461import org.openstreetmap.josm.data.AutosaveTask;
    5562import org.openstreetmap.josm.data.Bounds;
     
    653660    }
    654661
     662    /**
     663     * Download area specified as Bounds value.
     664     * @param rawGps Flag to download raw GPS tracks
     665     * @param b The bounds value
     666     * @return the complete download task (including post-download handler)
     667     */
     668    static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
     669        DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
     670        // asynchronously launch the download task ...
     671        Future<?> future = task.download(true, b, null);
     672        // ... and the continuation when the download is finished (this will wait for the download to finish)
     673        return Collections.singletonList(Main.worker.submit(new PostDownloadHandler(task, future)));
     674    }
     675
     676    /**
     677     * Handle command line instructions after GUI has been initialized.
     678     * @param args program arguments
     679     * @return the list of submitted tasks
     680     */
     681    static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
     682        List<Future<?>> tasks = new ArrayList<>();
     683        List<File> fileList = new ArrayList<>();
     684        for (String s : args.get(Option.DOWNLOAD)) {
     685            tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
     686        }
     687        if (!fileList.isEmpty()) {
     688            tasks.add(OpenFileAction.openFiles(fileList, true));
     689        }
     690        for (String s : args.get(Option.DOWNLOADGPS)) {
     691            tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
     692        }
     693        final Collection<String> selectionArguments = args.get(Option.SELECTION);
     694        if (!selectionArguments.isEmpty()) {
     695            tasks.add(Main.worker.submit(() -> {
     696                for (String s : selectionArguments) {
     697                    SearchAction.search(s, SearchAction.SearchMode.add);
     698                }
     699            }));
     700        }
     701        return tasks;
     702    }
     703
    655704    private static class GuiFinalizationWorker implements Runnable {
    656705
  • trunk/src/org/openstreetmap/josm/gui/ProgramArguments.java

    r11986 r12633  
    2020
    2121/**
    22  * This class holds the arguments passed on to Main.
     22 * This class holds the arguments passed on to {@link MainApplication#main}.
    2323 * @author Michael Zangl
    2424 * @since 10899
  • trunk/test/unit/org/openstreetmap/josm/MainTest.java

    r12632 r12633  
    1111import java.net.MalformedURLException;
    1212import java.net.URL;
    13 import java.nio.file.Paths;
    1413import java.util.Collection;
    15 import java.util.List;
    1614import java.util.Map;
    17 import java.util.concurrent.ExecutionException;
    18 import java.util.concurrent.Future;
    1915
    2016import javax.swing.UIManager;
     
    2218import org.junit.Rule;
    2319import org.junit.Test;
    24 import org.openstreetmap.josm.Main.DownloadParamType;
    2520import org.openstreetmap.josm.Main.InitStatusListener;
    2621import org.openstreetmap.josm.Main.InitializationTask;
    2722import org.openstreetmap.josm.actions.AboutAction;
    28 import org.openstreetmap.josm.data.osm.DataSet;
     23import org.openstreetmap.josm.gui.DownloadParamType;
    2924import org.openstreetmap.josm.gui.MapFrameListener;
    30 import org.openstreetmap.josm.gui.ProgramArguments;
    31 import org.openstreetmap.josm.gui.layer.GpxLayer;
    3225import org.openstreetmap.josm.io.OnlineResource;
    3326import org.openstreetmap.josm.testutils.JOSMTestRules;
    34 import org.openstreetmap.josm.tools.Logging;
    3527import org.openstreetmap.josm.tools.Shortcut;
    3628
     
    10597        assertEquals(Main.pref.get("laf", Main.platform.getDefaultStyle()), UIManager.getLookAndFeel().getClass().getCanonicalName());
    10698        assertNotNull(Main.toolbar);
    107     }
    108 
    109     /**
    110      * Unit test of {@link Main#postConstructorProcessCmdLine} - empty case.
    111      */
    112     @Test
    113     public void testPostConstructorProcessCmdLineEmpty() {
    114         // Check the method accepts no arguments
    115         Main.postConstructorProcessCmdLine(new ProgramArguments(new String[0]));
    116     }
    117 
    118     private static void doTestPostConstructorProcessCmdLine(String download, String downloadGps, boolean gpx) {
    119         assertNull(Main.getLayerManager().getEditDataSet());
    120         for (Future<?> f : Main.postConstructorProcessCmdLine(new ProgramArguments(new String[]{
    121                 "--download=" + download,
    122                 "--downloadgps=" + downloadGps,
    123                 "--selection=type: node"}))) {
    124             try {
    125                 f.get();
    126             } catch (InterruptedException | ExecutionException e) {
    127                 Logging.error(e);
    128             }
    129         }
    130         DataSet ds = Main.getLayerManager().getEditDataSet();
    131         assertNotNull(ds);
    132         assertFalse(ds.getSelected().isEmpty());
    133         Main.getLayerManager().removeLayer(Main.getLayerManager().getEditLayer());
    134         if (gpx) {
    135             List<GpxLayer> gpxLayers = Main.getLayerManager().getLayersOfType(GpxLayer.class);
    136             assertEquals(1, gpxLayers.size());
    137             Main.getLayerManager().removeLayer(gpxLayers.iterator().next());
    138         }
    139     }
    140 
    141     /**
    142      * Unit test of {@link Main#postConstructorProcessCmdLine} - nominal case with bounds.
    143      * This test assumes the DEV API contains nodes around 0,0 and GPX tracks around London
    144      */
    145     @Test
    146     public void testPostConstructorProcessCmdLineBounds() {
    147         doTestPostConstructorProcessCmdLine(
    148                 "0.01,0.01,0.05,0.05",
    149                 "51.35,-0.4,51.60,0.2", true);
    150     }
    151 
    152     /**
    153      * Unit test of {@link Main#postConstructorProcessCmdLine} - nominal case with http/https URLs.
    154      * This test assumes the DEV API contains nodes around 0,0 and GPX tracks around London
    155      */
    156     @Test
    157     public void testPostConstructorProcessCmdLineHttpUrl() {
    158         doTestPostConstructorProcessCmdLine(
    159                 "http://api06.dev.openstreetmap.org/api/0.6/map?bbox=0.01,0.01,0.05,0.05",
    160                 "https://master.apis.dev.openstreetmap.org/api/0.6/trackpoints?bbox=-0.4,51.35,0.2,51.6&page=0", true);
    161     }
    162 
    163     /**
    164      * Unit test of {@link Main#postConstructorProcessCmdLine} - nominal case with file URLs.
    165      * @throws MalformedURLException if an error occurs
    166      */
    167     @Test
    168     public void testPostConstructorProcessCmdLineFileUrl() throws MalformedURLException {
    169         doTestPostConstructorProcessCmdLine(
    170                 Paths.get(TestUtils.getTestDataRoot() + "multipolygon.osm").toUri().toURL().toExternalForm(),
    171                 Paths.get(TestUtils.getTestDataRoot() + "minimal.gpx").toUri().toURL().toExternalForm(), false);
    172     }
    173 
    174     /**
    175      * Unit test of {@link Main#postConstructorProcessCmdLine} - nominal case with file names.
    176      * @throws MalformedURLException if an error occurs
    177      */
    178     @Test
    179     public void testPostConstructorProcessCmdLineFilename() throws MalformedURLException {
    180         doTestPostConstructorProcessCmdLine(
    181                 Paths.get(TestUtils.getTestDataRoot() + "multipolygon.osm").toFile().getAbsolutePath(),
    182                 Paths.get(TestUtils.getTestDataRoot() + "minimal.gpx").toFile().getAbsolutePath(), false);
    183     }
    184 
    185     /**
    186      * Unit test of {@link DownloadParamType} enum.
    187      */
    188     @Test
    189     public void testEnumDownloadParamType() {
    190         TestUtils.superficialEnumCodeCoverage(DownloadParamType.class);
    19199    }
    192100
  • trunk/test/unit/org/openstreetmap/josm/gui/MainApplicationTest.java

    r12632 r12633  
    33
    44import static org.junit.Assert.assertEquals;
     5import static org.junit.Assert.assertFalse;
    56import static org.junit.Assert.assertNotNull;
    67import static org.junit.Assert.assertNull;
     
    910import java.io.IOException;
    1011import java.io.PrintStream;
     12import java.net.MalformedURLException;
    1113import java.nio.charset.StandardCharsets;
     14import java.nio.file.Paths;
    1215import java.util.Arrays;
    1316import java.util.Collection;
     17import java.util.List;
     18import java.util.concurrent.ExecutionException;
     19import java.util.concurrent.Future;
    1420
    1521import org.junit.Rule;
    1622import org.junit.Test;
     23import org.openstreetmap.josm.Main;
     24import org.openstreetmap.josm.TestUtils;
    1725import org.openstreetmap.josm.data.Version;
     26import org.openstreetmap.josm.data.osm.DataSet;
    1827import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
     28import org.openstreetmap.josm.gui.layer.GpxLayer;
    1929import org.openstreetmap.josm.plugins.PluginHandler;
    2030import org.openstreetmap.josm.plugins.PluginHandlerTestIT;
     
    2333import org.openstreetmap.josm.plugins.PluginListParser;
    2434import org.openstreetmap.josm.testutils.JOSMTestRules;
     35import org.openstreetmap.josm.tools.Logging;
    2536
    2637import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
     
    113124                "");
    114125    }
     126
     127    /**
     128     * Unit test of {@link MainApplication#postConstructorProcessCmdLine} - empty case.
     129     */
     130    @Test
     131    public void testPostConstructorProcessCmdLineEmpty() {
     132        // Check the method accepts no arguments
     133        MainApplication.postConstructorProcessCmdLine(new ProgramArguments(new String[0]));
     134    }
     135
     136    private static void doTestPostConstructorProcessCmdLine(String download, String downloadGps, boolean gpx) {
     137        assertNull(Main.getLayerManager().getEditDataSet());
     138        for (Future<?> f : MainApplication.postConstructorProcessCmdLine(new ProgramArguments(new String[]{
     139                "--download=" + download,
     140                "--downloadgps=" + downloadGps,
     141                "--selection=type: node"}))) {
     142            try {
     143                f.get();
     144            } catch (InterruptedException | ExecutionException e) {
     145                Logging.error(e);
     146            }
     147        }
     148        DataSet ds = Main.getLayerManager().getEditDataSet();
     149        assertNotNull(ds);
     150        assertFalse(ds.getSelected().isEmpty());
     151        Main.getLayerManager().removeLayer(Main.getLayerManager().getEditLayer());
     152        if (gpx) {
     153            List<GpxLayer> gpxLayers = Main.getLayerManager().getLayersOfType(GpxLayer.class);
     154            assertEquals(1, gpxLayers.size());
     155            Main.getLayerManager().removeLayer(gpxLayers.iterator().next());
     156        }
     157    }
     158
     159    /**
     160     * Unit test of {@link MainApplication#postConstructorProcessCmdLine} - nominal case with bounds.
     161     * This test assumes the DEV API contains nodes around 0,0 and GPX tracks around London
     162     */
     163    @Test
     164    public void testPostConstructorProcessCmdLineBounds() {
     165        doTestPostConstructorProcessCmdLine(
     166                "0.01,0.01,0.05,0.05",
     167                "51.35,-0.4,51.60,0.2", true);
     168    }
     169
     170    /**
     171     * Unit test of {@link MainApplication#postConstructorProcessCmdLine} - nominal case with http/https URLs.
     172     * This test assumes the DEV API contains nodes around 0,0 and GPX tracks around London
     173     */
     174    @Test
     175    public void testPostConstructorProcessCmdLineHttpUrl() {
     176        doTestPostConstructorProcessCmdLine(
     177                "http://api06.dev.openstreetmap.org/api/0.6/map?bbox=0.01,0.01,0.05,0.05",
     178                "https://master.apis.dev.openstreetmap.org/api/0.6/trackpoints?bbox=-0.4,51.35,0.2,51.6&page=0", true);
     179    }
     180
     181    /**
     182     * Unit test of {@link MainApplication#postConstructorProcessCmdLine} - nominal case with file URLs.
     183     * @throws MalformedURLException if an error occurs
     184     */
     185    @Test
     186    public void testPostConstructorProcessCmdLineFileUrl() throws MalformedURLException {
     187        doTestPostConstructorProcessCmdLine(
     188                Paths.get(TestUtils.getTestDataRoot() + "multipolygon.osm").toUri().toURL().toExternalForm(),
     189                Paths.get(TestUtils.getTestDataRoot() + "minimal.gpx").toUri().toURL().toExternalForm(), false);
     190    }
     191
     192    /**
     193     * Unit test of {@link MainApplication#postConstructorProcessCmdLine} - nominal case with file names.
     194     * @throws MalformedURLException if an error occurs
     195     */
     196    @Test
     197    public void testPostConstructorProcessCmdLineFilename() throws MalformedURLException {
     198        doTestPostConstructorProcessCmdLine(
     199                Paths.get(TestUtils.getTestDataRoot() + "multipolygon.osm").toFile().getAbsolutePath(),
     200                Paths.get(TestUtils.getTestDataRoot() + "minimal.gpx").toFile().getAbsolutePath(), false);
     201    }
     202
     203    /**
     204     * Unit test of {@link DownloadParamType} enum.
     205     */
     206    @Test
     207    public void testEnumDownloadParamType() {
     208        TestUtils.superficialEnumCodeCoverage(DownloadParamType.class);
     209    }
    115210}
Note: See TracChangeset for help on using the changeset viewer.