Changeset 92 in josm for src


Ignore:
Timestamp:
2006-04-22T18:50:21+02:00 (18 years ago)
Author:
imi
Message:
  • added progress bar and cancel button to all down-/uploads
  • added url loading via command line
  • added --selection=... loading of selections via command line
Location:
src/org/openstreetmap/josm
Files:
2 added
12 edited
1 moved

Legend:

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

    r90 r92  
    1 // Licence: GPL
     1//Licence: GPL
    22package org.openstreetmap.josm;
    33
     
    1111import java.io.IOException;
    1212import java.util.Arrays;
    13 import java.util.Iterator;
    1413import java.util.LinkedList;
    1514import java.util.StringTokenizer;
     
    3938import org.openstreetmap.josm.actions.UndoAction;
    4039import org.openstreetmap.josm.actions.UploadAction;
     40import org.openstreetmap.josm.data.Bounds;
    4141import org.openstreetmap.josm.data.Preferences;
    4242import org.openstreetmap.josm.data.osm.DataSet;
     
    4545import org.openstreetmap.josm.gui.MapFrame;
    4646import org.openstreetmap.josm.gui.ShowModifiers;
     47import org.openstreetmap.josm.gui.dialogs.SelectionListDialog;
    4748import org.openstreetmap.josm.gui.layer.Layer;
    4849import org.openstreetmap.josm.gui.layer.OsmDataLayer;
     
    6869         */
    6970        public static Executor worker = Executors.newSingleThreadExecutor();
    70        
    71        
     71
     72
    7273        public static Projection proj;
    7374
     
    8182         */
    8283        public static DataSet ds = new DataSet();
    83        
     84
    8485        /**
    8586         * The main panel.
     
    9697        private OpenAction openAction;
    9798        private DownloadAction downloadAction;
    98     //private Action wmsServerAction;
    99        
     99        //private Action wmsServerAction;
     100
    100101        /**
    101102         * Construct an main frame, ready sized and operating. Does not
     
    110111                setSize(1000,740); // some strange default size
    111112                setVisible(true);
    112                
     113
    113114                downloadAction = new DownloadAction();
    114115                Action uploadAction = new UploadAction();
    115116                //wmsServerAction = new WmsServerAction();
    116         openAction = new OpenAction();
     117                openAction = new OpenAction();
    117118                Action saveAction = new SaveAction();
    118119                Action gpxExportAction = new GpxExportAction(null);
     
    136137                mainMenu.add(fileMenu);
    137138
    138                
     139
    139140                JMenu layerMenu = new JMenu("Layer");
    140141                layerMenu.setMnemonic('L');
    141142                layerMenu.add(downloadAction);
    142143                layerMenu.add(uploadAction);
    143         layerMenu.addSeparator();
    144         //layerMenu.add(new JCheckBoxMenuItem(wmsServerAction));
     144                layerMenu.addSeparator();
     145                //layerMenu.add(new JCheckBoxMenuItem(wmsServerAction));
    145146                mainMenu.add(layerMenu);
    146                
     147
    147148                JMenu editMenu = new JMenu("Edit");
    148149                editMenu.setMnemonic('E');
     
    152153                editMenu.add(preferencesAction);
    153154                mainMenu.add(editMenu);
    154                
     155
    155156                mainMenu.add(new JSeparator());
    156157                JMenu helpMenu = new JMenu("Help");
     
    174175                toolBar.addSeparator();
    175176                toolBar.add(preferencesAction);
    176                
     177
    177178                getContentPane().add(toolBar, BorderLayout.NORTH);
    178        
     179
    179180                addWindowListener(new WindowAdapter(){
    180181                        @Override public void windowClosing(WindowEvent arg0) {
     
    214215                LinkedList<String> arguments = new LinkedList<String>(Arrays.asList(args));
    215216
    216                 if (arguments.contains("--help")) {
     217                if (arguments.contains("--help") || arguments.contains("-?") || arguments.contains("-h")) {
    217218                        System.out.println("Java OpenStreetMap Editor");
    218219                        System.out.println();
    219220                        System.out.println("usage:");
    220                         System.out.println("\tjava -jar josm.jar <options> file file file...");
     221                        System.out.println("\tjava -jar josm.jar <option> <option> <option>...");
    221222                        System.out.println();
    222223                        System.out.println("options:");
    223                         System.out.println("\t--help                                  Show this help");
    224                         System.out.println("\t--geometry=widthxheight(+|-)x(+|-)y     Standard unix geometry argument");
    225                         System.out.println("\t--download=minlat,minlon,maxlat,maxlon  Download the bounding box");
    226                         System.out.println("\t--no-fullscreen                         Don't launch in fullscreen mode");
    227                         System.out.println("\t--reset-preferences                     Reset the preferences to default");
    228                         System.out.println("file(.osm|.xml|.gpx|.txt|.csv)            Open the specific file");
     224                        System.out.println("\t--help|-?|-h                              Show this help");
     225                        System.out.println("\t--geometry=widthxheight(+|-)x(+|-)y       Standard unix geometry argument");
     226                        System.out.println("\t--download=minlat,minlon,maxlat,maxlon    Download the bounding box");
     227                        System.out.println("\t--downloadgps=minlat,minlon,maxlat,maxlon Download the bounding box");
     228                        System.out.println("\t--selection=<searchstring>                Select with the given search");
     229                        System.out.println("\t--no-fullscreen                           Don't launch in fullscreen mode");
     230                        System.out.println("\t--reset-preferences                       Reset the preferences to default");
     231                        System.out.println("\tURL|filename(.osm|.xml|.gpx|.txt|.csv)    Open file / Download url");
     232                        System.out.println();
     233                        System.out.println("examples:");
     234                        System.out.println("\tjava -jar josm.jar track1.gpx track2.gpx london.osm");
     235                        System.out.println("\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13");
     236                        System.out.println("\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml");
     237                        System.out.println("\tjava -jar josm.jar osm://43.2,11.1,43.4,11.4");
     238                        System.out.println();
     239                        System.out.println("Parameters are read in the order they are specified, so make sure you load");
     240                        System.out.println("some data before --selection");
     241                        System.out.println();
     242                        System.out.println("Instead of --download=<bbox> you may specify osm://<bbox>");
    229243                        System.exit(0);
    230244                }
     
    260274                        proj = new Epsg4326();
    261275                }
    262                
     276
    263277                try {
    264278                        UIManager.setLookAndFeel(pref.get("laf"));
     
    266280                        e.printStackTrace();
    267281                }
    268                
     282
    269283                new Main();
    270284                main.setVisible(true);
     
    279293                }
    280294
    281                 for (Iterator<String> it = arguments.iterator(); it.hasNext();) {
    282                         String s = it.next();
    283                         if (s.startsWith("--download=")) {
    284                                 downloadFromParamString(false, s.substring(11));
    285                                 it.remove();
     295                boolean showModifiers = false;
     296
     297                for (String s : arguments) {
     298                        if (s.startsWith("--download=") || s.startsWith("osm:")) {
     299                                downloadFromParamString(false, s);
    286300                        } else if (s.startsWith("--downloadgps=")) {
    287                                 downloadFromParamString(true, s.substring(14));
    288                                 it.remove();
     301                                downloadFromParamString(true, s);
    289302                        } else if (s.startsWith("--geometry=")) {
    290303                                Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(s.substring(11));
     
    305318                                } else
    306319                                        System.out.println("Ignoring malformed geometry: "+s.substring(11));
    307                                 it.remove();
     320                        } else if (s.equals("--show-modifiers")) {
     321                                showModifiers = true;
     322                        } else if (s.startsWith("--selection=")) {
     323                                SelectionListDialog.search(s.substring(12), SelectionListDialog.SearchMode.add);
     324                        } else if (s.startsWith("http:") || s.startsWith("ftp:") || s.startsWith("https:")) {
     325                                Bounds b = DownloadAction.osmurl2bounds(s);
     326                                if (b == null)
     327                                        System.out.println("Ignoring malformed url: "+s);
     328                                else
     329                                        Main.main.downloadAction.download(false, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
     330                        } else {
     331                                main.openAction.openFile(new File(s));
    308332                        }
    309333                }
    310334
    311                 if (arguments.remove("--show-modifiers")) {
     335                if (showModifiers) {
    312336                        Point p = main.getLocationOnScreen();
    313337                        Dimension s = main.getSize();
     
    315339                        main.setVisible(true);
    316340                }
    317 
    318                 for (String s : arguments)
    319                         main.openAction.openFile(new File(s));
    320341        }
    321342
    322343
    323344        private static void downloadFromParamString(boolean rawGps, String s) {
     345                s = s.replaceAll("^(osm:/?/?)|(--download(gps)?=)", "");
     346                System.out.println(s);
     347                System.exit(1);
    324348                StringTokenizer st = new StringTokenizer(s, ",");
    325349                if (st.countTokens() != 4) {
    326                         JOptionPane.showMessageDialog(main, "Download option does not take "+st.countTokens()+" bounding parameter.");
     350                        JOptionPane.showMessageDialog(main, "Malformed bounding box: "+s);
    327351                        return;
    328352                }
     
    355379        }
    356380
    357        
     381
    358382        /**
    359383         * Sets some icons to the ui.
  • src/org/openstreetmap/josm/actions/DownloadAction.java

    r86 r92  
    1313import java.util.Collection;
    1414import java.util.HashMap;
    15 import java.util.Map;
    1615
    1716import javax.swing.DefaultListModel;
     
    3635import org.openstreetmap.josm.gui.MapFrame;
    3736import org.openstreetmap.josm.gui.MapView;
     37import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    3838import org.openstreetmap.josm.gui.WorldChooser;
    3939import org.openstreetmap.josm.gui.BookmarkList.Bookmark;
     
    6060         * Run in the worker thread.
    6161         */
    62     private final class DownloadOsmTask extends PleaseWaitRunnable {
    63             private final OsmServerReader reader;
     62        private final class DownloadOsmTask extends PleaseWaitRunnable {
     63                private final OsmServerReader reader;
    6464                private DataSet dataSet;
    6565
    66             private DownloadOsmTask(OsmServerReader reader) {
    67                     super("Downloading data");
    68                     this.reader = reader;
    69             }
    70 
    71             @Override public void realRun() throws IOException, SAXException {
    72                 dataSet = reader.parseOsm();
    73                 if (dataSet == null)
    74                         return;
    75                 if (dataSet.nodes.isEmpty())
    76                         JOptionPane.showMessageDialog(Main.main, "No data imported.");
    77             }
     66                private DownloadOsmTask(OsmServerReader reader) {
     67                        super("Downloading data");
     68                        this.reader = reader;
     69                        reader.setProgressInformation(currentAction, progress);
     70                }
     71
     72                @Override public void realRun() throws IOException, SAXException {
     73                        dataSet = reader.parseOsm();
     74                        if (dataSet == null)
     75                                return;
     76                        if (dataSet.nodes.isEmpty())
     77                                JOptionPane.showMessageDialog(Main.main, "No data imported.");
     78                }
    7879
    7980                @Override protected void finish() {
     
    8182                                return; // user cancelled download or error occoured
    8283                        Layer layer = new OsmDataLayer(dataSet, "Data Layer", false);
    83                 if (Main.main.getMapFrame() == null)
    84                         Main.main.setMapFrame(new MapFrame(layer));
    85                 else
    86                         Main.main.getMapFrame().mapView.addLayer(layer);
    87                 }
    88            
    89     }
    90 
    91 
    92     private final class DownloadGpsTask extends PleaseWaitRunnable {
    93             private final OsmServerReader reader;
     84                        if (Main.main.getMapFrame() == null)
     85                                Main.main.setMapFrame(new MapFrame(layer));
     86                        else
     87                                Main.main.getMapFrame().mapView.addLayer(layer);
     88                }
     89
     90                @Override protected void cancel() {
     91                        reader.cancel();
     92                }
     93        }
     94
     95
     96        private final class DownloadGpsTask extends PleaseWaitRunnable {
     97                private final OsmServerReader reader;
    9498                private Collection<Collection<GpsPoint>> rawData;
    9599
    96             private DownloadGpsTask(OsmServerReader reader) {
    97                     super("Downloading GPS data");
    98                     this.reader = reader;
    99             }
    100 
    101             @Override public void realRun() throws IOException, JDOMException {
    102                 rawData = reader.parseRawGps();
    103             }
     100                private DownloadGpsTask(OsmServerReader reader) {
     101                        super("Downloading GPS data");
     102                        this.reader = reader;
     103                }
     104
     105                @Override public void realRun() throws IOException, JDOMException {
     106                        rawData = reader.parseRawGps();
     107                }
    104108
    105109                @Override protected void finish() {
     
    108112                        String name = latlon[0].getText() + " " + latlon[1].getText() + " x " + latlon[2].getText() + " " + latlon[3].getText();
    109113                        Layer layer = new RawGpsDataLayer(rawData, name);
    110                 if (Main.main.getMapFrame() == null)
    111                         Main.main.setMapFrame(new MapFrame(layer));
    112                 else
    113                         Main.main.getMapFrame().mapView.addLayer(layer);
    114                 }
    115            
    116     }
    117    
    118    
    119         /**
    120      * minlat, minlon, maxlat, maxlon
    121      */
     114                        if (Main.main.getMapFrame() == null)
     115                                Main.main.setMapFrame(new MapFrame(layer));
     116                        else
     117                                Main.main.getMapFrame().mapView.addLayer(layer);
     118                }
     119
     120                @Override protected void cancel() {
     121                }
     122        }
     123
     124
     125        /**
     126         * minlat, minlon, maxlat, maxlon
     127         */
    122128        JTextField[] latlon = new JTextField[]{
    123129                        new JTextField(9),
     
    136142
    137143        public void actionPerformed(ActionEvent e) {
    138                
    139144                String osmDataServer = Main.pref.get("osm-server.url");
    140145                //TODO: Remove this in later versions (temporary only)
     
    178183                }
    179184                dlg.add(rawGps, GBC.eop());
    180                
     185
    181186                // OSM url edit
    182187                dlg.add(new JLabel("URL from www.openstreetmap.org"), GBC.eol());
     
    221226                                SwingUtilities.invokeLater(new Runnable() {
    222227                                        public void run() {
    223                                                 Map<String, Double> map = readArgs(osmUrl.getText());
    224                                                 try {
    225                                                         double size = 180.0 / Math.pow(2, map.get("zoom"));
    226                                                         Bounds b = new Bounds(
    227                                                                         new LatLon(map.get("lat") - size/2, map.get("lon") - size),
    228                                                                         new LatLon(map.get("lat") + size/2, map.get("lon") + size));
     228                                                Bounds b = osmurl2bounds(osmUrl.getText());
     229                                                if (b != null)
    229230                                                        setEditBounds(b);
    230                                                 } catch (Exception x) { // NPE or IAE
     231                                                else
    231232                                                        for (JTextField f : latlon)
    232233                                                                f.setText("");
    233                                                 }
    234234                                        }
    235235                                });
    236236                        }
    237237                });
    238                
     238
    239239                // Bookmarks
    240240                dlg.add(new JLabel("Bookmarks"), GBC.eol());
     
    289289                wc.setPreferredSize(new Dimension(d.width, d.width/2));
    290290                wc.addInputFields(latlon, osmUrl, osmUrlRefresher);
    291                
     291
    292292                // Finally: the dialog
    293293                Bookmark b;
     
    330330                }
    331331        }
    332        
    333        
    334         /**
    335          * Extrakt URL arguments.
    336          */
    337         private Map<String, Double> readArgs(String s) {
    338                 int i = s.indexOf('?');
     332
     333
     334        public static Bounds osmurl2bounds(String url) {
     335                int i = url.indexOf('?');
    339336                if (i == -1)
    340                         return new HashMap<String, Double>();
    341                 String[] args = s.substring(i+1).split("&");
     337                        return null;
     338                String[] args = url.substring(i+1).split("&");
    342339                HashMap<String, Double> map = new HashMap<String, Double>();
    343340                for (String arg : args) {
     
    350347                        }
    351348                }
    352                 return map;
    353         }
    354        
     349                try {
     350                        double size = 180.0 / Math.pow(2, map.get("zoom"));
     351                        return new Bounds(
     352                                        new LatLon(map.get("lat") - size/2, map.get("lon") - size),
     353                                        new LatLon(map.get("lat") + size/2, map.get("lon") + size));
     354                } catch (Exception x) { // NPE or IAE
     355                        return null;
     356                }
     357        }
     358
    355359        /**
    356360         * Set the four edit fields to the given bounds coordinates.
  • src/org/openstreetmap/josm/actions/JosmAction.java

    r81 r92  
    11package org.openstreetmap.josm.actions;
    22
    3 import java.awt.EventQueue;
    4 import java.io.FileNotFoundException;
    5 import java.io.IOException;
    63
    74import javax.swing.AbstractAction;
    8 import javax.swing.BorderFactory;
    95import javax.swing.JComponent;
    10 import javax.swing.JDialog;
    11 import javax.swing.JLabel;
    12 import javax.swing.JOptionPane;
    136import javax.swing.KeyStroke;
    147
    15 import org.jdom.JDOMException;
    168import org.openstreetmap.josm.Main;
    179import org.openstreetmap.josm.tools.ImageProvider;
    18 import org.xml.sax.SAXException;
    1910
    2011/**
     
    2415abstract public class JosmAction extends AbstractAction {
    2516
    26         /**
    27          * Instanced of this thread will display a "Please Wait" message in middle of JOSM
    28          * to indicate a progress beeing executed.
    29          * 
    30          * @author Imi
    31          */
    32         protected abstract class PleaseWaitRunnable implements Runnable {
    33                 public final JDialog pleaseWaitDlg;
    34                 private String errorMessage;
    35                 /**
    36                  * Create the runnable object with a given message for the user.
    37                  */
    38                 public PleaseWaitRunnable(String msg) {
    39                         pleaseWaitDlg = new JDialog(Main.main, true);
    40                         pleaseWaitDlg.setUndecorated(true);
    41                         JLabel l = new JLabel(msg+". Please Wait.");
    42                         l.setBorder(BorderFactory.createCompoundBorder(
    43                                         BorderFactory.createEtchedBorder(),
    44                                         BorderFactory.createEmptyBorder(20,20,20,20)));
    45                         pleaseWaitDlg.getContentPane().add(l);
    46                         pleaseWaitDlg.pack();
    47                         pleaseWaitDlg.setLocationRelativeTo(Main.main);
    48                         pleaseWaitDlg.setResizable(false);
    49                 }
    50                 public final void run() {
    51                         try {
    52                                 realRun();
    53                 } catch (SAXException x) {
    54                         x.printStackTrace();
    55                         errorMessage = "Error while parsing: "+x.getMessage();
    56                 } catch (JDOMException x) {
    57                         x.printStackTrace();
    58                         errorMessage = "Error while parsing: "+x.getMessage();
    59                 } catch (FileNotFoundException x) {
    60                         x.printStackTrace();
    61                         errorMessage = "URL not found: " + x.getMessage();
    62                 } catch (IOException x) {
    63                         x.printStackTrace();
    64                         errorMessage = x.getMessage();
    65                         } finally {
    66                                 closeDialog();
    67                         }
    68                 }
    69                 /**
    70                  * Called in the worker thread to do the actual work. When any of the
    71                  * exception is thrown, a message box will be displayed and closeDialog
    72                  * is called. finish() is called in any case.
    73                  */
    74                 protected abstract void realRun() throws SAXException, JDOMException, IOException;
    75                 /**
    76                  * Finish up the data work. Is guaranteed to be called if realRun is called.
    77                  * Finish is called in the gui thread just after the dialog disappeared.
    78                  */
    79                 protected void finish() {}
    80                 /**
    81                  * Close the dialog. Usually called from worker thread.
    82                  */
    83                 public void closeDialog() {
    84                         EventQueue.invokeLater(new Runnable(){
    85                                 public void run() {
    86                                         finish();
    87                                         pleaseWaitDlg.setVisible(false);
    88                                         pleaseWaitDlg.dispose();
    89                                         if (errorMessage != null)
    90                                                 JOptionPane.showMessageDialog(Main.main, errorMessage);
    91                 }
    92                         });
    93                 }
    94         }
    95        
    9617        /**
    9718         * Construct the action as menu action entry.
  • src/org/openstreetmap/josm/actions/UploadAction.java

    r90 r92  
    1919import org.openstreetmap.josm.data.osm.OsmPrimitive;
    2020import org.openstreetmap.josm.gui.OsmPrimitivRenderer;
     21import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    2122import org.openstreetmap.josm.io.OsmServerWriter;
    2223import org.openstreetmap.josm.tools.GBC;
     
    3839
    3940        public void actionPerformed(ActionEvent e) {
    40                
     41
    4142                String osmDataServer = Main.pref.get("osm-server.url");
    4243                //TODO: Remove this in later versions (temporary only)
     
    5455                        Main.pref.put("osm-server.url", osmDataServer.substring(0, osmDataServer.length()-cutPos));
    5556                }
    56                
     57
    5758                if (!Main.main.getMapFrame().conflictDialog.conflicts.isEmpty()) {
    5859                        JOptionPane.showMessageDialog(Main.main, "There are unresolved conflicts. You have to resolve these first.");
     
    8283                all.addAll(update);
    8384                all.addAll(delete);
    84                
     85
    8586                PleaseWaitRunnable uploadTask = new PleaseWaitRunnable("Uploading data"){
    86                                 @Override protected void realRun() throws JDOMException {
    87                                         server.uploadOsm(all);
    88                                 }
    89                                 @Override protected void finish() {
    90                                         Main.main.getMapFrame().mapView.editLayer().cleanData(server.processed, !add.isEmpty());
    91                     }
    92                                
    93                         };
     87                        @Override protected void realRun() throws JDOMException {
     88                                server.setProgressInformation(currentAction, progress);
     89                                server.uploadOsm(all);
     90                        }
     91                        @Override protected void finish() {
     92                                Main.main.getMapFrame().mapView.editLayer().cleanData(server.processed, !add.isEmpty());
     93                        }
     94                        @Override protected void cancel() {
     95                                server.cancel();
     96                        }
     97                };
    9498                Main.worker.execute(uploadTask);
    9599                uploadTask.pleaseWaitDlg.setVisible(true);
  • src/org/openstreetmap/josm/data/osm/visitor/NameVisitor.java

    r86 r92  
    1717 * @author imi
    1818 */
    19 public class SelectionComponentVisitor implements Visitor {
     19public class NameVisitor implements Visitor {
    2020
     21        /**
     22         * The name of the item class
     23         */
     24        public String className;
    2125        /**
    2226         * The name of this item.
     
    4347                }
    4448                icon = ImageProvider.get("data", "segment");
     49                className = "segment";
    4550        }
    4651
     
    5459                        name = (n.id==0?"":""+n.id)+" ("+n.coor.lat()+","+n.coor.lon()+")";
    5560                icon = ImageProvider.get("data", "node");
     61                className = "node";
    5662        }
    5763
     
    7480                }
    7581                icon = ImageProvider.get("data", "way");
     82                className = "way";
    7683        }
    7784}
  • src/org/openstreetmap/josm/gui/MapStatus.java

    r86 r92  
    3030import org.openstreetmap.josm.data.coor.LatLon;
    3131import org.openstreetmap.josm.data.osm.OsmPrimitive;
    32 import org.openstreetmap.josm.data.osm.visitor.SelectionComponentVisitor;
     32import org.openstreetmap.josm.data.osm.visitor.NameVisitor;
    3333import org.openstreetmap.josm.tools.GBC;
    3434
     
    120120                                        osmNearest = mv.getNearest(ms.mousePos, (ms.modifiers & MouseEvent.ALT_DOWN_MASK) != 0);
    121121                                        if (osmNearest != null) {
    122                                                 SelectionComponentVisitor visitor = new SelectionComponentVisitor();
     122                                                NameVisitor visitor = new NameVisitor();
    123123                                                osmNearest.visit(visitor);
    124124                                                nameText.setText(visitor.name);
     
    133133                                                JPanel c = new JPanel(new GridBagLayout());
    134134                                                for (final OsmPrimitive osm : osms) {
    135                                                         SelectionComponentVisitor visitor = new SelectionComponentVisitor();
     135                                                        NameVisitor visitor = new NameVisitor();
    136136                                                        osm.visit(visitor);
    137137                                                        final StringBuilder text = new StringBuilder();
  • src/org/openstreetmap/josm/gui/OsmPrimitivRenderer.java

    r86 r92  
    88
    99import org.openstreetmap.josm.data.osm.OsmPrimitive;
    10 import org.openstreetmap.josm.data.osm.visitor.SelectionComponentVisitor;
     10import org.openstreetmap.josm.data.osm.visitor.NameVisitor;
    1111
    1212/**
     
    1616public class OsmPrimitivRenderer extends DefaultListCellRenderer {
    1717
    18         private SelectionComponentVisitor visitor = new SelectionComponentVisitor();
     18        private NameVisitor visitor = new NameVisitor();
    1919
    2020        @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
  • src/org/openstreetmap/josm/gui/dialogs/PropertiesDialog.java

    r86 r92  
    234234                        }
    235235                });
    236                 propertyTable.addMouseListener(new DblClickWatch());
     236                //propertyTable.addMouseListener(new DblClickWatch());
    237237
    238238                JScrollPane scrollPane = new JScrollPane(propertyTable);
  • src/org/openstreetmap/josm/gui/dialogs/SelectionListDialog.java

    r91 r92  
    1111import java.awt.event.MouseEvent;
    1212import java.io.IOException;
    13 import java.io.InputStreamReader;
    1413import java.io.Reader;
     14import java.net.HttpURLConnection;
    1515import java.net.MalformedURLException;
    1616import java.net.URL;
     
    3131import javax.swing.ListSelectionModel;
    3232
     33import org.jdom.JDOMException;
    3334import org.openstreetmap.josm.Main;
    3435import org.openstreetmap.josm.data.SelectionChangedListener;
     
    3637import org.openstreetmap.josm.gui.MapFrame;
    3738import org.openstreetmap.josm.gui.OsmPrimitivRenderer;
     39import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    3840import org.openstreetmap.josm.io.OsmIdReader;
     41import org.openstreetmap.josm.io.ProgressReader;
    3942import org.openstreetmap.josm.tools.GBC;
    4043import org.openstreetmap.josm.tools.ImageProvider;
     
    5154public class SelectionListDialog extends ToggleDialog implements SelectionChangedListener {
    5255
     56        public static enum SearchMode {replace, add, remove}
     57
     58        private static class SelectionWebsiteLoader extends PleaseWaitRunnable {
     59                public final URL url;
     60                public Collection<OsmPrimitive> sel;
     61                private final SearchMode mode;
     62                private OsmIdReader idReader = new OsmIdReader();
     63                public SelectionWebsiteLoader(String urlStr, SearchMode mode) {
     64                super("Load Selection");
     65                this.mode = mode;
     66                URL u = null;
     67                        try {u = new URL(urlStr);} catch (MalformedURLException e) {}
     68            this.url = u;
     69        }
     70                @Override protected void realRun() throws SAXException, JDOMException, IOException {
     71                        currentAction.setText("Contact "+url.getHost()+"...");
     72                        sel = mode != SearchMode.remove ? new LinkedList<OsmPrimitive>() : Main.ds.allNonDeletedPrimitives();
     73                        try {
     74                        HttpURLConnection con = (HttpURLConnection)url.openConnection();
     75                        Reader in = new ProgressReader(con, progress);
     76                                currentAction.setText("Downloading...");
     77                                Map<Long, String> ids = idReader.parseIds(in);
     78                        for (OsmPrimitive osm : Main.ds.allNonDeletedPrimitives()) {
     79                                if (ids.containsKey(osm.id) && osm.getClass().getName().toLowerCase().endsWith(ids.get(osm.id))) {
     80                                        if (mode == SearchMode.remove)
     81                                                sel.remove(osm);
     82                                        else
     83                                                sel.add(osm);
     84                                }
     85                                }
     86                } catch (IOException e) {
     87                        e.printStackTrace();
     88                        JOptionPane.showMessageDialog(Main.main, "Could not read from url: '"+url+"'");
     89                } catch (SAXException e) {
     90                        e.printStackTrace();
     91                        JOptionPane.showMessageDialog(Main.main, "Parsing error in url: '"+url+"'");
     92                }
     93        }
     94                @Override protected void cancel() {
     95                        sel = null;
     96                        idReader.cancel();
     97                }
     98                @Override protected void finish() {
     99                        if (sel != null)
     100                                Main.ds.setSelected(sel);
     101        }
     102        }
     103       
    53104        /**
    54105         * The selection's list data.
     
    128179                                        return;
    129180                                lastSearch = input.getText();
    130                                 Collection<OsmPrimitive> sel = null;
    131                                 if (lastSearch.startsWith("http://"))
    132                                         sel = selectFromWebsite(lastSearch, replace.isSelected(), add.isSelected(), remove.isSelected());
    133                                 if (sel == null) {
    134                                         sel = Main.ds.getSelected();
    135                                         SearchCompiler.Match matcher = SearchCompiler.compile(lastSearch);
    136                                         for (OsmPrimitive osm : Main.ds.allNonDeletedPrimitives()) {
    137                                                 if (replace.isSelected()) {
    138                                                         if (matcher.match(osm))
    139                                                                 sel.add(osm);
    140                                                         else
    141                                                                 sel.remove(osm);
    142                                                 } else if (add.isSelected() && !osm.selected && matcher.match(osm))
    143                                                         sel.add(osm);
    144                                                 else if (remove.isSelected() && osm.selected && matcher.match(osm))
    145                                                         sel.remove(osm);
    146                                         }
    147                                 }
    148                                 Main.ds.setSelected(sel);
     181                                SearchMode mode = replace.isSelected() ? SearchMode.replace : (add.isSelected() ? SearchMode.add : SearchMode.remove);
     182                                search(lastSearch, mode);
    149183                        }
    150184                });
     
    154188                selectionChanged(Main.ds.getSelected());
    155189        }
    156 
    157         private Collection<OsmPrimitive> selectFromWebsite(String url, boolean replace, boolean add, boolean remove) {
    158                 Collection<OsmPrimitive> sel = replace ? new LinkedList<OsmPrimitive>() : Main.ds.allNonDeletedPrimitives();
    159                 try {
    160                 Reader in = new InputStreamReader(new URL(url).openStream());
    161                 Map<Long, String> ids = OsmIdReader.parseIds(in);
    162                 for (OsmPrimitive osm : Main.ds.allNonDeletedPrimitives()) {
    163                         if (ids.containsKey(osm.id) && osm.getClass().getName().toLowerCase().endsWith(ids.get(osm.id))) {
    164                                 if (remove)
    165                                         sel.remove(osm);
    166                                 else
    167                                         sel.add(osm);
    168                         }
    169                         }
    170         } catch (MalformedURLException e) {
    171                 return null;
    172         } catch (IOException e) {
    173                 e.printStackTrace();
    174                 JOptionPane.showMessageDialog(Main.main, "Could not read from url: '"+url+"'");
    175         } catch (SAXException e) {
    176                 e.printStackTrace();
    177                 JOptionPane.showMessageDialog(Main.main, "Parsing error in url: '"+url+"'");
    178         }
    179         return sel;
    180     }
    181190
    182191        @Override public void setVisible(boolean b) {
     
    216225                Main.ds.setSelected(sel);
    217226        }
     227
     228        public static void search(String search, SearchMode mode) {
     229            if (search.startsWith("http://")) {
     230                SelectionWebsiteLoader loader = new SelectionWebsiteLoader(search, mode);
     231                if (loader.url != null) {
     232                        Main.worker.execute(loader);
     233                        loader.pleaseWaitDlg.setVisible(true);
     234                        return;
     235                }
     236            }
     237            Collection<OsmPrimitive> sel = Main.ds.getSelected();
     238        SearchCompiler.Match matcher = SearchCompiler.compile(search);
     239        for (OsmPrimitive osm : Main.ds.allNonDeletedPrimitives()) {
     240                if (mode == SearchMode.replace) {
     241                        if (matcher.match(osm))
     242                                sel.add(osm);
     243                        else
     244                                sel.remove(osm);
     245                } else if (mode == SearchMode.add && !osm.selected && matcher.match(osm))
     246                        sel.add(osm);
     247                else if (mode == SearchMode.remove && osm.selected && matcher.match(osm))
     248                        sel.remove(osm);
     249        }
     250            Main.ds.setSelected(sel);
     251    }
    218252}
  • src/org/openstreetmap/josm/io/OsmConnection.java

    r86 r92  
    77import java.net.PasswordAuthentication;
    88
     9import javax.swing.BoundedRangeModel;
    910import javax.swing.JLabel;
    1011import javax.swing.JOptionPane;
     
    2425public class OsmConnection {
    2526
    26         /**
    27          * The authentication class handling the login requests.
    28          */
    29         private static class OsmAuth extends Authenticator {
    30                 /**
    31                  * Set to true, when the autenticator tried the password once.
    32                  */
    33                 boolean passwordtried = false;
    34                 /**
    35                  * Whether the user cancelled the password dialog
    36                  */
    37                 boolean cancelled = false;
    38 
    39                 @Override protected PasswordAuthentication getPasswordAuthentication() {
    40                         String username = Main.pref.get("osm-server.username");
    41                         String password = Main.pref.get("osm-server.password");
    42                         if (passwordtried || username.equals("") || password.equals("")) {
    43                                 JPanel p = new JPanel(new GridBagLayout());
    44                                 p.add(new JLabel("Username"), GBC.std().insets(0,0,10,0));
    45                                 JTextField usernameField = new JTextField(username, 20);
    46                                 p.add(usernameField, GBC.eol());
    47                                 p.add(new JLabel("Password"), GBC.std().insets(0,0,10,0));
    48                                 JPasswordField passwordField = new JPasswordField(password, 20);
    49                                 p.add(passwordField, GBC.eol());
    50                                 JLabel warning = new JLabel("Warning: The password is transferred unencrypted.");
    51                                 warning.setFont(warning.getFont().deriveFont(Font.ITALIC));
    52                                 p.add(warning, GBC.eol());
    53                                 int choice = JOptionPane.showConfirmDialog(Main.main, p, "Enter Password", JOptionPane.OK_CANCEL_OPTION);
    54                                 if (choice == JOptionPane.CANCEL_OPTION) {
    55                                         cancelled = true;
    56                                         return null;
    57                                 }
    58                                 username = usernameField.getText();
    59                                 password = String.valueOf(passwordField.getPassword());
    60                                 if (username.equals(""))
    61                                         return null;
    62                         }
    63                         passwordtried = true;
    64                         return new PasswordAuthentication(username, password.toCharArray());
    65                 }
    66         }
    67 
    68         /**
    69          * The authenticator.
    70          */
     27        protected boolean cancel = false;
     28        protected HttpURLConnection activeConnection;
     29        protected JLabel currentAction;
     30        protected BoundedRangeModel progress;
     31       
    7132        private static OsmAuth authentication;
    72        
    7333        /**
    7434         * Initialize the http defaults and the authenticator.
     
    8040       
    8141        /**
     42     * The authentication class handling the login requests.
     43     */
     44    private static class OsmAuth extends Authenticator {
     45        /**
     46         * Set to true, when the autenticator tried the password once.
     47         */
     48        boolean passwordtried = false;
     49        /**
     50         * Whether the user cancelled the password dialog
     51         */
     52        boolean authCancelled = false;
     53   
     54        @Override protected PasswordAuthentication getPasswordAuthentication() {
     55                String username = Main.pref.get("osm-server.username");
     56                String password = Main.pref.get("osm-server.password");
     57                if (passwordtried || username.equals("") || password.equals("")) {
     58                        JPanel p = new JPanel(new GridBagLayout());
     59                        p.add(new JLabel("Username"), GBC.std().insets(0,0,10,0));
     60                        JTextField usernameField = new JTextField(username, 20);
     61                        p.add(usernameField, GBC.eol());
     62                        p.add(new JLabel("Password"), GBC.std().insets(0,0,10,0));
     63                        JPasswordField passwordField = new JPasswordField(password, 20);
     64                        p.add(passwordField, GBC.eol());
     65                        JLabel warning = new JLabel("Warning: The password is transferred unencrypted.");
     66                        warning.setFont(warning.getFont().deriveFont(Font.ITALIC));
     67                        p.add(warning, GBC.eol());
     68                        int choice = JOptionPane.showConfirmDialog(Main.main, p, "Enter Password", JOptionPane.OK_CANCEL_OPTION);
     69                        if (choice == JOptionPane.CANCEL_OPTION) {
     70                                authCancelled = true;
     71                                return null;
     72                        }
     73                        username = usernameField.getText();
     74                        password = String.valueOf(passwordField.getPassword());
     75                        if (username.equals(""))
     76                                return null;
     77                }
     78                passwordtried = true;
     79                return new PasswordAuthentication(username, password.toCharArray());
     80        }
     81    }
     82
     83        /**
    8284         * Must be called before each connection attemp to initialize the authentication.
    8385         */
    8486        protected final void initAuthentication() {
    85                 authentication.cancelled = false;
     87                authentication.authCancelled = false;
    8688                authentication.passwordtried = false;
    8789        }
     
    9092         * @return Whether the connection was cancelled.
    9193         */
    92         protected final boolean isCancelled() {
    93                 return authentication.cancelled;
     94        protected final boolean isAuthCancelled() {
     95                return authentication.authCancelled;
    9496        }
     97
     98        public void setProgressInformation(JLabel currentAction, BoundedRangeModel progress) {
     99                this.currentAction = currentAction;
     100                this.progress = progress;
     101    }
     102
     103        public void cancel() {
     104                currentAction.setText("Aborting...");
     105        cancel = true;
     106        if (activeConnection != null) {
     107                activeConnection.setConnectTimeout(1);
     108                activeConnection.setReadTimeout(1);
     109                activeConnection.disconnect();
     110        }
     111    }
    95112}
  • src/org/openstreetmap/josm/io/OsmIdReader.java

    r91 r92  
    1818public class OsmIdReader extends MinML2 {
    1919
     20        private boolean cancel;
    2021        Map<Long, String> entries = new HashMap<Long, String>();
     22        private Reader in;
    2123
    2224        @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
     
    3133    }
    3234
    33         public static Map<Long, String> parseIds(Reader in) throws IOException, SAXException {
    34                 OsmIdReader r = new OsmIdReader();
    35         r.parse(in);
    36                 return r.entries;
     35        public Map<Long, String> parseIds(Reader in) throws IOException, SAXException {
     36        this.in = in;
     37                try {
     38                parse(in);
     39        } catch (SAXException e) {
     40                if (!cancel)
     41                        throw e;
     42        }       
     43                return entries;
     44        }
     45       
     46        public void cancel() {
     47                cancel = true;
     48                if (in != null)
     49            try {in.close();} catch (IOException e) {}
    3750        }
    3851}
  • src/org/openstreetmap/josm/io/OsmServerReader.java

    r78 r92  
    22
    33import java.io.IOException;
    4 import java.io.InputStreamReader;
    54import java.io.Reader;
    65import java.net.HttpURLConnection;
     
    6867                                break;
    6968                        r.close();
     69                        activeConnection = null;
    7070                }
    7171
     
    8383                if (r == null)
    8484                        return null;
     85                currentAction.setText("Downloading OSM data...");
    8586                DataSet data = OsmReader.parseDataSet(r);
    8687                r.close();
     88                activeConnection = null;
    8789                return data;
    8890        }
     
    99101                initAuthentication();
    100102                URL url = new URL(urlStr);
    101                 HttpURLConnection con = (HttpURLConnection)url.openConnection();
    102                 con.setConnectTimeout(20000);
    103                 if (con.getResponseCode() == 401 && isCancelled())
     103                activeConnection = (HttpURLConnection)url.openConnection();
     104                activeConnection.setConnectTimeout(15000);
     105                if (isAuthCancelled() && activeConnection.getResponseCode() == 401)
    104106                        return null;
    105                 return new InputStreamReader(con.getInputStream());
     107                return new ProgressReader(activeConnection, progress);
    106108        }
    107109}
  • src/org/openstreetmap/josm/io/OsmServerWriter.java

    r86 r92  
    1616import org.jdom.JDOMException;
    1717import org.openstreetmap.josm.Main;
    18 import org.openstreetmap.josm.data.osm.Segment;
    1918import org.openstreetmap.josm.data.osm.Node;
    2019import org.openstreetmap.josm.data.osm.OsmPrimitive;
     20import org.openstreetmap.josm.data.osm.Segment;
    2121import org.openstreetmap.josm.data.osm.Way;
     22import org.openstreetmap.josm.data.osm.visitor.NameVisitor;
    2223import org.openstreetmap.josm.data.osm.visitor.Visitor;
    2324
     
    4445         */
    4546        public Collection<OsmPrimitive> processed;
    46        
     47
     48        /**
     49         * Whether the operation should be aborted as soon as possible.
     50         */
     51        private boolean cancel = false;
     52
    4753        /**
    4854         * Send the dataset to the server. Ask the user first and does nothing if he
     
    5359                initAuthentication();
    5460
     61                progress.setMaximum(list.size());
     62                progress.setValue(0);
     63
     64                NameVisitor v = new NameVisitor();
    5565                try {
    56                         for (OsmPrimitive osm : list)
     66                        for (OsmPrimitive osm : list) {
     67                                if (cancel)
     68                                        return;
     69                                osm.visit(v);
     70                                currentAction.setText("Upload "+v.className+" "+osm.id+"...");
    5771                                osm.visit(this);
     72                                progress.setValue(progress.getValue()+1);
     73                        }
    5874                } catch (RuntimeException e) {
    5975                        throw new JDOMException("An error occoured: ", e);
     
    138154                        URL url = new URL(Main.pref.get("osm-server.url") + "/0.3/" + urlSuffix + "/" + osm.id);
    139155                        System.out.println("upload to: "+url);
    140                         HttpURLConnection con = (HttpURLConnection) url.openConnection();
    141                         con.setConnectTimeout(20000);
    142                         con.setRequestMethod(requestMethod);
     156                        activeConnection = (HttpURLConnection) url.openConnection();
     157                        activeConnection.setConnectTimeout(15000);
     158                        activeConnection.setRequestMethod(requestMethod);
    143159                        if (addBody)
    144                                 con.setDoOutput(true);
    145                         con.connect();
     160                                activeConnection.setDoOutput(true);
     161                        activeConnection.connect();
    146162
    147163                        if (addBody) {
    148                                 Writer out = new OutputStreamWriter(con.getOutputStream());
     164                                Writer out = new OutputStreamWriter(activeConnection.getOutputStream());
    149165                                OsmWriter.outputSingle(out, osm, true);
    150166                                out.close();
    151167                        }
    152168
    153                         int retCode = con.getResponseCode();
     169                        int retCode = activeConnection.getResponseCode();
    154170                        if (retCode == 200 && osm.id == 0)
    155                                 osm.id = readId(con.getInputStream());
     171                                osm.id = readId(activeConnection.getInputStream());
    156172                        System.out.println("got return: "+retCode+" with id "+osm.id);
    157                         String retMsg = con.getResponseMessage();
    158                         con.disconnect();
     173                        String retMsg = activeConnection.getResponseMessage();
     174                        activeConnection.disconnect();
    159175                        if (retCode == 410 && requestMethod.equals("DELETE"))
    160176                                return; // everything fine.. was already deleted.
     
    170186                        if (e instanceof RuntimeException)
    171187                                throw (RuntimeException)e;
    172                         throw new RuntimeException(e.getMessage(), e);
     188                        if (!cancel)
     189                                throw new RuntimeException(e.getMessage(), e);
    173190                }
    174191        }
Note: See TracChangeset for help on using the changeset viewer.