Ignore:
Timestamp:
2010-09-15T18:54:18+02:00 (14 years ago)
Author:
stoecker
Message:

remove tabs

Location:
applications/editors/josm/plugins
Files:
104 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/DirectUpload/src/org/openstreetmap/josm/plugins/DirectUpload/UploadDataGui.java

    r22017 r23190  
    8282
    8383        @Override
    84                 public String toString() {
     84        public String toString() {
    8585            return this.name().toLowerCase();
    8686        }
     
    134134     */
    135135    private JPanel initComponents() {
    136         JLabel visibilityLabel = new JLabel(tr("Visibility"));
     136        JLabel visibilityLabel = new JLabel(tr("Visibility"));
    137137        visibilityLabel.setToolTipText(tr("Defines the visibility of your trace for other OSM users."));
    138138        for(visibility v : visibility.values()) {
    139                 visibilityCombo.addItem(v.description);
     139            visibilityCombo.addItem(v.description);
    140140        }
    141141        UrlLabel visiUrl = new UrlLabel(tr("http://wiki.openstreetmap.org/wiki/Visibility_of_GPS_traces"), tr("(What does that mean?)"));
     
    205205     */
    206206    private void upload(String description, String tags, String visi, GpxData gpxData, ProgressMonitor progressMonitor) throws IOException {
    207         progressMonitor.beginTask(null);
    208         try {
    209                 if(checkForErrors(username, password, description, gpxData))
    210                         return;
    211 
    212                 // Clean description/tags from disallowed chars
    213                 description = description.replaceAll("[&?/\\\\]"," ");
    214                 tags = tags.replaceAll("[&?/\\\\.;]"," ");
    215 
    216                 // Set progress dialog to indeterminate while connecting
    217                 progressMonitor.indeterminateSubTask(tr("Connecting..."));
    218 
    219                 try {
    220                         // Generate data for upload
    221                         ByteArrayOutputStream baos  = new ByteArrayOutputStream();
    222                         writeGpxFile(baos, "file", gpxData);
    223                         writeField(baos, "description", description);
    224                         writeField(baos, "tags", (tags != null && tags.length() > 0) ? tags : "");
    225                         writeField(baos, "visibility", visi);
    226                         writeString(baos, "--" + BOUNDARY + "--" + LINE_END);
    227 
    228                         ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    229                         HttpURLConnection conn = setupConnection(baos.size());
    230 
    231                         progressMonitor.setTicksCount(baos.size());
    232                         progressMonitor.subTask(null);
    233 
    234                         try {
    235                                 flushToServer(bais, conn.getOutputStream(), progressMonitor);
    236                         } catch(Exception e) {}
    237 
    238                         if(cancelled) {
    239                                 conn.disconnect();
    240                                 OutputDisplay.setText(tr("Upload cancelled"));
    241                                 buttons.get(0).setEnabled(true);
    242                                 cancelled = false;
    243                         } else {
    244                                 boolean success = finishUpConnection(conn);
    245                                 buttons.get(0).setEnabled(!success);
    246                                 if(success)
    247                                         buttons.get(1).setText(tr("Close"));
    248                         }
    249                 } catch(Exception e) {
    250                         OutputDisplay.setText(tr("Error while uploading"));
    251                         e.printStackTrace();
    252                 }
    253         } finally {
    254                 progressMonitor.finishTask();
    255         }
     207        progressMonitor.beginTask(null);
     208        try {
     209            if(checkForErrors(username, password, description, gpxData))
     210                return;
     211
     212            // Clean description/tags from disallowed chars
     213            description = description.replaceAll("[&?/\\\\]"," ");
     214            tags = tags.replaceAll("[&?/\\\\.;]"," ");
     215
     216            // Set progress dialog to indeterminate while connecting
     217            progressMonitor.indeterminateSubTask(tr("Connecting..."));
     218
     219            try {
     220                // Generate data for upload
     221                ByteArrayOutputStream baos  = new ByteArrayOutputStream();
     222                writeGpxFile(baos, "file", gpxData);
     223                writeField(baos, "description", description);
     224                writeField(baos, "tags", (tags != null && tags.length() > 0) ? tags : "");
     225                writeField(baos, "visibility", visi);
     226                writeString(baos, "--" + BOUNDARY + "--" + LINE_END);
     227
     228                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
     229                HttpURLConnection conn = setupConnection(baos.size());
     230
     231                progressMonitor.setTicksCount(baos.size());
     232                progressMonitor.subTask(null);
     233
     234                try {
     235                    flushToServer(bais, conn.getOutputStream(), progressMonitor);
     236                } catch(Exception e) {}
     237
     238                if(cancelled) {
     239                    conn.disconnect();
     240                    OutputDisplay.setText(tr("Upload cancelled"));
     241                    buttons.get(0).setEnabled(true);
     242                    cancelled = false;
     243                } else {
     244                    boolean success = finishUpConnection(conn);
     245                    buttons.get(0).setEnabled(!success);
     246                    if(success)
     247                        buttons.get(1).setText(tr("Close"));
     248                }
     249            } catch(Exception e) {
     250                OutputDisplay.setText(tr("Error while uploading"));
     251                e.printStackTrace();
     252            }
     253        } finally {
     254            progressMonitor.finishTask();
     255        }
    256256    }
    257257
  • applications/editors/josm/plugins/DirectUpload/src/org/openstreetmap/josm/plugins/DirectUpload/UploadDataGuiPlugin.java

    r20880 r23190  
    2727
    2828    public UploadDataGuiPlugin(PluginInformation info) {
    29         super(info);
     29        super(info);
    3030        openaction = new UploadAction();
    3131        Main.main.menu.toolsMenu.add(openaction);
     
    4444
    4545        @Override
    46                 protected void updateEnabledState() {
    47                 // enable button if there is "one active GpxLayer" or "exactly one GpxLayer in the list of all layers available"
    48                 if(Main.map == null
     46        protected void updateEnabledState() {
     47            // enable button if there is "one active GpxLayer" or "exactly one GpxLayer in the list of all layers available"
     48            if(Main.map == null
    4949                    || Main.map.mapView == null
    5050                    || Main.map.mapView.getActiveLayer() == null
    51                     || !(Main.map.mapView.getActiveLayer() instanceof GpxLayer)) {               
     51                    || !(Main.map.mapView.getActiveLayer() instanceof GpxLayer)) {
    5252                setEnabled(false);
    5353            } else {
    54                 setEnabled(true);
     54                setEnabled(true);
    5555            }
    5656
     
    6161            }
    6262
    63         }               
     63        }
    6464    }
    6565}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/AddressDialog.java

    r22529 r23190  
    2020@SuppressWarnings("serial")
    2121public class AddressDialog extends ExtendedDialog {
    22         private static String lhousenum,lstreetname;
    23         private static boolean inc = true;
    24         private JTextField housenum = new JTextField();
    25         private JTextField streetname = new JTextField();
    26         private Choice cincdec = new Choice();
     22    private static String lhousenum,lstreetname;
     23    private static boolean inc = true;
     24    private JTextField housenum = new JTextField();
     25    private JTextField streetname = new JTextField();
     26    private Choice cincdec = new Choice();
    2727
    28         private JPanel panel = new JPanel(new GridBagLayout());
    29         private void addLabelled(String str, Component c) {
    30                 JLabel label = new JLabel(str);
    31                 panel.add(label, GBC.std());
    32                 label.setLabelFor(c);
    33                 panel.add(c, GBC.eol().fill(GBC.HORIZONTAL));
    34         }
     28    private JPanel panel = new JPanel(new GridBagLayout());
     29    private void addLabelled(String str, Component c) {
     30        JLabel label = new JLabel(str);
     31        panel.add(label, GBC.std());
     32        label.setLabelFor(c);
     33        panel.add(c, GBC.eol().fill(GBC.HORIZONTAL));
     34    }
    3535
    36         public AddressDialog() {
    37                 super(Main.parent, tr("Building address"),
    38                                 new String[] { tr("OK"), tr("Cancel") },
    39                                 true);
    40                
    41                 contentInsets = new Insets(15,15,5,15);
    42                 setButtonIcons(new String[] {"ok.png", "cancel.png" });
    43                
    44                 addLabelled(tr("House number:"),housenum);
    45                 addLabelled(tr("Street Name:"),streetname);
    46                 housenum.setText(nextHouseNum());
    47                 streetname.setText(lstreetname);
     36    public AddressDialog() {
     37        super(Main.parent, tr("Building address"),
     38                new String[] { tr("OK"), tr("Cancel") },
     39                true);
    4840
    49                 cincdec.add(tr("Increment"));
    50                 cincdec.add(tr("Decrement"));
    51                 cincdec.select(inc?0:1);
    52                 addLabelled(tr("Numbers:"), cincdec);
     41        contentInsets = new Insets(15,15,5,15);
     42        setButtonIcons(new String[] {"ok.png", "cancel.png" });
    5343
    54                 setContent(panel);
    55                 setupDialog();
    56                 setVisible(true);
    57         }
    58        
    59         private static String nextHouseNum() {
    60                 if (lhousenum==null) return "";
    61                 try {
    62                         Integer num = NumberFormat.getInstance().parse(lhousenum).intValue();
    63                         if (inc) num=num+2; else num = num-2;
    64                         return num.toString();
    65                 } catch (ParseException e) {                   
    66                         return lhousenum;
    67                 }
    68         }
    69         public void saveValues() {
    70                 lhousenum = housenum.getText();
    71                 lstreetname = streetname.getText();
    72                 inc = cincdec.getSelectedIndex() == 0;         
    73         }
    74         public String getHouseNum() {
    75                 return housenum.getText();
    76         }
    77         public String getStreetName() {
    78                 return streetname.getText();
    79         }
     44        addLabelled(tr("House number:"),housenum);
     45        addLabelled(tr("Street Name:"),streetname);
     46        housenum.setText(nextHouseNum());
     47        streetname.setText(lstreetname);
     48
     49        cincdec.add(tr("Increment"));
     50        cincdec.add(tr("Decrement"));
     51        cincdec.select(inc?0:1);
     52        addLabelled(tr("Numbers:"), cincdec);
     53
     54        setContent(panel);
     55        setupDialog();
     56        setVisible(true);
     57    }
     58
     59    private static String nextHouseNum() {
     60        if (lhousenum==null) return "";
     61        try {
     62            Integer num = NumberFormat.getInstance().parse(lhousenum).intValue();
     63            if (inc) num=num+2; else num = num-2;
     64            return num.toString();
     65        } catch (ParseException e) {
     66            return lhousenum;
     67        }
     68    }
     69    public void saveValues() {
     70        lhousenum = housenum.getText();
     71        lstreetname = streetname.getText();
     72        inc = cincdec.getSelectedIndex() == 0;
     73    }
     74    public String getHouseNum() {
     75        return housenum.getText();
     76    }
     77    public String getStreetName() {
     78        return streetname.getText();
     79    }
    8080}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/AdvancedSettingsDialog.java

    r23124 r23190  
    1818
    1919public class AdvancedSettingsDialog extends ExtendedDialog {
    20         private TagEditorModel tagsModel = new TagEditorModel();
     20    private TagEditorModel tagsModel = new TagEditorModel();
    2121
    22         private JCheckBox cBigMode = new JCheckBox(tr("Big buildings mode"));
    23         private JCheckBox cSoftCur = new JCheckBox(tr("Rotate crosshair"));
     22    private JCheckBox cBigMode = new JCheckBox(tr("Big buildings mode"));
     23    private JCheckBox cSoftCur = new JCheckBox(tr("Rotate crosshair"));
    2424
    25         public AdvancedSettingsDialog() {
    26                 super(Main.parent, tr("Advanced settings"),
    27                                 new String[] { tr("OK"), tr("Cancel") },
    28                                 true);
    29                 contentInsets = new Insets(15, 15, 5, 15);
    30                 setButtonIcons(new String[] { "ok.png", "cancel.png" });
     25    public AdvancedSettingsDialog() {
     26        super(Main.parent, tr("Advanced settings"),
     27                new String[] { tr("OK"), tr("Cancel") },
     28                true);
     29        contentInsets = new Insets(15, 15, 5, 15);
     30        setButtonIcons(new String[] { "ok.png", "cancel.png" });
    3131
    32                 final JPanel panel = new JPanel(new GridBagLayout());
    33                 panel.add(new JLabel(tr("Buildings tags:")), GBC.eol().fill(GBC.HORIZONTAL));
     32        final JPanel panel = new JPanel(new GridBagLayout());
     33        panel.add(new JLabel(tr("Buildings tags:")), GBC.eol().fill(GBC.HORIZONTAL));
    3434
    35                 for (Entry<String, String> entry : ToolSettings.getTags().entrySet()) {
    36                         tagsModel.add(entry.getKey(), entry.getValue());
    37                 }
    38                 panel.add(new TagEditorPanel(tagsModel, null), GBC.eop().fill(GBC.BOTH));
     35        for (Entry<String, String> entry : ToolSettings.getTags().entrySet()) {
     36            tagsModel.add(entry.getKey(), entry.getValue());
     37        }
     38        panel.add(new TagEditorPanel(tagsModel, null), GBC.eop().fill(GBC.BOTH));
    3939
    40                 panel.add(cBigMode, GBC.eol().fill(GBC.HORIZONTAL));
    41                 panel.add(cSoftCur, GBC.eol().fill(GBC.HORIZONTAL));
     40        panel.add(cBigMode, GBC.eol().fill(GBC.HORIZONTAL));
     41        panel.add(cSoftCur, GBC.eol().fill(GBC.HORIZONTAL));
    4242
    43                 cBigMode.setSelected(ToolSettings.isBBMode());
    44                 cSoftCur.setSelected(ToolSettings.isSoftCursor());
     43        cBigMode.setSelected(ToolSettings.isBBMode());
     44        cSoftCur.setSelected(ToolSettings.isSoftCursor());
    4545
    46                 setContent(panel);
     46        setContent(panel);
    4747
    48                 setupDialog();
    49                 setVisible(true);
    50         }
     48        setupDialog();
     49        setVisible(true);
     50    }
    5151
    52         public boolean isBBMode() {
    53                 return cBigMode.isSelected();
    54         }
     52    public boolean isBBMode() {
     53        return cBigMode.isSelected();
     54    }
    5555
    56         public boolean isSoftCursor() {
    57                 return cSoftCur.isSelected();
    58         }
     56    public boolean isSoftCursor() {
     57        return cSoftCur.isSelected();
     58    }
    5959
    60         public void saveSettings() {
    61                 tagsModel.applyToTags(ToolSettings.getTags());
    62                 ToolSettings.setBBMode(isBBMode());
    63                 ToolSettings.setSoftCursor(isSoftCursor());
    64         }
     60    public void saveSettings() {
     61        tagsModel.applyToTags(ToolSettings.getTags());
     62        ToolSettings.setBBMode(isBBMode());
     63        ToolSettings.setSoftCursor(isSoftCursor());
     64    }
    6565}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/AngleSnap.java

    r21846 r23190  
    1111
    1212public class AngleSnap {
    13         private static final double PI_2 = Math.PI / 2;
    14         TreeSet<Double> snapSet = new TreeSet<Double>();
     13    private static final double PI_2 = Math.PI / 2;
     14    TreeSet<Double> snapSet = new TreeSet<Double>();
    1515
    16         public void clear() {
    17                 snapSet.clear();
    18         }
     16    public void clear() {
     17        snapSet.clear();
     18    }
    1919
    20         public void addSnap(double snap) {
    21                 snapSet.add(snap % PI_2);
    22         }
     20    public void addSnap(double snap) {
     21        snapSet.add(snap % PI_2);
     22    }
    2323
    24         public Double addSnap(Node[] nodes) {
    25                 if (nodes.length == 2) {
    26                         EastNorth p1, p2;
    27                         p1 = latlon2eastNorth(((Node) nodes[0]).getCoor());
    28                         p2 = latlon2eastNorth(((Node) nodes[1]).getCoor());
    29                         double heading = p1.heading(p2);
    30                         addSnap(heading);
    31                         addSnap(heading + Math.PI / 4);
    32                         return heading;
    33                 } else {
    34                         return null;
    35                 }
    36         }
     24    public Double addSnap(Node[] nodes) {
     25        if (nodes.length == 2) {
     26            EastNorth p1, p2;
     27            p1 = latlon2eastNorth(((Node) nodes[0]).getCoor());
     28            p2 = latlon2eastNorth(((Node) nodes[1]).getCoor());
     29            double heading = p1.heading(p2);
     30            addSnap(heading);
     31            addSnap(heading + Math.PI / 4);
     32            return heading;
     33        } else {
     34            return null;
     35        }
     36    }
    3737
    38         public void addSnap(Way way) {
    39                 for (Pair<Node, Node> pair : way.getNodePairs(false)) {
    40                         EastNorth a, b;
    41                         a = latlon2eastNorth(pair.a.getCoor());
    42                         b = latlon2eastNorth(pair.b.getCoor());
    43                         double heading = a.heading(b);
    44                         addSnap(heading);
    45                 }
    46         }
     38    public void addSnap(Way way) {
     39        for (Pair<Node, Node> pair : way.getNodePairs(false)) {
     40            EastNorth a, b;
     41            a = latlon2eastNorth(pair.a.getCoor());
     42            b = latlon2eastNorth(pair.b.getCoor());
     43            double heading = a.heading(b);
     44            addSnap(heading);
     45        }
     46    }
    4747
    48         public Double getAngle() {
    49                 if (snapSet.isEmpty()) {
    50                         return null;
    51                 }
    52                 double first = snapSet.first();
    53                 double last = snapSet.last();
    54                 if (first < Math.PI / 4 && last > Math.PI / 4) {
    55                         last -= PI_2;
    56                 }
    57                 if (Math.abs(first - last) < 0.001) {
    58                         double center = (first + last) / 2;
    59                         if (center < 0)
    60                                 center += PI_2;
    61                         return center;
    62                 } else {
    63                         return null;
    64                 }
    65         }
     48    public Double getAngle() {
     49        if (snapSet.isEmpty()) {
     50            return null;
     51        }
     52        double first = snapSet.first();
     53        double last = snapSet.last();
     54        if (first < Math.PI / 4 && last > Math.PI / 4) {
     55            last -= PI_2;
     56        }
     57        if (Math.abs(first - last) < 0.001) {
     58            double center = (first + last) / 2;
     59            if (center < 0)
     60                center += PI_2;
     61            return center;
     62        } else {
     63            return null;
     64        }
     65    }
    6666
    67         public double snapAngle(double angle) {
    68                 if (snapSet.isEmpty()) {
    69                         return angle;
    70                 }
    71                 int quadrant = (int) Math.floor(angle / PI_2);
    72                 double ang = angle % PI_2;
    73                 Double prev = snapSet.floor(ang);
    74                 if (prev == null)
    75                         prev = snapSet.last() - PI_2;
    76                 Double next = snapSet.ceiling(ang);
    77                 if (next == null)
    78                         next = snapSet.first() + PI_2;
     67    public double snapAngle(double angle) {
     68        if (snapSet.isEmpty()) {
     69            return angle;
     70        }
     71        int quadrant = (int) Math.floor(angle / PI_2);
     72        double ang = angle % PI_2;
     73        Double prev = snapSet.floor(ang);
     74        if (prev == null)
     75            prev = snapSet.last() - PI_2;
     76        Double next = snapSet.ceiling(ang);
     77        if (next == null)
     78            next = snapSet.first() + PI_2;
    7979
    80                 if (Math.abs(ang - next) > Math.abs(ang - prev)) {
    81                         if (Math.abs(ang - prev) > Math.PI / 8) {
    82                                 return angle;
    83                         } else {
    84                                 double ret = prev + PI_2 * quadrant;
    85                                 if (ret < 0)
    86                                         ret += 2 * Math.PI;
    87                                 return ret;
    88                         }
    89                 } else {
    90                         if (Math.abs(ang - next) > Math.PI / 8) {
    91                                 return angle;
    92                         } else {
    93                                 double ret = next + PI_2 * quadrant;
    94                                 if (ret > 2 * Math.PI)
    95                                         ret -= 2 * Math.PI;
    96                                 return ret;
    97                         }
    98                 }
    99         }
     80        if (Math.abs(ang - next) > Math.abs(ang - prev)) {
     81            if (Math.abs(ang - prev) > Math.PI / 8) {
     82                return angle;
     83            } else {
     84                double ret = prev + PI_2 * quadrant;
     85                if (ret < 0)
     86                    ret += 2 * Math.PI;
     87                return ret;
     88            }
     89        } else {
     90            if (Math.abs(ang - next) > Math.PI / 8) {
     91                return angle;
     92            } else {
     93                double ret = next + PI_2 * quadrant;
     94                if (ret > 2 * Math.PI)
     95                    ret -= 2 * Math.PI;
     96                return ret;
     97            }
     98        }
     99    }
    100100}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/Building.java

    r22904 r23190  
    2828
    2929class Building {
    30         private static final double eqlen = 40075004; // length of equator in metres
    31         private final EastNorth[] en = new EastNorth[4];
    32 
    33         double meter = 0;
    34 
    35         private double len = 0;
    36         private double width;
    37         private double heading;
    38         private AngleSnap angleSnap = new AngleSnap();
    39         private Double drawingAngle;
    40 
    41         public void clearAngleSnap() {
    42                 angleSnap.clear();
    43                 drawingAngle = null;
    44         }
    45 
    46         public void addAngleSnap(Node[] nodes) {
    47                 drawingAngle = angleSnap.addSnap(nodes);
    48         }
    49 
    50         public void addAngleSnap(Way way) {
    51                 angleSnap.addSnap(way);
    52                 if (drawingAngle == null) {
    53                         drawingAngle = angleSnap.getAngle();
    54                 }
    55         }
    56 
    57         public double getLength() {
    58                 return len;
    59         }
    60 
    61         public double getWidth() {
    62                 return width;
    63         }
    64 
    65         public boolean isRectDrawing() {
    66                 return drawingAngle != null && ToolSettings.getWidth() == 0 && ToolSettings.getLenStep() == 0;
    67         }
    68 
    69         public Double getDrawingAngle() {
    70                 return drawingAngle;
    71         }
    72 
    73         public void reset() {
    74                 len = 0;
    75 
    76                 for (int i = 0; i < 4; i++)
    77                         en[i] = null;
    78         }
    79 
    80         public EastNorth getPoint(int num) {
    81                 return en[num];
    82         }
    83 
    84         private void updMetrics() {
    85                 meter = 2 * Math.PI / (Math.cos(Math.toRadians(eastNorth2latlon(en[0]).lat())) * eqlen);
    86                 len = 0;
    87         }
    88 
    89         public void setBase(EastNorth base) {
    90                 en[0] = base;
    91                 updMetrics();
    92         }
    93 
    94         public void setBase(Node base) {
    95                 en[0] = latlon2eastNorth(base.getCoor());
    96                 updMetrics();
    97         }
    98 
    99         /**
    100         * @returns Projection of the point to the heading vector in metres
    101         */
    102         private double projection1(EastNorth p) {
    103                 final EastNorth vec = en[0].sub(p);
    104                 return (Math.sin(heading) * vec.east() + Math.cos(heading) * vec.north()) / meter;
    105         }
    106 
    107         /**
    108         * @returns Projection of the point to the perpendicular of the heading
    109         *          vector in metres
    110         */
    111         private double projection2(EastNorth p) {
    112                 final EastNorth vec = en[0].sub(p);
    113                 return (Math.cos(heading) * vec.east() - Math.sin(heading) * vec.north()) / meter;
    114         }
    115 
    116         private void updatePos() {
    117                 if (len == 0)
    118                         return;
    119                 final EastNorth p1 = en[0];
    120                 en[1] = new EastNorth(p1.east() + Math.sin(heading) * len * meter, p1.north() + Math.cos(heading) * len * meter);
    121                 en[2] = new EastNorth(p1.east() + Math.sin(heading) * len * meter + Math.cos(heading) * width * meter,
    122                                 p1.north() + Math.cos(heading) * len * meter - Math.sin(heading) * width * meter);
    123                 en[3] = new EastNorth(p1.east() + Math.cos(heading) * width * meter,
    124                                 p1.north() - Math.sin(heading) * width * meter);
    125         }
    126 
    127         public void setLengthWidth(double length, double width) {
    128                 this.len = length;
    129                 this.width = width;
    130                 updatePos();
    131         }
    132 
    133         public void setWidth(EastNorth p3) {
    134                 this.width = projection2(p3);
    135                 updatePos();
    136         }
    137 
    138         public void setPlace(EastNorth p2, double width, double lenstep, boolean ignoreConstraints) {
    139                 if (en[0] == null)
    140                         throw new IllegalStateException("setPlace() called without the base point");
    141                 this.heading = en[0].heading(p2);
    142                 if (!ignoreConstraints)
    143                         this.heading = angleSnap.snapAngle(this.heading);
    144 
    145                 this.width = width;
    146                 this.len = projection1(p2);
    147                 if (lenstep > 0 && !ignoreConstraints)
    148                         this.len = Math.round(this.len / lenstep) * lenstep;
    149 
    150                 updatePos();
    151 
    152                 Main.map.statusLine.setHeading(Math.toDegrees(heading));
    153                 if (this.drawingAngle != null && !ignoreConstraints) {
    154                         double ang = Math.toDegrees(heading - this.drawingAngle);
    155                         if (ang < 0)
    156                                 ang += 360;
    157                         if (ang > 360)
    158                                 ang -= 360;
    159                         Main.map.statusLine.setAngle(ang);
    160                 }
    161         }
    162 
    163         public void setPlaceRect(EastNorth p2) {
    164                 if (en[0] == null)
    165                         throw new IllegalStateException("SetPlaceRect() called without the base point");
    166                 if (!isRectDrawing())
    167                         throw new IllegalStateException("Invalid drawing mode");
    168                 heading = drawingAngle;
    169                 setLengthWidth(projection1(p2), projection2(p2));
    170                 Main.map.statusLine.setHeading(Math.toDegrees(heading));
    171         }
    172 
    173         public void angFix(EastNorth point) {
    174                 EastNorth en3 = en[2];
    175                 EastNorth mid = en[0].getCenter(en3);
    176                 double radius = en3.distance(mid);
    177                 heading = mid.heading(point);
    178                 heading = en[0].heading(mid.add(Math.sin(heading) * radius, Math.cos(heading) * radius));
    179                 setLengthWidth(projection1(en3), projection2(en3));
    180                 en[2] = en3;
    181         }
    182 
    183         public void paint(Graphics2D g, MapView mv) {
    184                 if (len == 0)
    185                         return;
    186                 GeneralPath b = new GeneralPath();
    187                 Point pp1 = mv.getPoint(eastNorth2latlon(en[0]));
    188                 Point pp2 = mv.getPoint(eastNorth2latlon(en[1]));
    189                 Point pp3 = mv.getPoint(eastNorth2latlon(en[2]));
    190                 Point pp4 = mv.getPoint(eastNorth2latlon(en[3]));
    191 
    192                 b.moveTo(pp1.x, pp1.y);
    193                 b.lineTo(pp2.x, pp2.y);
    194                 b.lineTo(pp3.x, pp3.y);
    195                 b.lineTo(pp4.x, pp4.y);
    196                 b.lineTo(pp1.x, pp1.y);
    197                 g.draw(b);
    198         }
    199 
    200         private Node findNode(EastNorth en) {
    201                 DataSet ds = Main.main.getCurrentDataSet();
    202                 LatLon l = eastNorth2latlon(en);
    203                 List<Node> nodes = ds.searchNodes(new BBox(l.lon() - 0.0000001, l.lat() - 0.0000001,
    204                                 l.lon() + 0.0000001, l.lat() + 0.0000001));
    205                 Node bestnode = null;
    206                 double mindist = 0.0003;
    207                 for (Node n : nodes) {
    208                         double dist = n.getCoor().distanceSq(l);
    209                         if (dist < mindist && OsmPrimitive.isUsablePredicate.evaluate(n)) {
    210                                 bestnode = n;
    211                                 mindist = dist;
    212                         }
    213                 }
    214                 return bestnode;
    215         }
    216 
    217         public Way create() {
    218                 if (len == 0)
    219                         return null;
    220                 final boolean[] created = new boolean[4];
    221                 final Node[] nodes = new Node[4];
    222                 for (int i = 0; i < 4; i++) {
    223 
    224                         Node n = findNode(en[i]);
    225                         if (n == null) {
    226                                 nodes[i] = new Node(eastNorth2latlon(en[i]));
    227                                 created[i] = true;
    228                         } else {
    229                                 nodes[i] = n;
    230                                 created[i] = false;
    231                         }
    232                         if (nodes[i].getCoor().isOutSideWorld()) {
    233                                 JOptionPane.showMessageDialog(Main.parent,
    234                                                 tr("Cannot place building outside of the world."));
    235                                 return null;
    236                         }
    237                 }
    238                 Way w = new Way();
    239                 w.addNode(nodes[0]);
    240                 if (projection2(en[2]) > 0 ^ len < 0) {
    241                         w.addNode(nodes[1]);
    242                         w.addNode(nodes[2]);
    243                         w.addNode(nodes[3]);
    244                 } else {
    245                         w.addNode(nodes[3]);
    246                         w.addNode(nodes[2]);
    247                         w.addNode(nodes[1]);
    248                 }
    249                 w.addNode(nodes[0]);
    250                 w.setKeys(ToolSettings.getTags());
    251                 Collection<Command> cmds = new LinkedList<Command>();
    252                 for (int i = 0; i < 4; i++) {
    253                         if (created[i])
    254                                 cmds.add(new AddCommand(nodes[i]));
    255                 }
    256                 cmds.add(new AddCommand(w));
    257                 Command c = new SequenceCommand(tr("Create building"), cmds);
    258                 Main.main.undoRedo.add(c);
    259                 return w;
    260         }
     30    private static final double eqlen = 40075004; // length of equator in metres
     31    private final EastNorth[] en = new EastNorth[4];
     32
     33    double meter = 0;
     34
     35    private double len = 0;
     36    private double width;
     37    private double heading;
     38    private AngleSnap angleSnap = new AngleSnap();
     39    private Double drawingAngle;
     40
     41    public void clearAngleSnap() {
     42        angleSnap.clear();
     43        drawingAngle = null;
     44    }
     45
     46    public void addAngleSnap(Node[] nodes) {
     47        drawingAngle = angleSnap.addSnap(nodes);
     48    }
     49
     50    public void addAngleSnap(Way way) {
     51        angleSnap.addSnap(way);
     52        if (drawingAngle == null) {
     53            drawingAngle = angleSnap.getAngle();
     54        }
     55    }
     56
     57    public double getLength() {
     58        return len;
     59    }
     60
     61    public double getWidth() {
     62        return width;
     63    }
     64
     65    public boolean isRectDrawing() {
     66        return drawingAngle != null && ToolSettings.getWidth() == 0 && ToolSettings.getLenStep() == 0;
     67    }
     68
     69    public Double getDrawingAngle() {
     70        return drawingAngle;
     71    }
     72
     73    public void reset() {
     74        len = 0;
     75
     76        for (int i = 0; i < 4; i++)
     77            en[i] = null;
     78    }
     79
     80    public EastNorth getPoint(int num) {
     81        return en[num];
     82    }
     83
     84    private void updMetrics() {
     85        meter = 2 * Math.PI / (Math.cos(Math.toRadians(eastNorth2latlon(en[0]).lat())) * eqlen);
     86        len = 0;
     87    }
     88
     89    public void setBase(EastNorth base) {
     90        en[0] = base;
     91        updMetrics();
     92    }
     93
     94    public void setBase(Node base) {
     95        en[0] = latlon2eastNorth(base.getCoor());
     96        updMetrics();
     97    }
     98
     99    /**
     100    * @returns Projection of the point to the heading vector in metres
     101    */
     102    private double projection1(EastNorth p) {
     103        final EastNorth vec = en[0].sub(p);
     104        return (Math.sin(heading) * vec.east() + Math.cos(heading) * vec.north()) / meter;
     105    }
     106
     107    /**
     108    * @returns Projection of the point to the perpendicular of the heading
     109    *          vector in metres
     110    */
     111    private double projection2(EastNorth p) {
     112        final EastNorth vec = en[0].sub(p);
     113        return (Math.cos(heading) * vec.east() - Math.sin(heading) * vec.north()) / meter;
     114    }
     115
     116    private void updatePos() {
     117        if (len == 0)
     118            return;
     119        final EastNorth p1 = en[0];
     120        en[1] = new EastNorth(p1.east() + Math.sin(heading) * len * meter, p1.north() + Math.cos(heading) * len * meter);
     121        en[2] = new EastNorth(p1.east() + Math.sin(heading) * len * meter + Math.cos(heading) * width * meter,
     122                p1.north() + Math.cos(heading) * len * meter - Math.sin(heading) * width * meter);
     123        en[3] = new EastNorth(p1.east() + Math.cos(heading) * width * meter,
     124                p1.north() - Math.sin(heading) * width * meter);
     125    }
     126
     127    public void setLengthWidth(double length, double width) {
     128        this.len = length;
     129        this.width = width;
     130        updatePos();
     131    }
     132
     133    public void setWidth(EastNorth p3) {
     134        this.width = projection2(p3);
     135        updatePos();
     136    }
     137
     138    public void setPlace(EastNorth p2, double width, double lenstep, boolean ignoreConstraints) {
     139        if (en[0] == null)
     140            throw new IllegalStateException("setPlace() called without the base point");
     141        this.heading = en[0].heading(p2);
     142        if (!ignoreConstraints)
     143            this.heading = angleSnap.snapAngle(this.heading);
     144
     145        this.width = width;
     146        this.len = projection1(p2);
     147        if (lenstep > 0 && !ignoreConstraints)
     148            this.len = Math.round(this.len / lenstep) * lenstep;
     149
     150        updatePos();
     151
     152        Main.map.statusLine.setHeading(Math.toDegrees(heading));
     153        if (this.drawingAngle != null && !ignoreConstraints) {
     154            double ang = Math.toDegrees(heading - this.drawingAngle);
     155            if (ang < 0)
     156                ang += 360;
     157            if (ang > 360)
     158                ang -= 360;
     159            Main.map.statusLine.setAngle(ang);
     160        }
     161    }
     162
     163    public void setPlaceRect(EastNorth p2) {
     164        if (en[0] == null)
     165            throw new IllegalStateException("SetPlaceRect() called without the base point");
     166        if (!isRectDrawing())
     167            throw new IllegalStateException("Invalid drawing mode");
     168        heading = drawingAngle;
     169        setLengthWidth(projection1(p2), projection2(p2));
     170        Main.map.statusLine.setHeading(Math.toDegrees(heading));
     171    }
     172
     173    public void angFix(EastNorth point) {
     174        EastNorth en3 = en[2];
     175        EastNorth mid = en[0].getCenter(en3);
     176        double radius = en3.distance(mid);
     177        heading = mid.heading(point);
     178        heading = en[0].heading(mid.add(Math.sin(heading) * radius, Math.cos(heading) * radius));
     179        setLengthWidth(projection1(en3), projection2(en3));
     180        en[2] = en3;
     181    }
     182
     183    public void paint(Graphics2D g, MapView mv) {
     184        if (len == 0)
     185            return;
     186        GeneralPath b = new GeneralPath();
     187        Point pp1 = mv.getPoint(eastNorth2latlon(en[0]));
     188        Point pp2 = mv.getPoint(eastNorth2latlon(en[1]));
     189        Point pp3 = mv.getPoint(eastNorth2latlon(en[2]));
     190        Point pp4 = mv.getPoint(eastNorth2latlon(en[3]));
     191
     192        b.moveTo(pp1.x, pp1.y);
     193        b.lineTo(pp2.x, pp2.y);
     194        b.lineTo(pp3.x, pp3.y);
     195        b.lineTo(pp4.x, pp4.y);
     196        b.lineTo(pp1.x, pp1.y);
     197        g.draw(b);
     198    }
     199
     200    private Node findNode(EastNorth en) {
     201        DataSet ds = Main.main.getCurrentDataSet();
     202        LatLon l = eastNorth2latlon(en);
     203        List<Node> nodes = ds.searchNodes(new BBox(l.lon() - 0.0000001, l.lat() - 0.0000001,
     204                l.lon() + 0.0000001, l.lat() + 0.0000001));
     205        Node bestnode = null;
     206        double mindist = 0.0003;
     207        for (Node n : nodes) {
     208            double dist = n.getCoor().distanceSq(l);
     209            if (dist < mindist && OsmPrimitive.isUsablePredicate.evaluate(n)) {
     210                bestnode = n;
     211                mindist = dist;
     212            }
     213        }
     214        return bestnode;
     215    }
     216
     217    public Way create() {
     218        if (len == 0)
     219            return null;
     220        final boolean[] created = new boolean[4];
     221        final Node[] nodes = new Node[4];
     222        for (int i = 0; i < 4; i++) {
     223
     224            Node n = findNode(en[i]);
     225            if (n == null) {
     226                nodes[i] = new Node(eastNorth2latlon(en[i]));
     227                created[i] = true;
     228            } else {
     229                nodes[i] = n;
     230                created[i] = false;
     231            }
     232            if (nodes[i].getCoor().isOutSideWorld()) {
     233                JOptionPane.showMessageDialog(Main.parent,
     234                        tr("Cannot place building outside of the world."));
     235                return null;
     236            }
     237        }
     238        Way w = new Way();
     239        w.addNode(nodes[0]);
     240        if (projection2(en[2]) > 0 ^ len < 0) {
     241            w.addNode(nodes[1]);
     242            w.addNode(nodes[2]);
     243            w.addNode(nodes[3]);
     244        } else {
     245            w.addNode(nodes[3]);
     246            w.addNode(nodes[2]);
     247            w.addNode(nodes[1]);
     248        }
     249        w.addNode(nodes[0]);
     250        w.setKeys(ToolSettings.getTags());
     251        Collection<Command> cmds = new LinkedList<Command>();
     252        for (int i = 0; i < 4; i++) {
     253            if (created[i])
     254                cmds.add(new AddCommand(nodes[i]));
     255        }
     256        cmds.add(new AddCommand(w));
     257        Command c = new SequenceCommand(tr("Create building"), cmds);
     258        Main.main.undoRedo.add(c);
     259        return w;
     260    }
    261261}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/BuildingSizeAction.java

    r21846 r23190  
    1212public class BuildingSizeAction extends JosmAction {
    1313
    14         public BuildingSizeAction() {
    15                 super(tr("Set buildings size"), "mapmode/building", tr("Set buildings size"),
    16                                 Shortcut.registerShortcut("edit:buildingsdialog",
    17                                 tr("Edit: {0}", tr("Set buildings size")),
    18                                 KeyEvent.VK_W, Shortcut.GROUP_EDIT,
    19                                 Shortcut.SHIFT_DEFAULT),
    20                                 true);
    21         }
     14    public BuildingSizeAction() {
     15        super(tr("Set buildings size"), "mapmode/building", tr("Set buildings size"),
     16                Shortcut.registerShortcut("edit:buildingsdialog",
     17                tr("Edit: {0}", tr("Set buildings size")),
     18                KeyEvent.VK_W, Shortcut.GROUP_EDIT,
     19                Shortcut.SHIFT_DEFAULT),
     20                true);
     21    }
    2222
    23         public void actionPerformed(ActionEvent arg0) {
    24                 BuildingSizeDialog dlg = new BuildingSizeDialog();
    25                 if (dlg.getValue() == 1) {
    26                         dlg.saveSettings();
    27                 }
    28         }
     23    public void actionPerformed(ActionEvent arg0) {
     24        BuildingSizeDialog dlg = new BuildingSizeDialog();
     25        if (dlg.getValue() == 1) {
     26            dlg.saveSettings();
     27        }
     28    }
    2929}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/BuildingSizeDialog.java

    r22529 r23190  
    2323@SuppressWarnings("serial")
    2424public class BuildingSizeDialog extends ExtendedDialog {
    25         private JFormattedTextField twidth = new JFormattedTextField(NumberFormat.getInstance());
    26         private JFormattedTextField tlenstep = new JFormattedTextField(NumberFormat.getInstance());
    27         private JCheckBox caddr = new JCheckBox(tr("Use Address dialog"));
    28         private JCheckBox cAutoSelect = new JCheckBox(tr("Auto-select building"));
     25    private JFormattedTextField twidth = new JFormattedTextField(NumberFormat.getInstance());
     26    private JFormattedTextField tlenstep = new JFormattedTextField(NumberFormat.getInstance());
     27    private JCheckBox caddr = new JCheckBox(tr("Use Address dialog"));
     28    private JCheckBox cAutoSelect = new JCheckBox(tr("Auto-select building"));
    2929
    30         static void addLabelled(JPanel panel, String str, Component c) {
    31                 JLabel label = new JLabel(str);
    32                 panel.add(label, GBC.std());
    33                 label.setLabelFor(c);
    34                 panel.add(c, GBC.eol().fill(GBC.HORIZONTAL));
    35         }
     30    static void addLabelled(JPanel panel, String str, Component c) {
     31        JLabel label = new JLabel(str);
     32        panel.add(label, GBC.std());
     33        label.setLabelFor(c);
     34        panel.add(c, GBC.eol().fill(GBC.HORIZONTAL));
     35    }
    3636
    37         public BuildingSizeDialog() {
    38                 super(Main.parent, tr("Set buildings size"),
    39                                 new String[] { tr("OK"), tr("Cancel") },
    40                                 true);
    41                 contentInsets = new Insets(15, 15, 5, 15);
    42                 setButtonIcons(new String[] { "ok.png", "cancel.png" });
     37    public BuildingSizeDialog() {
     38        super(Main.parent, tr("Set buildings size"),
     39                new String[] { tr("OK"), tr("Cancel") },
     40                true);
     41        contentInsets = new Insets(15, 15, 5, 15);
     42        setButtonIcons(new String[] { "ok.png", "cancel.png" });
    4343
    44                 final JPanel panel = new JPanel(new GridBagLayout());
    45                 addLabelled(panel, tr("Buildings width:"), twidth);
    46                 addLabelled(panel, tr("Length step:"), tlenstep);
    47                 panel.add(caddr, GBC.eol().fill(GBC.HORIZONTAL));
    48                 panel.add(cAutoSelect, GBC.eol().fill(GBC.HORIZONTAL));
     44        final JPanel panel = new JPanel(new GridBagLayout());
     45        addLabelled(panel, tr("Buildings width:"), twidth);
     46        addLabelled(panel, tr("Length step:"), tlenstep);
     47        panel.add(caddr, GBC.eol().fill(GBC.HORIZONTAL));
     48        panel.add(cAutoSelect, GBC.eol().fill(GBC.HORIZONTAL));
    4949
    50                 twidth.setValue(ToolSettings.getWidth());
    51                 tlenstep.setValue(ToolSettings.getLenStep());
    52                 caddr.setSelected(ToolSettings.isUsingAddr());
    53                 cAutoSelect.setSelected(ToolSettings.isAutoSelect());
     50        twidth.setValue(ToolSettings.getWidth());
     51        tlenstep.setValue(ToolSettings.getLenStep());
     52        caddr.setSelected(ToolSettings.isUsingAddr());
     53        cAutoSelect.setSelected(ToolSettings.isAutoSelect());
    5454
    55                 JButton bAdv = new JButton(tr("Advanced..."));
    56                 bAdv.addActionListener(new ActionListener() {
    57                         @Override
    58                         public void actionPerformed(ActionEvent arg0) {
    59                                 AdvancedSettingsDialog dlg = new AdvancedSettingsDialog();
    60                                 if (dlg.getValue() == 1) {
    61                                         dlg.saveSettings();
    62                                 }
    63                         }
    64                 });
    65                 panel.add(bAdv, GBC.eol().insets(0, 5, 0, 0).anchor(GBC.EAST));
     55        JButton bAdv = new JButton(tr("Advanced..."));
     56        bAdv.addActionListener(new ActionListener() {
     57            @Override
     58            public void actionPerformed(ActionEvent arg0) {
     59                AdvancedSettingsDialog dlg = new AdvancedSettingsDialog();
     60                if (dlg.getValue() == 1) {
     61                    dlg.saveSettings();
     62                }
     63            }
     64        });
     65        panel.add(bAdv, GBC.eol().insets(0, 5, 0, 0).anchor(GBC.EAST));
    6666
    67                 setContent(panel);
    68                 setupDialog();
    69                 setVisible(true);
    70         }
     67        setContent(panel);
     68        setupDialog();
     69        setVisible(true);
     70    }
    7171
    72         public double width() {
    73                 try {
    74                         return NumberFormat.getInstance().parse(twidth.getText()).doubleValue();
    75                 } catch (ParseException e) {
    76                         return 0;
    77                 }
    78         }
     72    public double width() {
     73        try {
     74            return NumberFormat.getInstance().parse(twidth.getText()).doubleValue();
     75        } catch (ParseException e) {
     76            return 0;
     77        }
     78    }
    7979
    80         public double lenstep() {
    81                 try {
    82                         return NumberFormat.getInstance().parse(tlenstep.getText()).doubleValue();
    83                 } catch (ParseException e) {
    84                         return 0;
    85                 }
    86         }
     80    public double lenstep() {
     81        try {
     82            return NumberFormat.getInstance().parse(tlenstep.getText()).doubleValue();
     83        } catch (ParseException e) {
     84            return 0;
     85        }
     86    }
    8787
    88         public boolean useAddr() {
    89                 return caddr.isSelected();
    90         }
     88    public boolean useAddr() {
     89        return caddr.isSelected();
     90    }
    9191
    92         public void saveSettings() {
    93                 ToolSettings.setSizes(width(), lenstep());
    94                 ToolSettings.setAddrDialog(useAddr());
    95                 ToolSettings.setAutoSelect(cAutoSelect.isSelected());
    96         }
     92    public void saveSettings() {
     93        ToolSettings.setSizes(width(), lenstep());
     94        ToolSettings.setAddrDialog(useAddr());
     95        ToolSettings.setAutoSelect(cAutoSelect.isSelected());
     96    }
    9797}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/BuildingsToolsPlugin.java

    r21875 r23190  
    1212
    1313public class BuildingsToolsPlugin extends Plugin {
    14         public static Mercator proj = new Mercator();
     14    public static Mercator proj = new Mercator();
    1515
    16         public static EastNorth latlon2eastNorth(LatLon p) {
    17                 return proj.latlon2eastNorth(p);
    18         }
    19         public static LatLon eastNorth2latlon(EastNorth p) {
    20                 return proj.eastNorth2latlon(p);
    21         }
     16    public static EastNorth latlon2eastNorth(LatLon p) {
     17        return proj.latlon2eastNorth(p);
     18    }
     19    public static LatLon eastNorth2latlon(EastNorth p) {
     20        return proj.eastNorth2latlon(p);
     21    }
    2222
    23         public BuildingsToolsPlugin(PluginInformation info) {
    24                 super(info);
    25                 Main.main.menu.editMenu.addSeparator();
    26                 MainMenu.add(Main.main.menu.editMenu, new BuildingSizeAction());
    27         }
    28         @Override public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
    29                 if (oldFrame==null && newFrame!=null) {
    30                         Main.map.addMapMode(new IconToggleButton(new DrawBuildingAction(Main.map)));
    31                 }
    32         }
     23    public BuildingsToolsPlugin(PluginInformation info) {
     24        super(info);
     25        Main.main.menu.editMenu.addSeparator();
     26        MainMenu.add(Main.main.menu.editMenu, new BuildingSizeAction());
     27    }
     28    @Override public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
     29        if (oldFrame==null && newFrame!=null) {
     30            Main.map.addMapMode(new IconToggleButton(new DrawBuildingAction(Main.map)));
     31        }
     32    }
    3333}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/DrawBuildingAction.java

    r22904 r23190  
    4242@SuppressWarnings("serial")
    4343public class DrawBuildingAction extends MapMode implements MapViewPaintable, AWTEventListener, SelectionChangedListener {
    44         private enum Mode {
    45                 None, Drawing, DrawingWidth, DrawingAngFix
    46         }
    47 
    48         final private Cursor cursorCrosshair;
    49         final private Cursor cursorJoinNode;
    50         private Cursor currCursor;
    51         private Cursor customCursor;
    52 
    53         private Mode mode = Mode.None;
    54         private Mode nextMode = Mode.None;
    55 
    56         private Color selectedColor;
    57         private Point drawStartPos;
    58         private Point mousePos;
    59         private boolean isCtrlDown;
    60         private boolean isShiftDown;
    61 
    62         Building building = new Building();
    63 
    64         public DrawBuildingAction(MapFrame mapFrame) {
    65                 super(tr("Draw buildings"), "building", tr("Draw buildings"),
    66                                 Shortcut.registerShortcut("mapmode:buildings",
    67                                                 tr("Mode: {0}", tr("Draw buildings")),
    68                                                 KeyEvent.VK_W, Shortcut.GROUP_EDIT),
    69                                 mapFrame, getCursor());
    70 
    71                 cursorCrosshair = getCursor();
    72                 cursorJoinNode = ImageProvider.getCursor("crosshair", "joinnode");
    73                 currCursor = cursorCrosshair;
    74 
    75                 selectedColor = Main.pref.getColor(marktr("selected"), Color.red);
    76         }
    77 
    78         private static Cursor getCursor() {
    79                 try {
    80                         return ImageProvider.getCursor("crosshair", null);
    81                 } catch (Exception e) {
    82                 }
    83                 return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
    84         }
    85 
    86         /**
    87         * Displays the given cursor instead of the normal one
    88          *
    89         * @param Cursors
    90         *            One of the available cursors
    91         */
    92         private void setCursor(final Cursor c) {
    93                 if (currCursor.equals(c))
    94                         return;
    95                 try {
    96                         // We invoke this to prevent strange things from happening
    97                         EventQueue.invokeLater(new Runnable() {
    98                                 public void run() {
    99                                         // Don't change cursor when mode has changed already
    100                                         if (!(Main.map.mapMode instanceof DrawBuildingAction))
    101                                                 return;
    102                                         Main.map.mapView.setCursor(c);
    103                                 }
    104                         });
    105                         currCursor = c;
    106                 } catch (Exception e) {
    107                 }
    108         }
    109 
    110         private static void showAddrDialog(Way w) {
    111                 AddressDialog dlg = new AddressDialog();
    112                 int answer = dlg.getValue();
    113                 if (answer == 1) {
    114                         dlg.saveValues();
    115                         String tmp;
    116                         tmp = dlg.getHouseNum();
    117                         if (tmp != null && tmp != "")
    118                                 w.put("addr:housenumber", tmp);
    119                         tmp = dlg.getStreetName();
    120                         if (tmp != null && tmp != "")
    121                                 w.put("addr:street", tmp);
    122                 }
    123         }
    124 
    125         @Override
    126         public void enterMode() {
    127                 super.enterMode();
    128                 if (getCurrentDataSet() == null) {
    129                         Main.map.selectSelectTool(false);
    130                         return;
    131                 }
    132                 currCursor = cursorCrosshair;
    133                 Main.map.mapView.addMouseListener(this);
    134                 Main.map.mapView.addMouseMotionListener(this);
    135                 Main.map.mapView.addTemporaryLayer(this);
    136                 DataSet.addSelectionListener(this);
    137                 updateSnap(getCurrentDataSet().getSelected());
    138                 try {
    139                         Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
    140                 } catch (SecurityException ex) {
    141                 }
    142         }
    143 
    144         @Override
    145         public void exitMode() {
    146                 super.exitMode();
    147                 Main.map.mapView.removeMouseListener(this);
    148                 Main.map.mapView.removeMouseMotionListener(this);
    149                 Main.map.mapView.removeTemporaryLayer(this);
    150                 DataSet.removeSelectionListener(this);
    151                 try {
    152                         Toolkit.getDefaultToolkit().removeAWTEventListener(this);
    153                 } catch (SecurityException ex) {
    154                 }
    155                 if (mode != Mode.None)
    156                         Main.map.mapView.repaint();
    157                 mode = Mode.None;
    158         }
    159 
    160         public void cancelDrawing() {
    161                 mode = Mode.None;
    162                 if (Main.map == null || Main.map.mapView == null)
    163                         return;
    164                 Main.map.statusLine.setHeading(-1);
    165                 Main.map.statusLine.setAngle(-1);
    166                 building.reset();
    167                 Main.map.mapView.repaint();
    168                 updateStatusLine();
    169         }
    170 
    171         public void eventDispatched(AWTEvent arg0) {
    172                 if (!(arg0 instanceof KeyEvent))
    173                         return;
    174                 KeyEvent ev = (KeyEvent) arg0;
    175                 int modifiers = ev.getModifiersEx();
    176                 boolean isCtrlDown = (modifiers & KeyEvent.CTRL_DOWN_MASK) != 0;
    177                 boolean isShiftDown = (modifiers & KeyEvent.SHIFT_DOWN_MASK) != 0;
    178                 if (this.isCtrlDown != isCtrlDown || this.isShiftDown != isShiftDown) {
    179                         this.isCtrlDown = isCtrlDown;
    180                         this.isShiftDown = isShiftDown;
    181                         processMouseEvent(null);
    182                         updCursor();
    183                         if (mode != Mode.None)
    184                                 Main.map.mapView.repaint();
    185                 }
    186 
    187                 if (ev.getKeyCode() == KeyEvent.VK_ESCAPE && ev.getID() == KeyEvent.KEY_PRESSED) {
    188                         if (mode != Mode.None)
    189                                 ev.consume();
    190 
    191                         cancelDrawing();
    192                 }
    193         }
    194 
    195         private EastNorth getEastNorth() {
    196                 Node n;
    197                 if (isCtrlDown) {
    198                         n = null;
    199                 } else {
    200                         n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isUsablePredicate);
    201                 }
    202                 if (n == null) {
    203                         return latlon2eastNorth(Main.map.mapView.getLatLon(mousePos.x, mousePos.y));
    204                 } else {
    205                         return latlon2eastNorth(n.getCoor());
    206                 }
    207         }
    208 
    209         private boolean isRectDrawing() {
    210                 return building.isRectDrawing() && (!isShiftDown || ToolSettings.isBBMode());
    211         }
    212 
    213         private Mode modeDrawing() {
    214                 EastNorth p = getEastNorth();
    215                 if (isRectDrawing()) {
    216                         building.setPlaceRect(p);
    217                         return isShiftDown ? Mode.DrawingAngFix : Mode.None;
    218                 } else {
    219                         building.setPlace(p, ToolSettings.getWidth(), ToolSettings.getLenStep(), isShiftDown);
    220                         Main.map.statusLine.setDist(building.getLength());
    221                         return this.nextMode = ToolSettings.getWidth() == 0 ? Mode.DrawingWidth : Mode.None;
    222                 }
    223         }
    224 
    225         private Mode modeDrawingWidth() {
    226                 building.setWidth(getEastNorth());
    227                 Main.map.statusLine.setDist(Math.abs(building.getWidth()));
    228                 return Mode.None;
    229         }
    230 
    231         private Mode modeDrawingAngFix() {
    232                 building.angFix(getEastNorth());
    233                 return Mode.None;
    234         }
    235 
    236         private void processMouseEvent(MouseEvent e) {
    237                 if (e != null) {
    238                         mousePos = e.getPoint();
    239                         isCtrlDown = e.isControlDown();
    240                         isShiftDown = e.isShiftDown();
    241                 }
    242                 if (mode == Mode.None) {
    243                         nextMode = Mode.None;
    244                         return;
    245                 }
    246 
    247                 if (mode == Mode.Drawing) {
    248                         nextMode = modeDrawing();
    249                 } else if (mode == Mode.DrawingWidth) {
    250                         nextMode = modeDrawingWidth();
    251                 } else if (mode == Mode.DrawingAngFix) {
    252                         nextMode = modeDrawingAngFix();
    253                 } else
    254                         throw new AssertionError("Invalid drawing mode");
    255         }
    256 
    257         public void paint(Graphics2D g, MapView mv, Bounds bbox) {
    258                 if (mode == Mode.None)
    259                         return;
    260                 if (building.getLength() == 0)
    261                         return;
    262 
    263                 g.setColor(selectedColor);
    264                 g.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    265 
    266                 building.paint(g, mv);
    267 
    268                 g.setStroke(new BasicStroke(1));
    269 
    270         }
    271 
    272         private void drawingStart(MouseEvent e) {
    273                 mousePos = e.getPoint();
    274                 drawStartPos = mousePos;
    275 
    276                 Node n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isUsablePredicate);
    277                 if (n == null) {
    278                         building.setBase(latlon2eastNorth(Main.map.mapView.getLatLon(mousePos.x, mousePos.y)));
    279                 } else {
    280                         building.setBase(n);
    281                 }
    282                 mode = Mode.Drawing;
    283                 updateStatusLine();
    284         }
    285 
    286         private void drawingAdvance(MouseEvent e) {
    287                 processMouseEvent(e);
    288                 if (this.mode != Mode.None && this.nextMode == Mode.None) {
    289                         drawingFinish();
    290                 } else {
    291                         mode = this.nextMode;
    292                         updateStatusLine();
    293                 }
    294         }
    295 
    296         private void drawingFinish() {
    297                 if (building.getLength() != 0) {
    298                         Way w = building.create();
    299                         if (w != null && ToolSettings.isUsingAddr())
    300                                 showAddrDialog(w);
    301                         if (ToolSettings.isAutoSelect() &&
    302                                         (Main.main.getCurrentDataSet().getSelected().isEmpty() || isShiftDown)) {
    303                                 Main.main.getCurrentDataSet().setSelected(w);
    304                         }
    305                 }
    306                 cancelDrawing();
    307         }
    308 
    309         @Override
    310         public void mousePressed(MouseEvent e) {
    311                 if (e.getButton() != MouseEvent.BUTTON1)
    312                         return;
    313                 if (!Main.map.mapView.isActiveLayerDrawable())
    314                         return;
    315 
    316                 if (mode == Mode.None)
    317                         drawingStart(e);
    318         }
    319 
    320         @Override
    321         public void mouseDragged(MouseEvent e) {
    322                 processMouseEvent(e);
    323                 updCursor();
    324                 if (mode != Mode.None)
    325                         Main.map.mapView.repaint();
    326         }
    327 
    328         @Override
    329         public void mouseReleased(MouseEvent e) {
    330                 if (e.getButton() != MouseEvent.BUTTON1)
    331                         return;
    332                 if (!Main.map.mapView.isActiveLayerDrawable())
    333                         return;
    334                 boolean dragged = true;
    335                 if (drawStartPos != null)
    336                         dragged = e.getPoint().distance(drawStartPos) > 10;
    337                 drawStartPos = null;
    338 
    339                 if (mode == Mode.Drawing && !dragged)
    340                         return;
    341                 if (mode == Mode.None)
    342                         return;
    343 
    344                 drawingAdvance(e);
    345         }
    346 
    347         private void updCursor() {
    348                 if (mousePos == null)
    349                         return;
    350                 if (!Main.isDisplayingMapView())
    351                         return;
    352                 Node n = null;
    353                 if (!isCtrlDown)
    354                         n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isUsablePredicate);
    355                 if (n != null) {
    356                         setCursor(cursorJoinNode);
    357                 } else {
    358                         if (customCursor != null && (!isShiftDown || isRectDrawing()))
    359                                 setCursor(customCursor);
    360                         else
    361                                 setCursor(cursorCrosshair);
    362                 }
    363 
    364         }
    365 
    366         @Override
    367         public void mouseMoved(MouseEvent e) {
    368                 if (!Main.map.mapView.isActiveLayerDrawable())
    369                         return;
    370                 processMouseEvent(e);
    371                 updCursor();
    372                 if (mode != Mode.None)
    373                         Main.map.mapView.repaint();
    374         }
    375 
    376         @Override
    377         public String getModeHelpText() {
    378                 if (mode == Mode.None)
    379                         return tr("Point on the corner of the building to start drawing");
    380                 if (mode == Mode.Drawing)
    381                         return tr("Point on opposite end of the building");
    382                 if (mode == Mode.DrawingWidth)
    383                         return tr("Set width of the building");
    384                 return "";
    385         }
    386 
    387         @Override
    388         public boolean layerIsSupported(Layer l) {
    389                 return l instanceof OsmDataLayer;
    390         }
    391 
    392         public void updateSnap(Collection<? extends OsmPrimitive> newSelection) {
    393                 building.clearAngleSnap();
    394                 // update snap only if selection isn't too big
    395                 if (newSelection.size() <= 10) {
    396                         LinkedList<Node> nodes = new LinkedList<Node>();
    397                         LinkedList<Way> ways = new LinkedList<Way>();
    398 
    399                         for (OsmPrimitive p : newSelection) {
    400                                 switch (p.getType()) {
    401                                 case NODE:
    402                                         nodes.add((Node) p);
    403                                         break;
    404                                 case WAY:
    405                                         ways.add((Way) p);
    406                                         break;
    407                                 }
    408                         }
    409 
    410                         building.addAngleSnap(nodes.toArray(new Node[0]));
    411                         for (Way w : ways) {
    412                                 building.addAngleSnap(w);
    413                         }
    414                 }
    415                 updateCustomCursor();
    416         }
    417 
    418         private void updateCustomCursor() {
    419                 Double angle = building.getDrawingAngle();
    420                 if (angle == null || !ToolSettings.isSoftCursor()) {
    421                         customCursor = null;
    422                         return;
    423                 }
    424                 final int R = 9; // crosshair outer radius
    425                 final int r = 3; // crosshair inner radius
    426                 BufferedImage img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
    427                 Graphics2D g = img.createGraphics();
    428 
    429                 GeneralPath b = new GeneralPath();
    430                 b.moveTo(16 - Math.cos(angle) * R, 16 - Math.sin(angle) * R);
    431                 b.lineTo(16 - Math.cos(angle) * r, 16 - Math.sin(angle) * r);
    432                 b.moveTo(16 + Math.cos(angle) * R, 16 + Math.sin(angle) * R);
    433                 b.lineTo(16 + Math.cos(angle) * r, 16 + Math.sin(angle) * r);
    434                 b.moveTo(16 + Math.sin(angle) * R, 16 - Math.cos(angle) * R);
    435                 b.lineTo(16 + Math.sin(angle) * r, 16 - Math.cos(angle) * r);
    436                 b.moveTo(16 - Math.sin(angle) * R, 16 + Math.cos(angle) * R);
    437                 b.lineTo(16 - Math.sin(angle) * r, 16 + Math.cos(angle) * r);
    438 
    439                 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    440                 g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    441 
    442                 g.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    443                 g.setColor(Color.WHITE);
    444                 g.draw(b);
    445 
    446                 g.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    447                 g.setColor(Color.BLACK);
    448                 g.draw(b);
    449 
    450                 customCursor = Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(16, 16), "custom crosshair");
    451 
    452                 updCursor();
    453         }
    454 
    455         public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
    456                 updateSnap(newSelection);
    457         }
     44    private enum Mode {
     45        None, Drawing, DrawingWidth, DrawingAngFix
     46    }
     47
     48    final private Cursor cursorCrosshair;
     49    final private Cursor cursorJoinNode;
     50    private Cursor currCursor;
     51    private Cursor customCursor;
     52
     53    private Mode mode = Mode.None;
     54    private Mode nextMode = Mode.None;
     55
     56    private Color selectedColor;
     57    private Point drawStartPos;
     58    private Point mousePos;
     59    private boolean isCtrlDown;
     60    private boolean isShiftDown;
     61
     62    Building building = new Building();
     63
     64    public DrawBuildingAction(MapFrame mapFrame) {
     65        super(tr("Draw buildings"), "building", tr("Draw buildings"),
     66                Shortcut.registerShortcut("mapmode:buildings",
     67                        tr("Mode: {0}", tr("Draw buildings")),
     68                        KeyEvent.VK_W, Shortcut.GROUP_EDIT),
     69                mapFrame, getCursor());
     70
     71        cursorCrosshair = getCursor();
     72        cursorJoinNode = ImageProvider.getCursor("crosshair", "joinnode");
     73        currCursor = cursorCrosshair;
     74
     75        selectedColor = Main.pref.getColor(marktr("selected"), Color.red);
     76    }
     77
     78    private static Cursor getCursor() {
     79        try {
     80            return ImageProvider.getCursor("crosshair", null);
     81        } catch (Exception e) {
     82        }
     83        return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
     84    }
     85
     86    /**
     87    * Displays the given cursor instead of the normal one
     88     *
     89    * @param Cursors
     90    *            One of the available cursors
     91    */
     92    private void setCursor(final Cursor c) {
     93        if (currCursor.equals(c))
     94            return;
     95        try {
     96            // We invoke this to prevent strange things from happening
     97            EventQueue.invokeLater(new Runnable() {
     98                public void run() {
     99                    // Don't change cursor when mode has changed already
     100                    if (!(Main.map.mapMode instanceof DrawBuildingAction))
     101                        return;
     102                    Main.map.mapView.setCursor(c);
     103                }
     104            });
     105            currCursor = c;
     106        } catch (Exception e) {
     107        }
     108    }
     109
     110    private static void showAddrDialog(Way w) {
     111        AddressDialog dlg = new AddressDialog();
     112        int answer = dlg.getValue();
     113        if (answer == 1) {
     114            dlg.saveValues();
     115            String tmp;
     116            tmp = dlg.getHouseNum();
     117            if (tmp != null && tmp != "")
     118                w.put("addr:housenumber", tmp);
     119            tmp = dlg.getStreetName();
     120            if (tmp != null && tmp != "")
     121                w.put("addr:street", tmp);
     122        }
     123    }
     124
     125    @Override
     126    public void enterMode() {
     127        super.enterMode();
     128        if (getCurrentDataSet() == null) {
     129            Main.map.selectSelectTool(false);
     130            return;
     131        }
     132        currCursor = cursorCrosshair;
     133        Main.map.mapView.addMouseListener(this);
     134        Main.map.mapView.addMouseMotionListener(this);
     135        Main.map.mapView.addTemporaryLayer(this);
     136        DataSet.addSelectionListener(this);
     137        updateSnap(getCurrentDataSet().getSelected());
     138        try {
     139            Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
     140        } catch (SecurityException ex) {
     141        }
     142    }
     143
     144    @Override
     145    public void exitMode() {
     146        super.exitMode();
     147        Main.map.mapView.removeMouseListener(this);
     148        Main.map.mapView.removeMouseMotionListener(this);
     149        Main.map.mapView.removeTemporaryLayer(this);
     150        DataSet.removeSelectionListener(this);
     151        try {
     152            Toolkit.getDefaultToolkit().removeAWTEventListener(this);
     153        } catch (SecurityException ex) {
     154        }
     155        if (mode != Mode.None)
     156            Main.map.mapView.repaint();
     157        mode = Mode.None;
     158    }
     159
     160    public void cancelDrawing() {
     161        mode = Mode.None;
     162        if (Main.map == null || Main.map.mapView == null)
     163            return;
     164        Main.map.statusLine.setHeading(-1);
     165        Main.map.statusLine.setAngle(-1);
     166        building.reset();
     167        Main.map.mapView.repaint();
     168        updateStatusLine();
     169    }
     170
     171    public void eventDispatched(AWTEvent arg0) {
     172        if (!(arg0 instanceof KeyEvent))
     173            return;
     174        KeyEvent ev = (KeyEvent) arg0;
     175        int modifiers = ev.getModifiersEx();
     176        boolean isCtrlDown = (modifiers & KeyEvent.CTRL_DOWN_MASK) != 0;
     177        boolean isShiftDown = (modifiers & KeyEvent.SHIFT_DOWN_MASK) != 0;
     178        if (this.isCtrlDown != isCtrlDown || this.isShiftDown != isShiftDown) {
     179            this.isCtrlDown = isCtrlDown;
     180            this.isShiftDown = isShiftDown;
     181            processMouseEvent(null);
     182            updCursor();
     183            if (mode != Mode.None)
     184                Main.map.mapView.repaint();
     185        }
     186
     187        if (ev.getKeyCode() == KeyEvent.VK_ESCAPE && ev.getID() == KeyEvent.KEY_PRESSED) {
     188            if (mode != Mode.None)
     189                ev.consume();
     190
     191            cancelDrawing();
     192        }
     193    }
     194
     195    private EastNorth getEastNorth() {
     196        Node n;
     197        if (isCtrlDown) {
     198            n = null;
     199        } else {
     200            n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isUsablePredicate);
     201        }
     202        if (n == null) {
     203            return latlon2eastNorth(Main.map.mapView.getLatLon(mousePos.x, mousePos.y));
     204        } else {
     205            return latlon2eastNorth(n.getCoor());
     206        }
     207    }
     208
     209    private boolean isRectDrawing() {
     210        return building.isRectDrawing() && (!isShiftDown || ToolSettings.isBBMode());
     211    }
     212
     213    private Mode modeDrawing() {
     214        EastNorth p = getEastNorth();
     215        if (isRectDrawing()) {
     216            building.setPlaceRect(p);
     217            return isShiftDown ? Mode.DrawingAngFix : Mode.None;
     218        } else {
     219            building.setPlace(p, ToolSettings.getWidth(), ToolSettings.getLenStep(), isShiftDown);
     220            Main.map.statusLine.setDist(building.getLength());
     221            return this.nextMode = ToolSettings.getWidth() == 0 ? Mode.DrawingWidth : Mode.None;
     222        }
     223    }
     224
     225    private Mode modeDrawingWidth() {
     226        building.setWidth(getEastNorth());
     227        Main.map.statusLine.setDist(Math.abs(building.getWidth()));
     228        return Mode.None;
     229    }
     230
     231    private Mode modeDrawingAngFix() {
     232        building.angFix(getEastNorth());
     233        return Mode.None;
     234    }
     235
     236    private void processMouseEvent(MouseEvent e) {
     237        if (e != null) {
     238            mousePos = e.getPoint();
     239            isCtrlDown = e.isControlDown();
     240            isShiftDown = e.isShiftDown();
     241        }
     242        if (mode == Mode.None) {
     243            nextMode = Mode.None;
     244            return;
     245        }
     246
     247        if (mode == Mode.Drawing) {
     248            nextMode = modeDrawing();
     249        } else if (mode == Mode.DrawingWidth) {
     250            nextMode = modeDrawingWidth();
     251        } else if (mode == Mode.DrawingAngFix) {
     252            nextMode = modeDrawingAngFix();
     253        } else
     254            throw new AssertionError("Invalid drawing mode");
     255    }
     256
     257    public void paint(Graphics2D g, MapView mv, Bounds bbox) {
     258        if (mode == Mode.None)
     259            return;
     260        if (building.getLength() == 0)
     261            return;
     262
     263        g.setColor(selectedColor);
     264        g.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
     265
     266        building.paint(g, mv);
     267
     268        g.setStroke(new BasicStroke(1));
     269
     270    }
     271
     272    private void drawingStart(MouseEvent e) {
     273        mousePos = e.getPoint();
     274        drawStartPos = mousePos;
     275
     276        Node n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isUsablePredicate);
     277        if (n == null) {
     278            building.setBase(latlon2eastNorth(Main.map.mapView.getLatLon(mousePos.x, mousePos.y)));
     279        } else {
     280            building.setBase(n);
     281        }
     282        mode = Mode.Drawing;
     283        updateStatusLine();
     284    }
     285
     286    private void drawingAdvance(MouseEvent e) {
     287        processMouseEvent(e);
     288        if (this.mode != Mode.None && this.nextMode == Mode.None) {
     289            drawingFinish();
     290        } else {
     291            mode = this.nextMode;
     292            updateStatusLine();
     293        }
     294    }
     295
     296    private void drawingFinish() {
     297        if (building.getLength() != 0) {
     298            Way w = building.create();
     299            if (w != null && ToolSettings.isUsingAddr())
     300                showAddrDialog(w);
     301            if (ToolSettings.isAutoSelect() &&
     302                    (Main.main.getCurrentDataSet().getSelected().isEmpty() || isShiftDown)) {
     303                Main.main.getCurrentDataSet().setSelected(w);
     304            }
     305        }
     306        cancelDrawing();
     307    }
     308
     309    @Override
     310    public void mousePressed(MouseEvent e) {
     311        if (e.getButton() != MouseEvent.BUTTON1)
     312            return;
     313        if (!Main.map.mapView.isActiveLayerDrawable())
     314            return;
     315
     316        if (mode == Mode.None)
     317            drawingStart(e);
     318    }
     319
     320    @Override
     321    public void mouseDragged(MouseEvent e) {
     322        processMouseEvent(e);
     323        updCursor();
     324        if (mode != Mode.None)
     325            Main.map.mapView.repaint();
     326    }
     327
     328    @Override
     329    public void mouseReleased(MouseEvent e) {
     330        if (e.getButton() != MouseEvent.BUTTON1)
     331            return;
     332        if (!Main.map.mapView.isActiveLayerDrawable())
     333            return;
     334        boolean dragged = true;
     335        if (drawStartPos != null)
     336            dragged = e.getPoint().distance(drawStartPos) > 10;
     337        drawStartPos = null;
     338
     339        if (mode == Mode.Drawing && !dragged)
     340            return;
     341        if (mode == Mode.None)
     342            return;
     343
     344        drawingAdvance(e);
     345    }
     346
     347    private void updCursor() {
     348        if (mousePos == null)
     349            return;
     350        if (!Main.isDisplayingMapView())
     351            return;
     352        Node n = null;
     353        if (!isCtrlDown)
     354            n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isUsablePredicate);
     355        if (n != null) {
     356            setCursor(cursorJoinNode);
     357        } else {
     358            if (customCursor != null && (!isShiftDown || isRectDrawing()))
     359                setCursor(customCursor);
     360            else
     361                setCursor(cursorCrosshair);
     362        }
     363
     364    }
     365
     366    @Override
     367    public void mouseMoved(MouseEvent e) {
     368        if (!Main.map.mapView.isActiveLayerDrawable())
     369            return;
     370        processMouseEvent(e);
     371        updCursor();
     372        if (mode != Mode.None)
     373            Main.map.mapView.repaint();
     374    }
     375
     376    @Override
     377    public String getModeHelpText() {
     378        if (mode == Mode.None)
     379            return tr("Point on the corner of the building to start drawing");
     380        if (mode == Mode.Drawing)
     381            return tr("Point on opposite end of the building");
     382        if (mode == Mode.DrawingWidth)
     383            return tr("Set width of the building");
     384        return "";
     385    }
     386
     387    @Override
     388    public boolean layerIsSupported(Layer l) {
     389        return l instanceof OsmDataLayer;
     390    }
     391
     392    public void updateSnap(Collection<? extends OsmPrimitive> newSelection) {
     393        building.clearAngleSnap();
     394        // update snap only if selection isn't too big
     395        if (newSelection.size() <= 10) {
     396            LinkedList<Node> nodes = new LinkedList<Node>();
     397            LinkedList<Way> ways = new LinkedList<Way>();
     398
     399            for (OsmPrimitive p : newSelection) {
     400                switch (p.getType()) {
     401                case NODE:
     402                    nodes.add((Node) p);
     403                    break;
     404                case WAY:
     405                    ways.add((Way) p);
     406                    break;
     407                }
     408            }
     409
     410            building.addAngleSnap(nodes.toArray(new Node[0]));
     411            for (Way w : ways) {
     412                building.addAngleSnap(w);
     413            }
     414        }
     415        updateCustomCursor();
     416    }
     417
     418    private void updateCustomCursor() {
     419        Double angle = building.getDrawingAngle();
     420        if (angle == null || !ToolSettings.isSoftCursor()) {
     421            customCursor = null;
     422            return;
     423        }
     424        final int R = 9; // crosshair outer radius
     425        final int r = 3; // crosshair inner radius
     426        BufferedImage img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
     427        Graphics2D g = img.createGraphics();
     428
     429        GeneralPath b = new GeneralPath();
     430        b.moveTo(16 - Math.cos(angle) * R, 16 - Math.sin(angle) * R);
     431        b.lineTo(16 - Math.cos(angle) * r, 16 - Math.sin(angle) * r);
     432        b.moveTo(16 + Math.cos(angle) * R, 16 + Math.sin(angle) * R);
     433        b.lineTo(16 + Math.cos(angle) * r, 16 + Math.sin(angle) * r);
     434        b.moveTo(16 + Math.sin(angle) * R, 16 - Math.cos(angle) * R);
     435        b.lineTo(16 + Math.sin(angle) * r, 16 - Math.cos(angle) * r);
     436        b.moveTo(16 - Math.sin(angle) * R, 16 + Math.cos(angle) * R);
     437        b.lineTo(16 - Math.sin(angle) * r, 16 + Math.cos(angle) * r);
     438
     439        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     440        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
     441
     442        g.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
     443        g.setColor(Color.WHITE);
     444        g.draw(b);
     445
     446        g.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
     447        g.setColor(Color.BLACK);
     448        g.draw(b);
     449
     450        customCursor = Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(16, 16), "custom crosshair");
     451
     452        updCursor();
     453    }
     454
     455    public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
     456        updateSnap(newSelection);
     457    }
    458458}
  • applications/editors/josm/plugins/buildings_tools/src/buildings_tools/ToolSettings.java

    r22904 r23190  
    77
    88public class ToolSettings {
    9         private static double width = 0;
    10         private static double lenstep = 0;
    11         private static boolean useAddr;
    12         private static final Map<String, String> tags = new HashMap<String, String>();
    13         private static boolean autoSelect;
     9    private static double width = 0;
     10    private static double lenstep = 0;
     11    private static boolean useAddr;
     12    private static final Map<String, String> tags = new HashMap<String, String>();
     13    private static boolean autoSelect;
    1414
    15         static {
    16                 tags.put("building", "yes");
    17         }
     15    static {
     16        tags.put("building", "yes");
     17    }
    1818
    19         public static void setAddrDialog(boolean _useAddr) {
    20                 useAddr = _useAddr;
    21         }
     19    public static void setAddrDialog(boolean _useAddr) {
     20        useAddr = _useAddr;
     21    }
    2222
    23         public static void setSizes(double newwidth, double newlenstep) {
    24                 width = newwidth;
    25                 lenstep = newlenstep;
    26         }
     23    public static void setSizes(double newwidth, double newlenstep) {
     24        width = newwidth;
     25        lenstep = newlenstep;
     26    }
    2727
    28         public static double getWidth() {
    29                 return width;
    30         }
     28    public static double getWidth() {
     29        return width;
     30    }
    3131
    32         public static double getLenStep() {
    33                 return lenstep;
    34         }
     32    public static double getLenStep() {
     33        return lenstep;
     34    }
    3535
    36         public static boolean isUsingAddr() {
    37                 return useAddr;
    38         }
     36    public static boolean isUsingAddr() {
     37        return useAddr;
     38    }
    3939
    40         public static Map<String, String> getTags() {
    41                 return tags;
    42         }
     40    public static Map<String, String> getTags() {
     41        return tags;
     42    }
    4343
    44         public static void setBBMode(boolean bbmode) {
    45                 Main.pref.put("buildings_tools.bbmode", bbmode);
    46         }
     44    public static void setBBMode(boolean bbmode) {
     45        Main.pref.put("buildings_tools.bbmode", bbmode);
     46    }
    4747
    48         public static boolean isBBMode() {
    49                 return Main.pref.getBoolean("buildings_tools.bbmode", false);
    50         }
     48    public static boolean isBBMode() {
     49        return Main.pref.getBoolean("buildings_tools.bbmode", false);
     50    }
    5151
    52         public static void setSoftCursor(boolean softCursor) {
    53                 Main.pref.put("buildings_tools.softcursor", softCursor);
    54         }
     52    public static void setSoftCursor(boolean softCursor) {
     53        Main.pref.put("buildings_tools.softcursor", softCursor);
     54    }
    5555
    56         public static boolean isSoftCursor() {
    57                 return Main.pref.getBoolean("buildings_tools.softcursor", false);
    58         }
     56    public static boolean isSoftCursor() {
     57        return Main.pref.getBoolean("buildings_tools.softcursor", false);
     58    }
    5959
    60         public static boolean isAutoSelect() {
    61                 return autoSelect;
    62         }
     60    public static boolean isAutoSelect() {
     61        return autoSelect;
     62    }
    6363
    64         public static void setAutoSelect(boolean _autoSelect) {
    65                 autoSelect = _autoSelect;
    66         }
     64    public static void setAutoSelect(boolean _autoSelect) {
     65        autoSelect = _autoSelect;
     66    }
    6767}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java

    r21191 r23190  
    2525
    2626public class CacheControl implements Runnable {
    27    
     27
    2828    public static final String cLambertCC9Z = "CC";
    2929
     
    5555        return ret;
    5656    }
    57    
     57
    5858    public CacheControl(WMSLayer wmsLayer) {
    5959        cacheEnabled = Main.pref.getBoolean("cadastrewms.enableCaching", true);
     
    110110                    int reply = (Integer)pane.getValue();
    111111                    // till here
    112    
     112
    113113                    if (reply == JOptionPane.OK_OPTION && loadCache(file, wmsLayer.getLambertZone())) {
    114114                        return true;
     
    136136        }
    137137    }
    138    
     138
    139139    private void delete(File file) {
    140140        System.out.println("Delete file "+file);
     
    215215        }
    216216    }
    217    
     217
    218218    private String WMSFileExtension() {
    219219        String ext = String.valueOf((wmsLayer.getLambertZone() + 1));
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreGrabber.java

    r20390 r23190  
    5252        }
    5353    }
    54    
     54
    5555    public GeorefImage grabParcels(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax) throws IOException, OsmTransferException {
    5656        try {
     
    6363        }
    6464    }
    65    
     65
    6666    private URL getURLRaster(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
    6767        // GET /scpc/wms?version=1.1&request=GetMap&layers=CDIF:PMC@QH4480001701&format=image/png&bbox=-1186,0,13555,8830&width=576&height=345&exception=application/vnd.ogc.se_inimage&styles= HTTP/1.1
     
    8585            EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
    8686        String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
    87         str += "&layers="+ layers; 
     87        str += "&layers="+ layers;
    8888        str += "&format=image/png";
    8989        //str += "&format=image/jpeg";
     
    100100
    101101    private URL getURLVector(EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
    102         return buildURLVector(CadastrePlugin.grabLayers, CadastrePlugin.grabStyles, 
    103                 CadastrePlugin.imageWidth, CadastrePlugin.imageHeight, 
     102        return buildURLVector(CadastrePlugin.grabLayers, CadastrePlugin.grabStyles,
     103                CadastrePlugin.imageWidth, CadastrePlugin.imageHeight,
    104104                lambertMin, lambertMax);
    105105    }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreInterface.java

    r22387 r23190  
    5353    final String cOptionListEnd = "</option>";
    5454    final String cBBoxCommunStart = "new GeoBox(";
    55     final String cBBoxCommunEnd = ")";   
     55    final String cBBoxCommunEnd = ")";
    5656
    5757    final String cInterfaceVector = "afficherCarteCommune.do";
     
    6262    final String cImageNameStart = ">Feuille ";
    6363    final String cTAImageNameStart = "Tableau d'assemblage <strong>";
    64    
     64
    6565    final static long cCookieExpiration = 30 * 60 * 1000; // 30 minutes expressed in milliseconds
    6666
     
    9797
    9898    /**
    99      * 
     99     *
    100100     * @return true if a cookie is delivered by WMS and false is WMS is not opening a client session
    101101     *         (too many clients or in maintenance)
     
    141141        cookie = null;
    142142    }
    143    
     143
    144144    public boolean isCookieExpired() {
    145145        long now = new Date().getTime();
     
    165165        urlConn.setRequestProperty("Cookie", this.cookie);
    166166    }
    167    
     167
    168168    private void getInterface(WMSLayer wmsLayer) throws IOException, DuplicateLayerException {
    169169        // first attempt : search for given name without codeCommune
     
    379379        return lines;
    380380    }
    381    
     381
    382382    private void parseFeuillesList(String input) {
    383383        listOfFeuilles.clear();
     
    402402        }
    403403    }
    404    
     404
    405405    private String selectMunicipalityDialog(WMSLayer wmsLayer) {
    406406        JPanel p = new JPanel(new GridBagLayout());
     
    455455     * and store it in given wmsLayer
    456456     * In case of raster image, we also check in the same http request if the image is already georeferenced
    457      * and store the result in the wmsLayer as well. 
     457     * and store the result in the wmsLayer as well.
    458458     * @param wmsLayer the WMSLayer where the commune data and images are stored
    459459     * @throws IOException
     
    502502        }
    503503    }
    504    
     504
    505505    private void parseGeoreferences(WMSLayer wmsLayer, String input) {
    506506        if (input.lastIndexOf(cBBoxCommunStart) != -1) {
     
    537537        }
    538538    }
    539    
     539
    540540    private double tryParseDouble(String str) {
    541541        try {
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastrePlugin.java

    r22850 r23190  
    9696 *                 - proper WMS layer cleanup at destruction (workaround for memory leak)
    9797 *                 - new cache format (v3) storing original image and cropped image bbox + angle
    98  *                 - new cache format (v4) storing original image size for later rotation 
     98 *                 - new cache format (v4) storing original image size for later rotation
    9999 *                 - cache files read compatible with previous formats
    100100 *                 - raster image rotation issues fixed, now using shift+ctrl key instead of ctrl
     
    104104 *                 - improved download cancellation
    105105 *                 - from Erik Amzallag:
    106  *                 -     possibility to modify the auto-sourcing text just before upload 
     106 *                 -     possibility to modify the auto-sourcing text just before upload
    107107 *                 - from Clément Ménier:
    108108 *                 -     new option allowing an auto-selection of the first cadastre layer for grab
     
    112112 *                 - download cancellation improved
    113113 *                 - last deployment for Java1.5 compatibility
    114  * 2.0 xx-xxx-xxxx - update projection for "La Reunion" departement to RGR92, UTM40S. 
     114 * 2.0 xx-xxx-xxxx - update projection for "La Reunion" departement to RGR92, UTM40S.
    115115 *                 - add 'departement' as option in the municipality selection
    116116 *                 - fixed bug in cache directory size control (and disabled by default)
     
    145145
    146146    public static int imageWidth, imageHeight;
    147    
     147
    148148    public static String grabLayers, grabStyles = null;
    149149
     
    156156     */
    157157    public CadastrePlugin(PluginInformation info) throws Exception {
    158         super(info);
     158        super(info);
    159159        System.out.println("Pluging cadastre-fr v"+VERSION+" started...");
    160160        if (Main.pref.get("cadastrewms.cacheDir").equals(""))
     
    218218
    219219    public static void refreshConfiguration() {
    220         source = checkSourceMillesime(); 
     220        source = checkSourceMillesime();
    221221        autoSourcing = Main.pref.getBoolean("cadastrewms.autosourcing", true);
    222222        alterColors = Main.pref.getBoolean("cadastrewms.alterColors");
     
    234234        } else if (currentResolution.equals("medium")){
    235235            imageWidth = 800; imageHeight = 600;
    236         } else { 
     236        } else {
    237237            imageWidth = 600; imageHeight = 400;
    238238        }
    239239        refreshLayersURL();
    240        
     240
    241241        // overwrite F11 shortcut used from the beginning by this plugin and recently used
    242242        // for full-screen switch in JOSM core
     
    268268        refreshMenu();
    269269    }
    270    
     270
    271271    private static void refreshLayersURL() {
    272272        grabLayers = "";
     
    346346        }
    347347    }
    348    
     348
    349349    public static boolean isCadastreProjection() {
    350350        return Main.proj.toString().equals(new Lambert().toString())
     
    360360
    361361    // See OptionPaneUtil
    362     // FIXME: this is a temporary solution. 
     362    // FIXME: this is a temporary solution.
    363363    public static void prepareDialog(JDialog dialog) {
    364364        if (Main.pref.getBoolean("window-handling.option-pane-always-on-top", true)) {
     
    373373        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    374374    }
    375    
     375
    376376    /**
    377377     * Adds the WMSLayer following this rule:<br/>
     
    393393            Main.main.addLayer(wmsLayer);
    394394    }
    395    
     395
    396396    private static String checkSourceMillesime() {
    397397        java.util.Calendar calendar = java.util.Calendar.getInstance();
     
    411411        return src;
    412412    }
    413    
     413
    414414}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastrePreferenceSetting.java

    r22387 r23190  
    4040
    4141    private JCheckBox disableImageCropping = new JCheckBox(tr("Disable image cropping during georeferencing."));
    42    
     42
    4343    private JCheckBox enableTableauAssemblage = new JCheckBox(tr("Use \"Tableau d''assemblage\""));
    44    
     44
    4545    private JCheckBox autoFirstLayer = new JCheckBox(tr("Select first WMS layer in list."));
    46    
     46
    4747    private JCheckBox dontUseRelation = new JCheckBox(tr("Don't use relation for addresses (but \"addr:street\" on elements)."));
    48    
     48
    4949    private JRadioButton grabMultiplier1 = new JRadioButton("", true);
    5050
     
    5454
    5555    private JRadioButton grabMultiplier4 = new JRadioButton("", true);
    56    
     56
    5757    private JRadioButton crosspiece1 = new JRadioButton("off");
    58    
     58
    5959    private JRadioButton crosspiece2 = new JRadioButton("25m");
    6060
     
    8787    JLabel jLabelCacheSize = new JLabel(tr("Max. cache size (in MB)"));
    8888    private JTextField cacheSize = new JTextField(20);
    89    
     89
    9090    static final String DEFAULT_RASTER_DIVIDER = "5";
    9191    private JTextField rasterDivider = new JTextField(10);
    9292
    9393    static final int DEFAULT_CROSSPIECES = 0;
    94    
     94
    9595    public void addGui(final PreferenceTabbedPane gui) {
    9696
     
    101101                + "before any upload of data created by this plugin.");
    102102        JPanel cadastrewmsMast = gui.createPreferenceTab("cadastrewms.gif", I18n.tr("French cadastre WMS"), description);
    103        
     103
    104104        JPanel cadastrewms = new JPanel(new GridBagLayout());
    105105        cadastrewms.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
     
    177177        cadastrewms.add(grabRes2, GBC.std().insets(5, 0, 5, 0));
    178178        cadastrewms.add(grabRes3, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 0, 5));
    179        
     179
    180180        // option to select image zooming interpolation method
    181181        JLabel jLabelImageZoomInterpolation = new JLabel(tr("Image filter interpolation:"));
     
    185185        imageInterpolationMethod.addItem(tr("Bicubic (slow)"));
    186186        String savedImageInterpolationMethod = Main.pref.get("cadastrewms.imageInterpolation", "standard");
    187         if (savedImageInterpolationMethod.equals("bilinear")) 
     187        if (savedImageInterpolationMethod.equals("bilinear"))
    188188            imageInterpolationMethod.setSelectedIndex(1);
    189         else if (savedImageInterpolationMethod.equals("bicubic")) 
     189        else if (savedImageInterpolationMethod.equals("bicubic"))
    190190            imageInterpolationMethod.setSelectedIndex(2);
    191191        else
     
    195195        // separator
    196196        cadastrewms.add(new JSeparator(SwingConstants.HORIZONTAL), GBC.eol().fill(GBC.HORIZONTAL));
    197        
     197
    198198        // the vectorized images multiplier
    199199        JLabel jLabelScale = new JLabel(tr("Vector images grab multiplier:"));
     
    275275        layerCommune.setToolTipText(tr("Municipality administrative borders."));
    276276        cadastrewms.add(layerCommune, GBC.eop().insets(5, 0, 5, 0));
    277        
     277
    278278        // separator
    279279        cadastrewms.add(new JSeparator(SwingConstants.HORIZONTAL), GBC.eol().fill(GBC.HORIZONTAL));
     
    335335        // separator
    336336        cadastrewms.add(new JSeparator(SwingConstants.HORIZONTAL), GBC.eol().fill(GBC.HORIZONTAL));
    337        
     337
    338338        // option to select the first WMS layer
    339339        autoFirstLayer.setSelected(Main.pref.getBoolean("cadastrewms.autoFirstLayer", false));
     
    348348        dontUseRelation.setToolTipText(tr("Enable this to use the tag \"add:street\" on nodes."));
    349349        cadastrewms.add(dontUseRelation, GBC.eop().insets(0, 0, 0, 0));
    350        
     350
    351351        // end of dialog, scroll bar
    352352        cadastrewms.add(Box.createVerticalGlue(), GBC.eol().fill(GBC.VERTICAL));
     
    374374        else if (imageInterpolationMethod.getSelectedIndex() == 1)
    375375            Main.pref.put("cadastrewms.imageInterpolation", "bilinear");
    376         else 
     376        else
    377377            Main.pref.put("cadastrewms.imageInterpolation", "standard");
    378378        if (grabMultiplier1.isSelected())
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CheckSourceUploadHook.java

    r19149 r23190  
    3838     * Add the tag "source" if it doesn't exist for all new Nodes and Ways before uploading
    3939     */
    40     public boolean checkUpload(APIDataSet apiDataSet) 
     40    public boolean checkUpload(APIDataSet apiDataSet)
    4141    {
    4242        if (CadastrePlugin.autoSourcing && CadastrePlugin.pluginUsed && !apiDataSet.getPrimitivesToAdd().isEmpty()) {
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java

    r20412 r23190  
    5454    @Override
    5555    public void realRun() throws IOException, OsmTransferException {
    56         progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
     56        progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
    5757        errorMessage = null;
    5858        try {
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGTask.java

    r20412 r23190  
    5757    @Override
    5858    public void realRun() throws IOException, OsmTransferException {
    59         progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
     59        progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
    6060        errorMessage = null;
    6161        try {
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadWMSVectorImage.java

    r20412 r23190  
    1616
    1717    private WMSLayer wmsLayer;
    18     private Bounds bounds;   
    19     private CadastreGrabber grabber = CadastrePlugin.cadastreGrabber;   
     18    private Bounds bounds;
     19    private CadastreGrabber grabber = CadastrePlugin.cadastreGrabber;
    2020    private static String errorMessage;
    2121
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/EastNorthBound.java

    r18544 r23190  
    3131        return enb;
    3232    }
    33    
     33
    3434    public Bounds toBounds() {
    3535        return new Bounds(Main.proj.eastNorth2latlon(min), Main.proj.eastNorth2latlon(max));
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/GeorefImage.java

    r22230 r23190  
    3030    public EastNorth max;
    3131    // bbox of the georeferenced original image (raster only) (inclined if rotated and before cropping)
    32     // P[0] is bottom,left then next are clockwise. 
     32    // P[0] is bottom,left then next are clockwise.
    3333    public EastNorth[] orgRaster = new EastNorth[4];
    34     // bbox of the georeferenced original image (raster only) after cropping 
     34    // bbox of the georeferenced original image (raster only) after cropping
    3535    public EastNorth[] orgCroppedRaster = new EastNorth[4];
    3636    // angle with georeferenced original image after rotation (raster images only)(in radian)
     
    4646    public GeorefImage(BufferedImage img, EastNorth min, EastNorth max) {
    4747        image = img;
    48        
     48
    4949        this.min = min;
    5050        this.max = max;
     
    7070
    7171    /**
    72      * Recalculate the new bounding box of the image based on the four points provided as parameters. 
    73      * The new bbox defined in [min.max] will retain the extreme values of both boxes. 
     72     * Recalculate the new bounding box of the image based on the four points provided as parameters.
     73     * The new bbox defined in [min.max] will retain the extreme values of both boxes.
    7474     * @param p1 one of the bounding box corner
    7575     * @param p2 one of the bounding box corner
     
    128128                    g.drawLine(croppedPoint[i].x, croppedPoint[i].y, croppedPoint[i+1].x, croppedPoint[i+1].y);
    129129                }
    130                 /* 
     130                /*
    131131                //Uncomment this section to display the original image size (before cropping)
    132132                Point[] orgPoint = new Point[5];
     
    212212            imageOriginalHeight = in.readInt();
    213213            imageOriginalWidth =  in.readInt();
    214         }       
     214        }
    215215        image = (BufferedImage) ImageIO.read(ImageIO.createImageInputStream(in));
    216216        updatePixelPer();
     
    276276        }
    277277    }
    278    
     278
    279279    /**
    280280     * Change this image scale by moving the min,max coordinates around an anchor
    281      * @param anchor 
     281     * @param anchor
    282282     * @param proportion
    283283     */
     
    324324        angle+=delta_ang;
    325325    }
    326    
     326
    327327    /**
    328328     * Crop the image based on new bbox coordinates adj1 and adj2 (for raster images only).
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/ImageModifier.java

    r20931 r23190  
    1919
    2020    protected int parcelColor = Color.RED.getRGB();
    21    
     21
    2222    public BufferedImage bufferedImage;
    2323
     
    3131            new byte[] { (byte) 0, (byte) 0xFF }
    3232        );
    33        
     33
    3434        BufferedImage dest = new BufferedImage(
    3535            src.getWidth(), src.getHeight(),
     
    3737            icm
    3838            );
    39        
     39
    4040        ColorConvertOp cco = new ColorConvertOp(
    4141            src.getColorModel().getColorSpace(),
     
    4343            null
    4444            );
    45        
     45
    4646        cco.filter(src, dest);
    47        
     47
    4848        return dest;
    4949      }
     
    7272        return convert4(src, cmap);
    7373      }
    74        
     74
    7575      /**
    7676       * Converts the source image to 4-bit colour
     
    9696            );
    9797        cco.filter(src, dest);
    98        
     98
    9999        return dest;
    100100      }
    101      
     101
    102102    protected BufferedImage convert8(BufferedImage src) {
    103103        BufferedImage dest = new BufferedImage(
     
    115115
    116116    public boolean isBuildingColor(int rgb, boolean ignoreParcelColor) {
    117         for (int i = 0; i < cBuilingFootColors.length; i++) 
     117        for (int i = 0; i < cBuilingFootColors.length; i++)
    118118            if (rgb == cBuilingFootColors[i])
    119119                    return true;
     
    124124
    125125    public boolean isRoofColor(int rgb, boolean ignoreParcelColor) {
    126         for (int i = 0; i < cRoofColors.length; i++) 
     126        for (int i = 0; i < cRoofColors.length; i++)
    127127            if (rgb == cRoofColors[i])
    128128                    return true;
     
    152152        return ret;
    153153    }
    154    
     154
    155155    /**
    156156     * Checks if the rgb value is the black background color
    157      * @param 
     157     * @param
    158158     * @return
    159159     */
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/MenuActionGrabPlanImage.java

    r21493 r23190  
    180180     */
    181181    private boolean startCropping() {
    182             mode = cGetCorners;
    183             countMouseClicked = 0;
    184                 Object[] options = { "OK", "Cancel" };
    185                 int ret = JOptionPane.showOptionDialog( null,
    186                                 tr("Click first corner for image cropping\n(two points required)"),
    187                                 tr("Image cropping"),
    188                         JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
    189                         null, options, options[0]);
    190             if (ret == JOptionPane.OK_OPTION) {
    191                 mouseClickedTime = System.currentTimeMillis();
    192             } else
    193                 if (canceledOrRestartCurrAction("image cropping"))
    194                         return startCropping();
    195             return true;
     182        mode = cGetCorners;
     183        countMouseClicked = 0;
     184        Object[] options = { "OK", "Cancel" };
     185        int ret = JOptionPane.showOptionDialog( null,
     186                tr("Click first corner for image cropping\n(two points required)"),
     187                tr("Image cropping"),
     188                JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
     189                null, options, options[0]);
     190        if (ret == JOptionPane.OK_OPTION) {
     191            mouseClickedTime = System.currentTimeMillis();
     192        } else
     193            if (canceledOrRestartCurrAction("image cropping"))
     194                return startCropping();
     195        return true;
    196196    }
    197197
     
    201201     */
    202202    private boolean continueCropping() {
    203                 Object[] options = { "OK", "Cancel" };
    204                 int ret = JOptionPane.showOptionDialog( null,
    205                                 tr("Click second corner for image cropping"),
    206                                 tr("Image cropping"),
    207                         JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
    208                         null, options, options[0]);
    209             if (ret != JOptionPane.OK_OPTION) {
    210                 if (canceledOrRestartCurrAction("image cropping"))
    211                         return startCropping();
    212             }
    213             return true;
     203        Object[] options = { "OK", "Cancel" };
     204        int ret = JOptionPane.showOptionDialog( null,
     205                tr("Click second corner for image cropping"),
     206                tr("Image cropping"),
     207                JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
     208                null, options, options[0]);
     209        if (ret != JOptionPane.OK_OPTION) {
     210            if (canceledOrRestartCurrAction("image cropping"))
     211                return startCropping();
     212        }
     213        return true;
    214214    }
    215215
     
    219219     */
    220220    private boolean startGeoreferencing() {
    221             countMouseClicked = 0;
    222             mode = cGetLambertCrosspieces;
    223                 Object[] options = { "OK", "Cancel" };
    224                 int ret = JOptionPane.showOptionDialog( null,
    225                                 tr("Click first Lambert crosspiece for georeferencing\n(two points required)"),
    226                                 tr("Image georeferencing"),
    227                         JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
    228                         null, options, options[0]);
    229             if (ret == JOptionPane.OK_OPTION) {
    230                 mouseClickedTime = System.currentTimeMillis();
    231             } else
    232                 if (canceledOrRestartCurrAction("georeferencing"))
    233                         return startGeoreferencing();
    234             return true;
     221        countMouseClicked = 0;
     222        mode = cGetLambertCrosspieces;
     223        Object[] options = { "OK", "Cancel" };
     224        int ret = JOptionPane.showOptionDialog( null,
     225                tr("Click first Lambert crosspiece for georeferencing\n(two points required)"),
     226                tr("Image georeferencing"),
     227                JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
     228                null, options, options[0]);
     229        if (ret == JOptionPane.OK_OPTION) {
     230            mouseClickedTime = System.currentTimeMillis();
     231        } else
     232            if (canceledOrRestartCurrAction("georeferencing"))
     233                return startGeoreferencing();
     234        return true;
    235235    }
    236236
     
    240240     */
    241241    private boolean continueGeoreferencing() {
    242                 Object[] options = { "OK", "Cancel" };
    243                 int ret = JOptionPane.showOptionDialog( null,
    244                                 tr("Click second Lambert crosspiece for georeferencing"),
    245                                 tr("Image georeferencing"),
    246                         JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
    247                         null, options, options[0]);
    248             if (ret != JOptionPane.OK_OPTION) {
    249                 if (canceledOrRestartCurrAction("georeferencing"))
    250                         return startGeoreferencing();
    251             }
    252             return true;
     242        Object[] options = { "OK", "Cancel" };
     243        int ret = JOptionPane.showOptionDialog( null,
     244                tr("Click second Lambert crosspiece for georeferencing"),
     245                tr("Image georeferencing"),
     246                JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
     247                null, options, options[0]);
     248        if (ret != JOptionPane.OK_OPTION) {
     249            if (canceledOrRestartCurrAction("georeferencing"))
     250                return startGeoreferencing();
     251        }
     252        return true;
    253253    }
    254254   
     
    271271     */
    272272    private boolean canceledOrRestartCurrAction(String action) {
    273         Object[] options = { "Cancel", "Retry" };
    274         int selectedValue = JOptionPane.showOptionDialog( null,
    275                         tr("Do you want to cancel completely\n"+
    276                                         "or just retry "+action+" ?"), "",
    277                         JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
    278                         null, options, options[0]);
     273        Object[] options = { "Cancel", "Retry" };
     274        int selectedValue = JOptionPane.showOptionDialog( null,
     275                tr("Do you want to cancel completely\n"+
     276                        "or just retry "+action+" ?"), "",
     277                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
     278                null, options, options[0]);
    279279        countMouseClicked = 0;
    280280        if (selectedValue == 0) { // "Cancel"
    281                 // remove layer
    282                 Main.map.mapView.removeLayer(wmsLayer);
     281            // remove layer
     282            Main.map.mapView.removeLayer(wmsLayer);
    283283            wmsLayer = null;
    284284            Main.map.mapView.removeMouseListener(this);
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/MenuActionLoadFromCache.java

    r20824 r23190  
    7777                    if (wmsLayer.getCacheControl().loadCache(file, layoutZone)) {
    7878                        CadastrePlugin.addWMSLayer(wmsLayer);
    79                     }                   
     79                    }
    8080                }
    8181            }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/MenuActionNewLocation.java

    r21202 r23190  
    2525
    2626    private static final long serialVersionUID = 1L;
    27    
     27
    2828    private static final String departements[] = {
    2929        "", tr("(optional)"),
    3030        "001", "01 - Ain",                 "002", "02 - Aisne",              "003", "03 - Allier",                "004", "04 - Alpes de Haute-Provence", "005", "05 - Hautes-Alpes",
    3131        "006", "06 - Alpes-Maritimes",     "007", "07 - Ard\u00eache",       "008", "08 - Ardennes",              "009", "09 - Ari\u00e8ge",             "010", "10 - Aube",
    32         "011", "11 - Aude",                "012", "12 - Aveyron",            "013", "13 - Bouches-du-Rh\u00f4ne", "014", "14 - Calvados",                "015", "15 - Cantal", 
    33         "016", "16 - Charente",            "017", "17 - Charente-Maritime",  "018", "18 - Cher",                  "019", "19 - Corr\u00e8ze", 
    34         "02A", "2A - Corse-du-Sud",        "02B", "2B - Haute-Corse", 
    35         "021", "21 - C\u00f4te-d'Or",      "022", "22 - C\u00f4tes d'Armor", "023", "23 - Creuse",                "024", "24 - Dordogne",                "025", "25 - Doubs", 
     32        "011", "11 - Aude",                "012", "12 - Aveyron",            "013", "13 - Bouches-du-Rh\u00f4ne", "014", "14 - Calvados",                "015", "15 - Cantal",
     33        "016", "16 - Charente",            "017", "17 - Charente-Maritime",  "018", "18 - Cher",                  "019", "19 - Corr\u00e8ze",
     34        "02A", "2A - Corse-du-Sud",        "02B", "2B - Haute-Corse",
     35        "021", "21 - C\u00f4te-d'Or",      "022", "22 - C\u00f4tes d'Armor", "023", "23 - Creuse",                "024", "24 - Dordogne",                "025", "25 - Doubs",
    3636        "026", "26 - Dr\u00f4me",          "027", "27 - Eure",               "028", "28 - Eure-et-Loir",          "029", "29 - Finist\u00e8re",          "030", "30 - Gard",
    37         "031", "31 - Haute-Garonne",       "032", "32 - Gers",               "033", "33 - Gironde",               "034", "34 - H\u00e9rault",            "035", "35 - Ille-et-Vilaine", 
     37        "031", "31 - Haute-Garonne",       "032", "32 - Gers",               "033", "33 - Gironde",               "034", "34 - H\u00e9rault",            "035", "35 - Ille-et-Vilaine",
    3838        "036", "36 - Indre",               "037", "37 - Indre-et-Loire",     "038", "38 - Is\u00e8re",            "039", "39 - Jura",                    "040", "40 - Landes",
    39         "041", "41 - Loir-et-Cher",        "042", "42 - Loire",              "043", "43 - Haute-Loire",           "044", "44 - Loire-Atlantique",        "045", "45 - Loiret", 
     39        "041", "41 - Loir-et-Cher",        "042", "42 - Loire",              "043", "43 - Haute-Loire",           "044", "44 - Loire-Atlantique",        "045", "45 - Loiret",
    4040        "046", "46 - Lot",                 "047", "47 - Lot-et-Garonne",     "048", "48 - Loz\u00e8re",           "049", "49 - Maine-et-Loire",          "050", "50 - Manche",
    41         "051", "51 - Marne",               "052", "52 - Haute-Marne",        "053", "53 - Mayenne",               "054", "54 - Meurthe-et-Moselle",      "055", "55 - Meuse", 
     41        "051", "51 - Marne",               "052", "52 - Haute-Marne",        "053", "53 - Mayenne",               "054", "54 - Meurthe-et-Moselle",      "055", "55 - Meuse",
    4242        "056", "56 - Morbihan",            "057", "57 - Moselle",            "058", "58 - Ni\u00e8vre",           "059", "59 - Nord",                    "060", "60 - Oise",
    43         "061", "61 - Orne",                "062", "62 - Pas-de-Calais",      "063", "63 - Puy-de-D\u00f4me",      "064", "64 - Pyr\u00e9n\u00e9es-Atlantiques", "065", "65 - Hautes-Pyr\u00e9n\u00e9es", 
     43        "061", "61 - Orne",                "062", "62 - Pas-de-Calais",      "063", "63 - Puy-de-D\u00f4me",      "064", "64 - Pyr\u00e9n\u00e9es-Atlantiques", "065", "65 - Hautes-Pyr\u00e9n\u00e9es",
    4444        "066", "66 - Pyr\u00e9n\u00e9es-Orientales", "067", "67 - Bas-Rhin", "068", "68 - Haut-Rhin",             "069", "69 - Rh\u00f4ne",              "070", "70 - Haute-Sa\u00f4ne",
    45         "071", "71 - Sa\u00f4ne-et-Loire", "072", "72 - Sarthe",             "073", "73 - Savoie",                "074", "74 - Haute-Savoie",            "075", "75 - Paris", 
     45        "071", "71 - Sa\u00f4ne-et-Loire", "072", "72 - Sarthe",             "073", "73 - Savoie",                "074", "74 - Haute-Savoie",            "075", "75 - Paris",
    4646        "076", "76 - Seine-Maritime",      "077", "77 - Seine-et-Marne",     "078", "78 - Yvelines",              "079", "79 - Deux-S\u00e8vres",        "080", "80 - Somme",
    47         "081", "81 - Tarn",                "082", "82 - Tarn-et-Garonne",    "083", "83 - Var",                   "084", "84 - Vaucluse",                "085", "85 - Vend\u00e9e", 
     47        "081", "81 - Tarn",                "082", "82 - Tarn-et-Garonne",    "083", "83 - Var",                   "084", "84 - Vaucluse",                "085", "85 - Vend\u00e9e",
    4848        "086", "86 - Vienne",              "087", "87 - Haute-Vienne",       "088", "88 - Vosges",                "089", "89 - Yonne",                   "090", "90 - Territoire de Belfort",
    49         "091", "91 - Essonne",             "092", "92 - Hauts-de-Seine",     "093", "93 - Seine-Saint-Denis",     "094", "94 - Val-de-Marne",            "095", "95 - Val-d'Oise", 
     49        "091", "91 - Essonne",             "092", "92 - Hauts-de-Seine",     "093", "93 - Seine-Saint-Denis",     "094", "94 - Val-de-Marne",            "095", "95 - Val-d'Oise",
    5050        "971", "971 - Guadeloupe",         "972", "972 - Martinique",        "973", "973 - Guyane",               "974", "974 - R\u00e9union"
    5151    };
     
    8181            for (int i=0; i < departements.length; i=i+2)
    8282                if (departements[i].equals(Main.pref.get("cadastrewms.codeDepartement")))
    83                     inputDepartement.setSelectedIndex(i/2);       
     83                    inputDepartement.setSelectedIndex(i/2);
    8484        }
    8585        p.add(labelSectionNewLocation, GBC.eol());
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java

    r22547 r23190  
    104104
    105105    @Override
    106         public void destroy() {
     106    public void destroy() {
    107107        // if the layer is currently saving the images in the cache, wait until it's finished
    108108        if (cacheControl != null) {
     
    305305        saveAsPng.setEnabled(isRaster);
    306306        return new Action[] {
    307                         LayerListDialog.getInstance().createShowHideLayerAction(),
     307                LayerListDialog.getInstance().createShowHideLayerAction(),
    308308                LayerListDialog.getInstance().createDeleteLayerAction(),
    309309                new MenuActionLoadFromCache(),
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/CzechAddressPlugin.java

    r22915 r23190  
    8686
    8787    public CzechAddressPlugin(PluginInformation info) {
    88         super(info);
     88        super(info);
    8989
    9090        /*boolean x;
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/DatabaseLoadException.java

    r15166 r23190  
    66/**
    77 * Exception occuring during parsing the database.
    8  * 
     8 *
    99 * <p>This exception is used during <i>download</i>, <i>extraction</i> or
    1010 * <i>parsing</i> of the database. It can set a message to be displayed
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/NotNullList.java

    r15585 r23190  
    66/**
    77 * ArrayList, which refuses to add {@code null}.
    8  * 
     8 *
    99 * @author Radomír Černoch, radomir.cernoch@gmail.com
    1010 */
     
    3939        if (c == null)
    4040            return false;
    41        
     41
    4242        if (c instanceof NotNullList)
    4343            return super.addAll(c);
     
    4646        return true;
    4747    }
    48    
     48
    4949}
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/PrimUtils.java

    r16743 r23190  
    66/**
    77 * Utilities for handling {@link OsmPrimitive}s.
    8  * 
     8 *
    99 * @author Radomír Černoch, radomir.cernoch@gmail.com
    1010 */
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/StatusListener.java

    r15585 r23190  
    2121 *
    2222 * @see CzechAddressPlugin
    23  * 
     23 *
    2424 * @author Radomír Černoch, radomir.cernoch@gmail.com
    2525 */
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/StringUtils.java

    r18894 r23190  
    107107                return false;
    108108        }
    109        
     109
    110110        return true;
    111111    }
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/actions/ManagerAction.java

    r15585 r23190  
    1111 *
    1212 * @author Radomír Černoch, radomir.cernoch@gmail.com
    13  * 
     13 *
    1414 * @see ManagerDialog
    1515 */
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/actions/SplitAreaByEmptyWayAction.java

    r21860 r23190  
    6363                if (!(prim2 instanceof Way)) continue;
    6464                if (prim2.equals(prim))      continue;
    65                 Way border = (Way) prim2;
     65                Way border = (Way) prim2;
    6666                if (border.getNodes().size() == 0)   continue;
    6767                if (border.keySet().size() > 0) continue;
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/AddressElement.java

    r19943 r23190  
    1414 *
    1515 * <p>Every element must have a <i>name</i> and may have a <i>parent</i>.</p>
    16  * 
     16 *
    1717 * @author Radomír Černoch radomir.cernoch@gmail.com
    1818 */
     
    9999            Node node = (Node) prim;
    100100            result += " " + StringUtils.latLonToString(node.getCoor());
    101            
     101
    102102        } else if (prim instanceof Way) {
    103103            Way way = (Way) prim;
     
    135135    /**
    136136     * Compares 2 elements.
    137      * 
     137     *
    138138     * <p>Basic criterion to comparing elements is their <i>name</i> and the
    139139     * </i>parent</i>. Notice that this behaviour might be changed
     
    217217    }
    218218
    219    
     219
    220220    protected int[] getFieldMatchList(OsmPrimitive primitive) {
    221         int[] result = {0};       
     221        int[] result = {0};
    222222        return result;
    223223    }
     
    242242     */
    243243    public int getQ(OsmPrimitive primitive) {
    244        
     244
    245245        // Firstly get integers representing a match of every matchable field.
    246246        int[] fieldMatches = getFieldMatchList(primitive);
    247247        assert fieldMatches.length > 0;
    248        
     248
    249249        // Now find the max and min of this array.
    250250        int minVal = fieldMatches[0];
     
    260260        assert Math.abs(minVal) <= 1;
    261261        assert Math.abs(maxVal) <= 1;
    262        
     262
    263263        // If the best among all fields is 'neutral' match, the given primitive
    264264        // has nothing to do with our field.
    265265        if (maxVal <= 0)
    266266            return Reasoner.MATCH_NOMATCH;
    267        
     267
    268268        // If all fields are 1    --> ROCKSOLID MATCH
    269269        // If some are 1, none -1 --> PARTIAL MATCH
     
    274274            case +1 : return Reasoner.MATCH_ROCKSOLID;
    275275        }
    276        
     276
    277277        return 0; // <-- just to make compilers happy. We cannot get here.
    278278    }
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/Database.java

    r15585 r23190  
    99 * <p>Contains the tree of all regions, municipalities, suburbs, streets
    1010 * and houses in the Czech republic.</p>
    11  * 
     11 *
    1212 * @see AddressElement
    1313 * @see DatabaseParser
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/ElementWithHouses.java

    r15763 r23190  
    4747    /**
    4848     * Returns all houses directly contained in this element.
    49      * 
     49     *
    5050     * NOTICE: If a subclass element contains other data structured capable
    5151     * of storing houses, they are not included in the returned set.
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/ElementWithStreets.java

    r15585 r23190  
    2424    public void addStreet(Street streetToAdd) {
    2525        //if (streetToAdd.getParent() instanceof ElementWithStreets)
    26        
     26
    2727        streetToAdd.setParent(this);
    2828        streets.add(streetToAdd);
     
    7979        // We make an conservative estimate...
    8080        List<House> result = new ArrayList<House>(20 * streets.size());
    81        
     81
    8282        result.addAll(this.houses);
    83        
     83
    8484        for (Street street : streets)
    8585            result.addAll(street.getHouses());
    86        
     86
    8787        return result;
    8888    }
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/House.java

    r16743 r23190  
    2020 * {@link ElementWithHouses}. The {@code setParent()} method should
    2121 * be called immediatelly after the constructor.</p>
    22  * 
     22 *
    2323 * @author Radomír Černoch, radomir.cernoch@gmail.com
    2424 */
     
    4444
    4545        assert (co != null) || (cp != null);
    46        
     46
    4747        //... but the the name is overwritten.
    4848        this.name = generateName(this.cp, this.co);
    4949    }
    50    
     50
    5151    /**
    5252     * Returns the number unique in a suburb (číslo popisné)
     
    128128        super.setParent(parent);
    129129    }
    130    
     130
    131131    /**
    132132     * Returns the parent of this house with type-checking.
     
    159159        result[0] = matchField(this.cp, prim.get(PrimUtils.KEY_ADDR_CP));
    160160        result[2] = matchField(name,    prim.get(PrimUtils.KEY_ADDR_HOUSE_N));
    161        
     161
    162162        // Second field is the Housenumber
    163163        if (parent instanceof Street)
     
    178178    }
    179179
    180    
     180
    181181
    182182    /**
     
    188188    @Override
    189189    public List<Proposal> getDiff(OsmPrimitive prim) {
    190        
     190
    191191        List<Proposal> props = new NotNullList<Proposal>();
    192192        ParentResolver resolver = new ParentResolver(this);
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/Region.java

    r15585 r23190  
    1010 */
    1111public class Region extends ElementWithStreets {
    12    
     12
    1313    private ArrayList<ViToCi> vitocis
    1414            = new ArrayList<ViToCi>();
    15    
     15
    1616    /**
    1717     * Adds a single municipality into this element.
     
    2121        vitocis.add(municipality);
    2222    }
    23    
     23
    2424    /**
    2525     * Replaces the list of municipalities of this element.
     
    3030            obec.setParent(this);
    3131    }
    32    
     32
    3333    /**
    3434     * Returns the list of all municipalities in this region.
     
    5353    String nuts3name = null;
    5454    String nuts4name = null;
    55    
     55
    5656    /**
    5757     * Default constructor setting the name of this region.
     
    6161        super(name);
    6262    }
    63    
     63
    6464    /**
    6565     * Constructor which sets the region's name together with higher
     
    7171        if (nuts4name != null) this.nuts4name = nuts4name;
    7272    }
    73    
     73
    7474    public String getNuts3Name() {
    7575        return nuts3name;
    7676    }
    77    
     77
    7878    public String getNuts4Name() {
    7979        return nuts4name;
    8080    }
    81    
     81
    8282    /**
    8383     * Returns the name of this region. If the NUTS3 name was entered,
     
    8686    @Override
    8787    public String toString() {
    88        
     88
    8989        String thisString = name;
    90        
     90
    9191        if (nuts3name != null)
    9292            thisString += " (kraj " + nuts3name + ")";
    93        
     93
    9494        return thisString;
    9595    }
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/Street.java

    r15582 r23190  
    2525        super.setParent(parent);
    2626    }
    27    
     27
    2828    @Override
    2929    public ElementWithStreets getParent() {
     
    3636        int[] result = {0};
    3737        if (!isMatchable(primitive)) return result;
    38        
     38
    3939        result[0] = matchFieldAbbrev(name, primitive.get("name"));
    4040        return result;
     
    4444    public List<Proposal> getDiff(OsmPrimitive prim) {
    4545        List<Proposal> props = new NotNullList<Proposal>();
    46        
     46
    4747        props.add(getStringFieldDiff(PrimUtils.KEY_NAME, prim.get(PrimUtils.KEY_NAME), getName()));
    4848        return props;
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/Suburb.java

    r15582 r23190  
    66/**
    77 * Suburb is a part of a {@link Municipality}.
    8  * 
     8 *
    99 * @author Radomír Černoch radomir.cernoch@gmail.com
    1010 */
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/addressdatabase/ViToCi.java

    r15582 r23190  
    66/**
    77 * ViToCi is either a village, town or a city.
    8  * 
     8 *
    99 * @author Radomír Černoch radomir.cernoch@gmail.com
    1010 */
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/gui/ConflictResolver.java

    r18408 r23190  
    234234                if (r.translate(prim) != null)
    235235                    r.unOverwrite(prim, r.translate(prim));
    236                
     236
    237237                ComboBoxModel model = candField.getModel();
    238238                for (int i = 0; i < model.getSize(); i++) {
     
    242242                        r.unOverwrite(r.translate(elem), elem);
    243243                }
    244                
     244
    245245                r.doOverwrite(prim, (AddressElement) model.getSelectedItem());
    246246            }
     
    358358                                        +AddressElement.getName(prim) + "“");
    359359                primitives.add(-index-1, prim);
    360                
     360
    361361                ListDataEvent evt = new ListDataEvent(this,
    362362                        ListDataEvent.INTERVAL_ADDED,
     
    364364                for (ListDataListener listener : listeners)
    365365                    listener.intervalAdded(evt);
    366                
     366
    367367                if (mainField.getSelectedItem() == null)
    368368                    mainField.setSelectedIndex(-index-1);
     
    378378                                        + elem.getName() + "“");
    379379                elements.remove(index);
    380                
     380
    381381                if (selected == elem)
    382382                    setSelectedItem(null);
     
    401401                if (selected == prim)
    402402                    setSelectedItem(null);
    403                
     403
    404404                ListDataEvent evt = new ListDataEvent(this,
    405405                        ListDataEvent.INTERVAL_REMOVED,
     
    419419            elements.clear();
    420420            primitives.clear();
    421            
     421
    422422            for (ListDataListener listener : listeners)
    423423                listener.contentsChanged(evt);
    424424        }
    425        
     425
    426426        public void setSelectedItem(Object anItem) {
    427427
     
    447447            if (index< elements.size())
    448448                return elements.get(index);
    449            
     449
    450450            index -= elements.size();
    451451
    452452            if (index< primitives.size())
    453453                return primitives.get(index);
    454            
     454
    455455            return null;
    456456        }
     
    466466
    467467    private void updateCandidatesModel(Object selected) {
    468        
     468
    469469        if (selected instanceof AddressElement) {
    470470            AddressElement selElem = (AddressElement) selected;
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/gui/FactoryDialog.java

    r18896 r23190  
    5252    private HouseListModel  houseModel  = new HouseListModel();
    5353    private StreetListModel streetModel = new StreetListModel();
    54    
     54
    5555    private FactoryDialog() {
    5656
     
    8989            return;
    9090        }
    91        
     91
    9292        if (message == MESSAGE_LOCATION_CHANGED) {
    9393            DataSet.selListeners.add(this);
     
    9999            keepOddityCheckBox.setEnabled(true);
    100100            return;
    101         }       
     101        }
    102102    }
    103103
     
    174174            do {
    175175                selectNextUnmatchedHouse();
    176                    
     176
    177177                String newStr = StringUtils.extractNumber(getSelectedHouse().getCO());
    178178
     
    360360                setFont(getFont().deriveFont(Font.PLAIN));
    361361                setText(((Street) value).getName());
    362                
     362
    363363            } else if (value instanceof ElementWithHouses) {
    364364                setFont(getFont().deriveFont(Font.BOLD));
    365365                setText("[" + ((ElementWithHouses) value).getName() + "]");
    366366            }
    367            
     367
    368368            return c;
    369369        }
     
    435435            House house = (House) elem;
    436436            int index = Collections.binarySearch(houses, house);
    437            
     437
    438438            if (Reasoner.getInstance().translate(house) != null) {
    439439                if (index >= 0) houses.remove(index);
     
    441441                if (index < 0)  houses.add(-index-1, house);
    442442            }
    443            
     443
    444444            houseModel.notifyAllListeners();
    445445        }
     
    472472            this.selected = parent;
    473473            this.parent   = parent;
    474            
     474
    475475            metaElem.set(0, parent);
    476476            metaElem.get(1).setHouses(parent.getAllHouses());
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/gui/GroupManipulatorDialog.java

    r22015 r23190  
    124124
    125125        proposalTree.addKeyListener(new java.awt.event.KeyAdapter() {
    126                 @Override
     126            @Override
    127127            public void keyReleased(java.awt.event.KeyEvent evt) {
    128128                proposalTreeKeyReleased(evt);
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/gui/LocationSelector.java

    r22915 r23190  
    7979     *
    8080     */
    81         private void initLocationHints() {
     81    private void initLocationHints() {
    8282        boolean assertions = false;
    8383        assert  assertions = true;
     
    177177        int curHlIndex = 0;
    178178
    179         for (int i = 0; i < list.getSize(); i++) 
     179        for (int i = 0; i < list.getSize(); i++)
    180180            for (int j = 0; j < hlList.size(); j++) {
    181181                Object t = list.getElementAt(i);
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/gui/PointManipulatorDialog.java

    r22015 r23190  
    207207
    208208        alternateNumberEdit.addKeyListener(new java.awt.event.KeyAdapter() {
    209                 @Override
     209            @Override
    210210            public void keyReleased(java.awt.event.KeyEvent evt) {
    211211                PointManipulatorDialog.this.keyReleased(evt);
     
    228228        proposalList.addKeyListener(new java.awt.event.KeyAdapter() {
    229229            @Override
    230                         public void keyReleased(java.awt.event.KeyEvent evt) {
     230            public void keyReleased(java.awt.event.KeyEvent evt) {
    231231                proposalListKeyReleased(evt);
    232232            }
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/gui/databaseeditors/SuburbEditor.java

    r18408 r23190  
    2828        this.parent = suburb.getParent();
    2929        nameField.setText(suburb.getName());
    30        
     30
    3131        if (parent != null)
    3232            parentField.setText(parent.getName());
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/gui/utils/UniversalListRenderer.java

    r15585 r23190  
    1515    public Component getListCellRendererComponent(JList list, Object value,
    1616                          int index, boolean isSelected, boolean cellHasFocus) {
    17        
     17
    1818        Component c = super.getListCellRendererComponent(list, value, index,
    1919                                                      isSelected, cellHasFocus);
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/gui/utils/UniversalRenderer.java

    r15585 r23190  
    3434
    3535    public static ImageIcon getIcon(Object value) {
    36        
     36
    3737             if (value instanceof AddKeyValueProposal)    return iconAdd;
    3838        else if (value instanceof KeyValueChangeProposal) return iconEdit;
     
    6969        if (value instanceof AddressElement)
    7070            return ((AddressElement) value).getName();
    71                
     71
    7272        if (value instanceof OsmPrimitive)
    7373            return AddressElement.getName(value);
     
    7575        if (value == null)
    7676            return "";
    77        
     77
    7878        return value.toString();
    7979    }
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/intelligence/Reasoner.java

    r18896 r23190  
    9999     * modify the data in the reasoner.
    100100     * The only exception is {@code reset()}.</p>
    101      * 
     101     *
    102102     * <p>When there's an open transaction, the result of most output methods
    103103     * undefined. Exceptions to this rules are indicated.</p>
     
    387387        if (getStrictlyBest(elem) == prim)
    388388            return elem;
    389        
     389
    390390        return null;
    391391    }
     
    417417        if (getStrictlyBest(prim) == elem)
    418418            return prim;
    419        
     419
    420420        return null;
    421421    }
     
    515515                best = cand;
    516516        }
    517        
     517
    518518        for (OsmPrimitive prim : elemMatchIndex.get(elem).keySet()) {
    519519            int cand = elemMatchIndex.get(elem).get(prim);
     
    542542     */
    543543    public AddressElement getStrictlyBest(OsmPrimitive prim) {
    544        
     544
    545545        AddressElement result = null;
    546546        try {
     
    563563                }
    564564            }
    565            
     565
    566566        } catch (NullPointerException except) {
    567567            System.err.println("Strange exception occured." +
     
    601601                return null;
    602602            }
    603            
     603
    604604            int bestQ = MATCH_NOMATCH;
    605605            for (OsmPrimitive prim : matches.keySet()) {
     
    683683            ProposalContainer container = new ProposalContainer(prim);
    684684            container.addProposals(elem.getDiff(prim));
    685            
     685
    686686            if (container.getProposals().size() > 0)
    687687                database.addContainer(container);
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/parser/DatabaseParser.java

    r19964 r23190  
    1414/**
    1515 * General superclass for any parser capable of filling the database.
    16  * 
     16 *
    1717 * @see Database
    1818 *
     
    4343    /**
    4444     * The ultimate method, which starts filling the database.
    45      * 
     45     *
    4646     * @throws DatabaseLoadException if anything goes wrong...
    4747     */
     
    6060    /**
    6161     * The internal method, which does the actual parsing.
    62      * 
     62     *
    6363     * @throws DatabaseLoadException should be thrown if anything gets wrong...
    6464     */
     
    8787     *
    8888     * The URL is provided by {@code getDatabaseUrl()} method.
    89      * 
     89     *
    9090     * @throws DatabaseLoadException if any error occurs during the download.
    9191     */
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/parser/MvcrParser.java

    r19964 r23190  
    5757            return;
    5858        }
    59        
     59
    6060        // ========== PARSING STREET ========== //
    6161        if (name.equals("ulice")) {
     
    245245        ZipEntry zipEntry = null;
    246246        try {
    247             zis = new ZipInputStream(new FileInputStream(getDatabasePath()));
    248 
    249             while ((zipEntry = zis.getNextEntry()) != null)
    250                 if (zipEntry.getName().equals("adresy.xml"))
    251                         break;
     247        zis = new ZipInputStream(new FileInputStream(getDatabasePath()));
     248
     249        while ((zipEntry = zis.getNextEntry()) != null)
     250            if (zipEntry.getName().equals("adresy.xml"))
     251                break;
    252252
    253253        } catch (IOException ioexp) {
     
    256256
    257257        if (zipEntry == null)
    258             throw new DatabaseLoadException(
     258        throw new DatabaseLoadException(
    259259                    "ZIP archiv s databází neobsahuje soubor 'adresy.xml'.");
    260260
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/proposal/ProposalDatabase.java

    r15166 r23190  
    8585    public void addProposals(OsmPrimitive primitive,
    8686                             Collection<Proposal> proposal) {
    87        
     87
    8888        ProposalContainer container = findContainer(primitive);
    8989        if (container == null) {
     
    114114    /**
    115115     * Gives a reference to the internal list of {@link ProposalContainer}s.
    116      * 
     116     *
    117117     * @return the refernence to internal changeset.
    118118     */
  • applications/editors/josm/plugins/duplicateway/src/org/openstreetmap/josm/plugins/duplicateway/JVector.java

    r13497 r23190  
    1515 * A class encapsulating a line Segment treating it as a Vector (
    1616 * direction and length). Includes Utility routines to perform various
    17  * transformations and Trigonometric operations 
     17 * transformations and Trigonometric operations
    1818 *
    1919 * @author Brent Easton
     
    2121 */
    2222public class JVector extends Line2D.Double {
    23  
     23
    2424  public static final double EARTH_CIRCUMFERENCE = 40041455;
    2525  protected static final double PI_ON_2 = Math.PI / 2.0;
    2626  protected Point2D.Double slopeIntercept = null;
    2727  protected Point2D.Double rtheta = null;
    28  
     28
    2929  /**
    3030   * Create new JVector joining two points
    31    * 
     31   *
    3232   * @param x1
    3333   * @param y1
     
    3838    super(x1, y1, x2, y2);
    3939  }
    40  
     40
    4141  /**
    4242   * Create new JVector from another JVector
    43    * 
     43   *
    4444   * @param v JVector to copy
    4545   */
     
    5151    y2 = v.y2;
    5252  }
    53  
     53
    5454  /**
    5555   * Create a new JVector based on a JOSM Segment object
    56    * 
     56   *
    5757   * @param s
    5858   */
     
    6060    super(s.from.eastNorth.east(), s.from.eastNorth.north(), s.to.eastNorth.east(), s.to.eastNorth.north());
    6161  }
    62  
     62
    6363  /**
    6464   * Calculate slope/intersect from cartesian co-ords
     
    7070    slopeIntercept = new Point2D.Double(slope, intersect);
    7171  }
    72  
     72
    7373  /**
    7474   * Return the slope of the JVector
     
    8181    return slopeIntercept.x;
    8282  }
    83  
     83
    8484  /**
    8585   * Return the Y intercept of the JVector
     
    9292    return slopeIntercept.y;
    9393  }
    94  
     94
    9595  /**
    9696   * Calculate the polar coordinates for this line as a ray with
     
    104104    rtheta = new Point2D.Double(r, theta);
    105105  }
    106  
     106
    107107  /**
    108108   * Return the length of the line segment
     
    115115    return rtheta.x;
    116116  }
    117  
     117
    118118  /**
    119119   * Return the angle of the line segment
     
    126126    return rtheta.y;
    127127  }
    128  
     128
    129129  /**
    130130   * Convert Polar co-ords to cartesian
     
    137137    slopeIntercept = null;
    138138  }
    139  
     139
    140140  /**
    141141   * Set the line segment using Polar co-ordinates
    142    * 
     142   *
    143143   * @param r line length
    144144   * @param theta angle
     
    148148    polarToCartesian();
    149149  }
    150  
     150
    151151  /**
    152152   * Set the length of the line segment
     
    157157    polarToCartesian();
    158158  }
    159  
     159
    160160  /**
    161161   * Reverse the direction of the segment
     
    171171    rtheta = null;
    172172  }
    173  
     173
    174174  /**
    175175   * Rotate the line segment about the origin
     
    183183    polarToCartesian();
    184184  }
    185  
     185
    186186  /**
    187187   * Rotate 90 degrees clockwise
     
    191191    rotate(-PI_ON_2);
    192192  }
    193  
     193
    194194  /**
    195195   * Rotate 90 degrees counterclockwise
     
    199199    rotate(PI_ON_2);
    200200  }
    201  
     201
    202202  /**
    203203   * Normalize theta to be in the range -PI < theta < PI
     
    216216    return theta;
    217217  }
    218  
    219   /**
    220    * Rotate the line segment 90 degrees and set the length. 
     218
     219  /**
     220   * Rotate the line segment 90 degrees and set the length.
    221221   * @param offset length
    222222   */
     
    226226  }
    227227
    228   /* 
    229    * Return the distance of the given point from this line. Offset is 
     228  /*
     229   * Return the distance of the given point from this line. Offset is
    230230   * -ve if the point is to the left of the line, or +ve if to the right
    231231   */
    232  
    233  
    234   /**
    235    * Return the distance of the given point from this line. Offset is 
     232
     233
     234  /**
     235   * Return the distance of the given point from this line. Offset is
    236236   * -ve if the point is to the left of the line, or +ve if to the right
    237    * @param target 
     237   * @param target
    238238   */
    239239  protected double calculateOffset(EastNorth target) {
    240    
     240
    241241    // Calculate the perpendicular interceptor to this point
    242242    EastNorth intersectPoint = perpIntersect(target);
    243243    JVector intersectRay = new JVector(intersectPoint.east(), intersectPoint.north(), target.east(), target.north());
    244    
     244
    245245    // Offset is equal to the length of the interceptor
    246246    double offset = intersectRay.getLength();
    247    
     247
    248248    // Check the angle between this line and the interceptor to calculate left/right
    249249    double theta = normalize(getTheta() - intersectRay.getTheta());
     
    251251      offset = -offset;
    252252    }
    253    
     253
    254254    return offset;
    255255  }
    256  
     256
    257257
    258258  /**
     
    282282   * @return
    283283   */
    284   public static double perpDistance(Segment s, EastNorth en) { 
     284  public static double perpDistance(Segment s, EastNorth en) {
    285285   return Line2D.ptSegDist(s.from.eastNorth.east(), s.from.eastNorth.north(), s.to.eastNorth.east(), s.to.eastNorth.north(), en.east(), en.north());
    286286  }
    287  
     287
    288288  /**
    289289   * Calculate the bisector between this and another Vector. A positive offset means
     
    297297    double newTheta = Math.PI + ls.getTheta() - getTheta();
    298298    newSeg.setPolar(Math.abs(offset), newSeg.getTheta() - newTheta/2.0);
    299    
     299
    300300    double angle = normalize(getTheta() - newSeg.getTheta());
    301301    if ((angle < 0 && offset > 0) || (angle > 0 && offset < 0)) {
     
    304304    return newSeg;
    305305  }
    306  
     306
    307307  /**
    308308   * Return the Perpendicular Intersector from a point to this line
     
    313313    return perpIntersect(n.eastNorth);
    314314  }
    315  
     315
    316316  /**
    317317   * Calculate the point on our line closest to the supplied point
     
    320320   */
    321321  public EastNorth perpIntersect(EastNorth en) {
    322    
     322
    323323    /*
    324324     * Calculate the coefficients for the two lines
     
    326326     *  2. The perpendicular line through the new point: y = cx + d
    327327     */
    328     double perpSlope = -1 / getSlope();   
     328    double perpSlope = -1 / getSlope();
    329329    double perpIntercept = en.north() - (en.east() * perpSlope);
    330    
     330
    331331    /*
    332332     * Solve the simultaneous equation to calculate the intersection
     
    334334     *  ax - cx = d - b
    335335     *  x (a-c) = d - b
    336      *  x = (d - b) / (a - c) 
     336     *  x = (d - b) / (a - c)
    337337     */
    338338    double intersectE = (perpIntercept - getIntercept()) / (getSlope() - perpSlope);
    339339    double intersectN = intersectE * getSlope() + getIntercept();
    340    
     340
    341341    return new EastNorth(intersectE, intersectN);
    342342  }
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/BooleanConfigurer.java

    r19624 r23190  
    2323 */
    2424public class BooleanConfigurer extends Configurer {
    25         private javax.swing.JCheckBox box;
     25    private javax.swing.JCheckBox box;
    2626
    27         public BooleanConfigurer() {
    28                 this(false);
    29         }
     27    public BooleanConfigurer() {
     28        this(false);
     29    }
    3030
    31         public BooleanConfigurer(boolean val) {
    32                 this(null, "", val);
    33         }
     31    public BooleanConfigurer(boolean val) {
     32        this(null, "", val);
     33    }
    3434
    35         public BooleanConfigurer(String key, String name, Boolean val) {
    36                 super(key, name, val);
    37         }
     35    public BooleanConfigurer(String key, String name, Boolean val) {
     36        super(key, name, val);
     37    }
    3838
    39         public BooleanConfigurer(String key, String name, boolean val) {
    40                 super(key, name, val ? Boolean.TRUE : Boolean.FALSE);
    41         }
     39    public BooleanConfigurer(String key, String name, boolean val) {
     40        super(key, name, val ? Boolean.TRUE : Boolean.FALSE);
     41    }
    4242
    43         public BooleanConfigurer(String key, String name) {
    44                 this(key, name, Boolean.FALSE);
    45         }
     43    public BooleanConfigurer(String key, String name) {
     44        this(key, name, Boolean.FALSE);
     45    }
    4646
    47         @Override
    48         public String getValueString() {
    49                 return booleanValue().toString();
    50         }
     47    @Override
     48    public String getValueString() {
     49        return booleanValue().toString();
     50    }
    5151
    52         @Override
    53         public void setValue(Object o) {
    54                 super.setValue(o);
    55                 if (box != null
    56                                 && !o.equals(box.isSelected())) {
    57                         box.setSelected(booleanValue().booleanValue());
    58                 }
    59         }
     52    @Override
     53    public void setValue(Object o) {
     54        super.setValue(o);
     55        if (box != null
     56                && !o.equals(box.isSelected())) {
     57            box.setSelected(booleanValue().booleanValue());
     58        }
     59    }
    6060
    61         @Override
    62         public void setValue(String s) {
    63                 setValue(Boolean.valueOf(s));
    64         }
     61    @Override
     62    public void setValue(String s) {
     63        setValue(Boolean.valueOf(s));
     64    }
    6565
    66         @Override
    67         public void setName(String s) {
    68                 super.setName(s);
    69                 if (box != null) {
    70                         box.setText(s);
    71                 }
    72         }
     66    @Override
     67    public void setName(String s) {
     68        super.setName(s);
     69        if (box != null) {
     70            box.setText(s);
     71        }
     72    }
    7373
    74         @Override
    75         public java.awt.Component getControls() {
    76                 if (box == null) {
    77                         box = new javax.swing.JCheckBox(getName());
    78                         box.setSelected(booleanValue().booleanValue());
    79                         box.addItemListener(new java.awt.event.ItemListener() {
    80                                 public void itemStateChanged(java.awt.event.ItemEvent e) {
    81                                         setValue(box.isSelected());
    82                                 }
    83                         });
    84                 }
    85                 return box;
    86         }
     74    @Override
     75    public java.awt.Component getControls() {
     76        if (box == null) {
     77            box = new javax.swing.JCheckBox(getName());
     78            box.setSelected(booleanValue().booleanValue());
     79            box.addItemListener(new java.awt.event.ItemListener() {
     80                public void itemStateChanged(java.awt.event.ItemEvent e) {
     81                    setValue(box.isSelected());
     82                }
     83            });
     84        }
     85        return box;
     86    }
    8787
    88         public Boolean booleanValue() {
    89                 return (Boolean) value;
    90         }
     88    public Boolean booleanValue() {
     89        return (Boolean) value;
     90    }
    9191}
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/Configurer.java

    r13497 r23190  
    1414 *
    1515 * You should have received a copy of the GNU Library General Public
    16  * License along with this library; if not, copies are available 
     16 * License along with this library; if not, copies are available
    1717 * at http://www.opensource.org.
    1818 */
     
    139139    changeSupport.addPropertyChangeListener(l);
    140140  }
    141  
     141
    142142  public void removePropertyChangeListener(PropertyChangeListener l) {
    143143    changeSupport.removePropertyChangeListener(l);
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/DoubleConfigurer.java

    r19624 r23190  
    3737
    3838    @Override
    39         public void setValue(String s) {
     39    public void setValue(String s) {
    4040        Double d = null;
    4141        try {
     
    5050
    5151    @Override
    52         public void setValue(Object o) {
     52    public void setValue(Object o) {
    5353        if (!noUpdate && nameField != null && o != null) {
    5454            nameField.setText(o.toString());
     
    5858
    5959    @Override
    60         public String getValueString() {
     60    public String getValueString() {
    6161        if (value == null || value.equals("")) {
    6262            return null;
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/IntConfigurer.java

    r19624 r23190  
    2424public class IntConfigurer extends StringConfigurer {
    2525
    26         public IntConfigurer() {
    27                 super();
    28         }
     26    public IntConfigurer() {
     27        super();
     28    }
    2929
    30         public IntConfigurer(String key, String name) {
    31                 this(key, name, 0);
    32         }
     30    public IntConfigurer(String key, String name) {
     31        this(key, name, 0);
     32    }
    3333
    34         public IntConfigurer(String key, String name, Integer val) {
    35                 super(key, name);
    36                 if (val != null) {
    37                         setValue(val);
    38                 }
    39         }
     34    public IntConfigurer(String key, String name, Integer val) {
     35        super(key, name);
     36        if (val != null) {
     37            setValue(val);
     38        }
     39    }
    4040
    41         @Override
    42         public void setValue(String s) {
    43                 Integer i = null;
    44                 try {
    45                         i = Integer.valueOf(s);
    46                 }
    47                 catch (NumberFormatException e) {
    48                         i = null;
    49                 }
    50                 if (i != null) {
    51                         setValue(i);
    52                 }
    53         }
     41    @Override
     42    public void setValue(String s) {
     43        Integer i = null;
     44        try {
     45            i = Integer.valueOf(s);
     46        }
     47        catch (NumberFormatException e) {
     48            i = null;
     49        }
     50        if (i != null) {
     51            setValue(i);
     52        }
     53    }
    5454
    55         public int getIntValue(int defaultValue) {
    56                 if (getValue() instanceof Integer) {
    57                         return ((Integer)getValue()).intValue();
    58                 }
    59                 else {
    60                         return defaultValue;
    61                 }
    62         }
     55    public int getIntValue(int defaultValue) {
     56        if (getValue() instanceof Integer) {
     57            return ((Integer)getValue()).intValue();
     58        }
     59        else {
     60            return defaultValue;
     61        }
     62    }
    6363
    64         @Override
    65         public void setValue(Object o) {
    66                 if (!noUpdate && nameField != null && o != null) {
    67                         nameField.setText(o.toString());
    68                 }
    69                 super.setValue(o);
    70         }
     64    @Override
     65    public void setValue(Object o) {
     66        if (!noUpdate && nameField != null && o != null) {
     67            nameField.setText(o.toString());
     68        }
     69        super.setValue(o);
     70    }
    7171
    72         @Override
    73         public String getValueString() {
    74                 return value == null ? null : value.toString();
    75         }
     72    @Override
     73    public String getValueString() {
     74        return value == null ? null : value.toString();
     75    }
    7676}
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/Lakewalker.java

    r19624 r23190  
    8484    public ArrayList<double[]> trace(double lat, double lon, double tl_lon, double br_lon, double tl_lat, double br_lat, ProgressMonitor progressMonitor) throws LakewalkerException {
    8585
    86         progressMonitor.beginTask(null);
    87 
    88         try {
    89 
    90                 LakewalkerWMS wms = new LakewalkerWMS(this.resolution, this.tilesize, this.wmslayer, this.workingdir);
    91                 LakewalkerBBox bbox = new LakewalkerBBox(tl_lat,tl_lon,br_lat,br_lon);
    92 
    93                 Boolean detect_loop = false;
    94 
    95                 ArrayList<double[]> nodelist = new ArrayList<double[]>();
    96 
    97                 int[] xy = geo_to_xy(lat,lon,this.resolution);
    98 
    99                 if(!bbox.contains(lat, lon)){
    100                         throw new LakewalkerException(tr("The starting location was not within the bbox"));
    101                 }
    102 
    103                 int v;
    104 
    105                 progressMonitor.indeterminateSubTask(tr("Looking for shoreline..."));
    106 
    107                 while(true){
    108                         double[] geo = xy_to_geo(xy[0],xy[1],this.resolution);
    109                         if(bbox.contains(geo[0],geo[1])==false){
    110                                 break;
    111                         }
    112 
    113                         v = wms.getPixel(xy[0], xy[1], progressMonitor.createSubTaskMonitor(0, false));
    114                         if(v > this.threshold){
    115                                 break;
    116                         }
    117 
    118                         int delta_lat = this.dirslat[getDirectionIndex(this.startdir)];
    119                         int delta_lon = this.dirslon[getDirectionIndex(this.startdir)];
    120 
    121                         xy[0] = xy[0]+delta_lon;
    122                         xy[1] = xy[1]+delta_lat;
    123 
    124                 }
    125 
    126                 int[] startxy = new int[] {xy[0], xy[1]};
    127                 double[] startgeo = xy_to_geo(xy[0],xy[1],this.resolution);
    128 
    129                 //System.out.printf("Found shore at lat %.4f lon %.4f\n",lat,lon);
    130 
    131                 int last_dir = this.getDirectionIndex(this.startdir);
    132 
    133                 for(int i = 0; i < this.maxnode; i++){
    134 
    135                         // Print a counter
    136                         if(i % 250 == 0){
    137                                 progressMonitor.indeterminateSubTask(tr("{0} nodes so far...",i));
    138                                 //System.out.println(i+" nodes so far...");
    139                         }
    140 
    141                         // Some variables we need
    142                         int d;
    143                         int test_x=0;
    144                         int test_y=0;
    145                         int new_dir = 0;
    146 
    147                         // Loop through all the directions we can go
    148                         for(d = 1; d <= this.dirslat.length; d++){
    149 
    150                                 // Decide which direction we want to look at from this pixel
    151                                 new_dir = (last_dir + d + 4) % 8;
    152 
    153                                 test_x = xy[0] + this.dirslon[new_dir];
    154                                 test_y = xy[1] + this.dirslat[new_dir];
    155 
    156                                 double[] geo = xy_to_geo(test_x,test_y,this.resolution);
    157 
    158                                 if(!bbox.contains(geo[0], geo[1])){
    159                                         System.out.println("Outside bbox");
    160                                         break;
    161                                 }
    162 
    163                                 v = wms.getPixel(test_x, test_y, progressMonitor.createSubTaskMonitor(0, false));
    164                                 if(v > this.threshold){
    165                                         break;
    166                                 }
    167 
    168                                 if(d == this.dirslat.length-1){
    169                                         System.out.println("Got stuck");
    170                                         break;
    171                                 }
    172                         }
    173 
    174                         // Remember this direction
    175                         last_dir = new_dir;
    176 
    177                         // Set the pixel we found as current
    178                         xy[0] = test_x;
    179                         xy[1] = test_y;
    180 
    181                         // Break the loop if we managed to get back to our starting point
    182                         if(xy[0] == startxy[0] && xy[1] == startxy[1]){
    183                                 break;
    184                         }
    185 
    186                         // Store this node
    187                         double[] geo = xy_to_geo(xy[0],xy[1],this.resolution);
    188                         nodelist.add(geo);
    189                         //System.out.println("Adding node at "+xy[0]+","+xy[1]+" ("+geo[1]+","+geo[0]+")");
    190 
    191                         // Check if we got stuck in a loop
    192                         double start_proximity = Math.pow((geo[0] - startgeo[0]),2) + Math.pow((geo[1] - startgeo[1]),2);
    193 
    194                         if(detect_loop){
    195                                 if(start_proximity < Math.pow(start_radius_small,2)){
    196                                         System.out.println("Detected loop");
    197                                         break;
    198                                 }
    199                         }else{
    200                                 if(start_proximity > Math.pow(start_radius_big,2)){
    201                                         detect_loop = true;
    202                                 }
    203                         }
    204                 }
    205 
    206                 return nodelist;
    207         } finally {
    208                 progressMonitor.finishTask();
    209         }
     86        progressMonitor.beginTask(null);
     87
     88        try {
     89
     90            LakewalkerWMS wms = new LakewalkerWMS(this.resolution, this.tilesize, this.wmslayer, this.workingdir);
     91            LakewalkerBBox bbox = new LakewalkerBBox(tl_lat,tl_lon,br_lat,br_lon);
     92
     93            Boolean detect_loop = false;
     94
     95            ArrayList<double[]> nodelist = new ArrayList<double[]>();
     96
     97            int[] xy = geo_to_xy(lat,lon,this.resolution);
     98
     99            if(!bbox.contains(lat, lon)){
     100                throw new LakewalkerException(tr("The starting location was not within the bbox"));
     101            }
     102
     103            int v;
     104
     105            progressMonitor.indeterminateSubTask(tr("Looking for shoreline..."));
     106
     107            while(true){
     108                double[] geo = xy_to_geo(xy[0],xy[1],this.resolution);
     109                if(bbox.contains(geo[0],geo[1])==false){
     110                    break;
     111                }
     112
     113                v = wms.getPixel(xy[0], xy[1], progressMonitor.createSubTaskMonitor(0, false));
     114                if(v > this.threshold){
     115                    break;
     116                }
     117
     118                int delta_lat = this.dirslat[getDirectionIndex(this.startdir)];
     119                int delta_lon = this.dirslon[getDirectionIndex(this.startdir)];
     120
     121                xy[0] = xy[0]+delta_lon;
     122                xy[1] = xy[1]+delta_lat;
     123
     124            }
     125
     126            int[] startxy = new int[] {xy[0], xy[1]};
     127            double[] startgeo = xy_to_geo(xy[0],xy[1],this.resolution);
     128
     129            //System.out.printf("Found shore at lat %.4f lon %.4f\n",lat,lon);
     130
     131            int last_dir = this.getDirectionIndex(this.startdir);
     132
     133            for(int i = 0; i < this.maxnode; i++){
     134
     135                // Print a counter
     136                if(i % 250 == 0){
     137                    progressMonitor.indeterminateSubTask(tr("{0} nodes so far...",i));
     138                    //System.out.println(i+" nodes so far...");
     139                }
     140
     141                // Some variables we need
     142                int d;
     143                int test_x=0;
     144                int test_y=0;
     145                int new_dir = 0;
     146
     147                // Loop through all the directions we can go
     148                for(d = 1; d <= this.dirslat.length; d++){
     149
     150                    // Decide which direction we want to look at from this pixel
     151                    new_dir = (last_dir + d + 4) % 8;
     152
     153                    test_x = xy[0] + this.dirslon[new_dir];
     154                    test_y = xy[1] + this.dirslat[new_dir];
     155
     156                    double[] geo = xy_to_geo(test_x,test_y,this.resolution);
     157
     158                    if(!bbox.contains(geo[0], geo[1])){
     159                        System.out.println("Outside bbox");
     160                        break;
     161                    }
     162
     163                    v = wms.getPixel(test_x, test_y, progressMonitor.createSubTaskMonitor(0, false));
     164                    if(v > this.threshold){
     165                        break;
     166                    }
     167
     168                    if(d == this.dirslat.length-1){
     169                        System.out.println("Got stuck");
     170                        break;
     171                    }
     172                }
     173
     174                // Remember this direction
     175                last_dir = new_dir;
     176
     177                // Set the pixel we found as current
     178                xy[0] = test_x;
     179                xy[1] = test_y;
     180
     181                // Break the loop if we managed to get back to our starting point
     182                if(xy[0] == startxy[0] && xy[1] == startxy[1]){
     183                    break;
     184                }
     185
     186                // Store this node
     187                double[] geo = xy_to_geo(xy[0],xy[1],this.resolution);
     188                nodelist.add(geo);
     189                //System.out.println("Adding node at "+xy[0]+","+xy[1]+" ("+geo[1]+","+geo[0]+")");
     190
     191                // Check if we got stuck in a loop
     192                double start_proximity = Math.pow((geo[0] - startgeo[0]),2) + Math.pow((geo[1] - startgeo[1]),2);
     193
     194                if(detect_loop){
     195                    if(start_proximity < Math.pow(start_radius_small,2)){
     196                        System.out.println("Detected loop");
     197                        break;
     198                    }
     199                }else{
     200                    if(start_proximity > Math.pow(start_radius_big,2)){
     201                        detect_loop = true;
     202                    }
     203                }
     204            }
     205
     206            return nodelist;
     207        } finally {
     208            progressMonitor.finishTask();
     209        }
    210210    }
    211211
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerAction.java

    r19624 r23190  
    155155                }
    156156
    157                                 @Override protected void cancel() {
    158                                         LakewalkerAction.this.cancel();
    159                                 }
     157                @Override protected void cancel() {
     158                    LakewalkerAction.this.cancel();
     159                }
    160160            };
    161161            Thread executeThread = new Thread(lakewalkerTask);
     
    247247
    248248                } catch (Exception ex) {
    249                         ex.printStackTrace();
     249                    ex.printStackTrace();
    250250                }
    251251
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerException.java

    r19624 r23190  
    55class LakewalkerException extends Exception {
    66    public LakewalkerException(){
    7         super(tr("An unknown error has occurred"));
     7        super(tr("An unknown error has occurred"));
    88    }
    99
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerPlugin.java

    r19624 r23190  
    1515 */
    1616public class LakewalkerPlugin extends Plugin {
    17         public LakewalkerPlugin(PluginInformation info) {
    18                 super(info);
    19                 MainMenu.add(Main.main.menu.toolsMenu, new LakewalkerAction(tr("Lake Walker")));
    20         }
     17    public LakewalkerPlugin(PluginInformation info) {
     18        super(info);
     19        MainMenu.add(Main.main.menu.toolsMenu, new LakewalkerAction(tr("Lake Walker")));
     20    }
    2121
    22         @Override
    23         public PreferenceSetting getPreferenceSetting()
    24         {
    25                 return new LakewalkerPreferences();
    26         }
     22    @Override
     23    public PreferenceSetting getPreferenceSetting()
     24    {
     25        return new LakewalkerPreferences();
     26    }
    2727
    2828}
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerWMS.java

    r19624 r23190  
    4848
    4949    public BufferedImage getTile(int x, int y, ProgressMonitor progressMonitor) throws LakewalkerException {
    50         progressMonitor.beginTask(tr("Downloading image tile..."));
    51         try {
    52                 String layer = "global_mosaic_base";
    53 
    54                 int[] bottom_left_xy = new int[2];
    55                 bottom_left_xy[0] = floor(x,this.tilesize);
    56                 bottom_left_xy[1] = floor(y,this.tilesize);
    57 
    58                 int[] top_right_xy = new int[2];
    59                 top_right_xy[0] = bottom_left_xy[0] + this.tilesize;
    60                 top_right_xy[1] = bottom_left_xy[1] + this.tilesize;
    61 
    62                 double[] topright_geo = xy_to_geo(top_right_xy[0],top_right_xy[1],this.resolution);
    63                 double[] bottomleft_geo = xy_to_geo(bottom_left_xy[0],bottom_left_xy[1],this.resolution);
    64 
    65                 String filename = this.wmslayer+"/landsat_"+this.resolution+"_"+this.tilesize+
    66                 "_xy_"+bottom_left_xy[0]+"_"+bottom_left_xy[1]+".png";
    67 
    68                 // The WMS server only understands decimal points using periods, so we need
    69                 // to convert to a locale that uses that to build the proper URL
    70                 NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
    71                 DecimalFormat df = (DecimalFormat)nf;
    72                 df.applyLocalizedPattern("0.000000");
    73 
    74                 String urlloc = "http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&layers="+layer+
    75                 "&styles="+wmslayer+"&srs=EPSG:4326&format=image/png"+
    76                 "&bbox="+df.format(bottomleft_geo[1])+","+df.format(bottomleft_geo[0])+
    77                 ","+df.format(topright_geo[1])+","+df.format(topright_geo[0])+
    78                 "&width="+this.tilesize+"&height="+this.tilesize;
    79 
    80                 File file = new File(this.working_dir,filename);
    81 
    82                 // Calculate the hashmap key
    83                 String hashkey = Integer.toString(bottom_left_xy[0])+":"+Integer.toString(bottom_left_xy[1]);
    84 
    85                 // See if this image is already loaded
    86                 if(this.image != null){
    87                         if(this.imagex != bottom_left_xy[0] || this.imagey != bottom_left_xy[1]){
    88 
    89                                 // Check if this image exists in the hashmap
    90                                 if(this.imageindex.containsKey(hashkey)){
    91                                         // Store which image we have
    92                                         this.imagex = bottom_left_xy[0];
    93                                         this.imagey = bottom_left_xy[1];
    94 
    95                                         // Retrieve from cache
    96                                         this.image = this.images.get(this.imageindex.get(hashkey));
    97                                         return this.image;
    98                                 } else {
    99                                         this.image = null;
    100                                 }
    101                         } else {
    102                                 return this.image;
    103                         }
    104                 }
    105 
    106                 try {
    107                         System.out.println("Looking for image in disk cache: "+filename);
    108 
    109                         // Read from a file
    110                         this.image = ImageIO.read(file);
    111 
    112                         this.images.add(this.image);
    113                         this.imageindex.put(hashkey,this.images.size()-1);
    114 
    115                 } catch(FileNotFoundException e){
    116                         System.out.println("Could not find cached image, downloading.");
    117                 } catch(IOException e){
    118                         System.out.println(e.getMessage());
    119                 } catch(Exception e){
    120                         System.out.println(e.getMessage());
    121                 }
    122 
    123                 if(this.image == null){
    124                         /**
    125                         * Try downloading the image
    126                         */
    127                         try {
    128                                 System.out.println("Downloading from "+urlloc);
    129 
    130                                 // Read from a URL
    131                                 URL url = new URL(urlloc);
    132                                 this.image = ImageIO.read(url); // this can return null!
    133                         } catch(MalformedURLException e){
    134                                 System.out.println(e.getMessage());
    135                         } catch(IOException e){
    136                                 System.out.println(e.getMessage());
    137                         } catch(Exception e){
    138                                 System.out.println(e.getMessage());
    139                         }
    140 
    141                         if (this.image != null) {
    142                                 this.images.add(this.image);
    143                                 this.imageindex.put(hashkey,this.images.size()-1);
    144 
    145                                 this.saveimage(file,this.image);
    146                         }
    147                 }
    148 
    149                 this.imagex = bottom_left_xy[0];
    150                 this.imagey = bottom_left_xy[1];
    151 
    152                 if(this.image == null){
    153                         throw new LakewalkerException(tr("Could not acquire image"));
    154                 }
    155 
    156                 return this.image;
    157         } finally {
    158                 progressMonitor.finishTask();
    159         }
     50        progressMonitor.beginTask(tr("Downloading image tile..."));
     51        try {
     52            String layer = "global_mosaic_base";
     53
     54            int[] bottom_left_xy = new int[2];
     55            bottom_left_xy[0] = floor(x,this.tilesize);
     56            bottom_left_xy[1] = floor(y,this.tilesize);
     57
     58            int[] top_right_xy = new int[2];
     59            top_right_xy[0] = bottom_left_xy[0] + this.tilesize;
     60            top_right_xy[1] = bottom_left_xy[1] + this.tilesize;
     61
     62            double[] topright_geo = xy_to_geo(top_right_xy[0],top_right_xy[1],this.resolution);
     63            double[] bottomleft_geo = xy_to_geo(bottom_left_xy[0],bottom_left_xy[1],this.resolution);
     64
     65            String filename = this.wmslayer+"/landsat_"+this.resolution+"_"+this.tilesize+
     66            "_xy_"+bottom_left_xy[0]+"_"+bottom_left_xy[1]+".png";
     67
     68            // The WMS server only understands decimal points using periods, so we need
     69            // to convert to a locale that uses that to build the proper URL
     70            NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
     71            DecimalFormat df = (DecimalFormat)nf;
     72            df.applyLocalizedPattern("0.000000");
     73
     74            String urlloc = "http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&layers="+layer+
     75            "&styles="+wmslayer+"&srs=EPSG:4326&format=image/png"+
     76            "&bbox="+df.format(bottomleft_geo[1])+","+df.format(bottomleft_geo[0])+
     77            ","+df.format(topright_geo[1])+","+df.format(topright_geo[0])+
     78            "&width="+this.tilesize+"&height="+this.tilesize;
     79
     80            File file = new File(this.working_dir,filename);
     81
     82            // Calculate the hashmap key
     83            String hashkey = Integer.toString(bottom_left_xy[0])+":"+Integer.toString(bottom_left_xy[1]);
     84
     85            // See if this image is already loaded
     86            if(this.image != null){
     87                if(this.imagex != bottom_left_xy[0] || this.imagey != bottom_left_xy[1]){
     88
     89                    // Check if this image exists in the hashmap
     90                    if(this.imageindex.containsKey(hashkey)){
     91                        // Store which image we have
     92                        this.imagex = bottom_left_xy[0];
     93                        this.imagey = bottom_left_xy[1];
     94
     95                        // Retrieve from cache
     96                        this.image = this.images.get(this.imageindex.get(hashkey));
     97                        return this.image;
     98                    } else {
     99                        this.image = null;
     100                    }
     101                } else {
     102                    return this.image;
     103                }
     104            }
     105
     106            try {
     107                System.out.println("Looking for image in disk cache: "+filename);
     108
     109                // Read from a file
     110                this.image = ImageIO.read(file);
     111
     112                this.images.add(this.image);
     113                this.imageindex.put(hashkey,this.images.size()-1);
     114
     115            } catch(FileNotFoundException e){
     116                System.out.println("Could not find cached image, downloading.");
     117            } catch(IOException e){
     118                System.out.println(e.getMessage());
     119            } catch(Exception e){
     120                System.out.println(e.getMessage());
     121            }
     122
     123            if(this.image == null){
     124                /**
     125                * Try downloading the image
     126                */
     127                try {
     128                    System.out.println("Downloading from "+urlloc);
     129
     130                    // Read from a URL
     131                    URL url = new URL(urlloc);
     132                    this.image = ImageIO.read(url); // this can return null!
     133                } catch(MalformedURLException e){
     134                    System.out.println(e.getMessage());
     135                } catch(IOException e){
     136                    System.out.println(e.getMessage());
     137                } catch(Exception e){
     138                    System.out.println(e.getMessage());
     139                }
     140
     141                if (this.image != null) {
     142                    this.images.add(this.image);
     143                    this.imageindex.put(hashkey,this.images.size()-1);
     144
     145                    this.saveimage(file,this.image);
     146                }
     147            }
     148
     149            this.imagex = bottom_left_xy[0];
     150            this.imagey = bottom_left_xy[1];
     151
     152            if(this.image == null){
     153                throw new LakewalkerException(tr("Could not acquire image"));
     154            }
     155
     156            return this.image;
     157        } finally {
     158            progressMonitor.finishTask();
     159        }
    160160    }
    161161
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/StringConfigurer.java

    r19624 r23190  
    7373      nameField.addKeyListener(new java.awt.event.KeyAdapter() {
    7474        @Override
    75                 public void keyReleased(java.awt.event.KeyEvent evt) {
     75        public void keyReleased(java.awt.event.KeyEvent evt) {
    7676          noUpdate = true;
    7777          setValue(nameField.getText());
  • applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/StringEnumConfigurer.java

    r19624 r23190  
    6464    }
    6565    @Override
    66         public Component getControls() {
     66    public Component getControls() {
    6767        if (panel == null) {
    6868            panel = Box.createHorizontalBox();
     
    8585
    8686    @Override
    87         public void setValue(Object o) {
     87    public void setValue(Object o) {
    8888        if(o == null)
    8989            o = 0;
     
    9494
    9595    @Override
    96         public void setValue(String s) {
     96    public void setValue(String s) {
    9797        Integer n = 0;
    9898        for (int i = 0; i < transValues.length; ++i)
     
    107107
    108108    @Override
    109         public String getValueString() {
     109    public String getValueString() {
    110110        return validValues[(Integer)value];
    111111    }
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/CalibrationFileFilter.java

    r20217 r23190  
    3030 */
    3131public class CalibrationFileFilter extends FileFilter {
    32        
    33         // Extension used by calibration files
    34         public static final String EXTENSION = ".cal";
    3532
    36         @Override
    37         public boolean accept(File f) {
    38             String ext3 = ( f.getName().length() > 4 ) ?  f.getName().substring( f.getName().length() - 4 ).toLowerCase() : "";
     33    // Extension used by calibration files
     34    public static final String EXTENSION = ".cal";
    3935
    40             // TODO: check what is supported by Java :)
    41             return ( f.isDirectory()
    42                 ||      ext3.equals( EXTENSION )
    43                 );
    44         }
     36    @Override
     37    public boolean accept(File f) {
     38        String ext3 = ( f.getName().length() > 4 ) ?  f.getName().substring( f.getName().length() - 4 ).toLowerCase() : "";
    4539
    46         @Override
    47         public String getDescription() {
    48                 return tr("Calibration Files")+ " (*" + EXTENSION + ")";
    49         }
     40        // TODO: check what is supported by Java :)
     41        return ( f.isDirectory()
     42            ||  ext3.equals( EXTENSION )
     43            );
     44    }
     45
     46    @Override
     47    public String getDescription() {
     48        return tr("Calibration Files")+ " (*" + EXTENSION + ")";
     49    }
    5050}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/LoadPictureCalibrationAction.java

    r20217 r23190  
    4444public class LoadPictureCalibrationAction extends JosmAction {
    4545
    46         // Owner layer of the action
    47         PicLayerAbstract m_owner = null;
    48        
    49         /**
    50         * Constructor
    51         */
    52         public LoadPictureCalibrationAction( PicLayerAbstract owner ) {
    53                 super(tr("Load Picture Calibration..."), null, tr("Loads calibration data to a file"), null, false);
    54                 // Remember the owner...
    55                 m_owner = owner;
    56         }
    57        
    58         /**
    59         * Action handler
    60         */
    61         public void actionPerformed(ActionEvent arg0) {
    62                 // Save dialog
    63                 final JFileChooser fc = new JFileChooser();
    64                 fc.setAcceptAllFileFilterUsed( false );
    65                 fc.setFileFilter( new CalibrationFileFilter() );
    66                 fc.setSelectedFile( new File(m_owner.getPicLayerName() + CalibrationFileFilter.EXTENSION));
    67                 int result = fc.showOpenDialog(Main.parent );
     46    // Owner layer of the action
     47    PicLayerAbstract m_owner = null;
     48   
     49    /**
     50    * Constructor
     51    */
     52    public LoadPictureCalibrationAction( PicLayerAbstract owner ) {
     53        super(tr("Load Picture Calibration..."), null, tr("Loads calibration data to a file"), null, false);
     54        // Remember the owner...
     55        m_owner = owner;
     56    }
     57   
     58    /**
     59    * Action handler
     60    */
     61    public void actionPerformed(ActionEvent arg0) {
     62        // Save dialog
     63        final JFileChooser fc = new JFileChooser();
     64        fc.setAcceptAllFileFilterUsed( false );
     65        fc.setFileFilter( new CalibrationFileFilter() );
     66        fc.setSelectedFile( new File(m_owner.getPicLayerName() + CalibrationFileFilter.EXTENSION));
     67        int result = fc.showOpenDialog(Main.parent );
    6868
    69                 if ( result == JFileChooser.APPROVE_OPTION ) {
    70                                        
    71                         // Load
    72                         try {
    73                                 Properties props = new Properties();
    74                                 props.load(new FileInputStream(fc.getSelectedFile()));
    75                                 m_owner.loadCalibration(props);
    76                         } catch (Exception e) {
    77                                 // Error
    78                                 e.printStackTrace();
    79                                 JOptionPane.showMessageDialog(Main.parent , tr("Loading file failed: {0}", e.getMessage()));
    80                         }
    81                 }
    82         }
     69        if ( result == JFileChooser.APPROVE_OPTION ) {
     70                   
     71            // Load
     72            try {
     73                Properties props = new Properties();
     74                props.load(new FileInputStream(fc.getSelectedFile()));
     75                m_owner.loadCalibration(props);
     76            } catch (Exception e) {
     77                // Error
     78                e.printStackTrace();
     79                JOptionPane.showMessageDialog(Main.parent , tr("Loading file failed: {0}", e.getMessage()));
     80            }
     81        }
     82    }
    8383}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/MovePictureAction.java

    r20217 r23190  
    3838 * This class handles the input during moving the picture.
    3939 */
    40 public class MovePictureAction extends MapMode implements MouseListener, MouseMotionListener 
     40public class MovePictureAction extends MapMode implements MouseListener, MouseMotionListener
    4141{
    42         // Action ongoing?
    43         private boolean mb_dragging = false;
    44        
    45         // Last mouse position
    46         private EastNorth m_prevEastNorth;
    47        
    48         // The layer we're working on
    49         private PicLayerAbstract m_currentLayer = null;
    50        
    51         /**
    52          * Constructor
    53          */
    54         public MovePictureAction(MapFrame frame) {
    55                 super(tr("PicLayer move"), "move", tr("Drag to move the picture"), frame, ImageProvider.getCursor("crosshair", null));
    56         }
     42    // Action ongoing?
     43    private boolean mb_dragging = false;
    5744
    58     @Override
     45    // Last mouse position
     46    private EastNorth m_prevEastNorth;
     47
     48    // The layer we're working on
     49    private PicLayerAbstract m_currentLayer = null;
     50
     51    /**
     52     * Constructor
     53     */
     54    public MovePictureAction(MapFrame frame) {
     55        super(tr("PicLayer move"), "move", tr("Drag to move the picture"), frame, ImageProvider.getCursor("crosshair", null));
     56    }
     57
     58    @Override
    5959    public void enterMode() {
    6060        super.enterMode();
     
    6363    }
    6464
    65     @Override 
     65    @Override
    6666    public void exitMode() {
    6767        super.exitMode();
    6868        Main.map.mapView.removeMouseListener(this);
    6969        Main.map.mapView.removeMouseMotionListener(this);
    70     }   
    71        
    72     @Override 
     70    }
     71
     72    @Override
    7373    public void mousePressed(MouseEvent e) {
    74        
    75         // If everything is OK, we start dragging/moving the picture
    76         if ( Main.map.mapView.getActiveLayer() instanceof PicLayerAbstract ) {
    77                 m_currentLayer = (PicLayerAbstract)Main.map.mapView.getActiveLayer();
    78                
    79                 if ( m_currentLayer != null && e.getButton() == MouseEvent.BUTTON1 ) {
    80                         mb_dragging = true;
    81                         m_prevEastNorth=Main.map.mapView.getEastNorth(e.getX(),e.getY());
    82                 }
    83         }
    84     }   
    85    
    86     @Override 
     74
     75        // If everything is OK, we start dragging/moving the picture
     76        if ( Main.map.mapView.getActiveLayer() instanceof PicLayerAbstract ) {
     77            m_currentLayer = (PicLayerAbstract)Main.map.mapView.getActiveLayer();
     78
     79            if ( m_currentLayer != null && e.getButton() == MouseEvent.BUTTON1 ) {
     80                mb_dragging = true;
     81                m_prevEastNorth=Main.map.mapView.getEastNorth(e.getX(),e.getY());
     82            }
     83        }
     84    }
     85
     86    @Override
    8787    public void mouseDragged(MouseEvent e) {
    88         // Picture moving is ongoing
     88        // Picture moving is ongoing
    8989        if(mb_dragging) {
    9090            EastNorth eastNorth = Main.map.mapView.getEastNorth(e.getX(),e.getY());
    9191            m_currentLayer.movePictureBy(
    92                 eastNorth.east()-m_prevEastNorth.east(),
     92                eastNorth.east()-m_prevEastNorth.east(),
    9393                eastNorth.north()-m_prevEastNorth.north()
    9494            );
     
    9696            Main.map.mapView.repaint();
    9797        }
    98     }   
    99    
    100     @Override 
     98    }
     99
     100    @Override
    101101    public void mouseReleased(MouseEvent e) {
    102         // Stop moving
    103         mb_dragging = false;
    104     }   
     102        // Stop moving
     103        mb_dragging = false;
     104    }
    105105
    106106}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/NewLayerFromClipboardAction.java

    r22549 r23190  
    3535 */
    3636public class NewLayerFromClipboardAction extends JosmAction {
    37        
    38         /**
    39          * Constructor...
    40          */
    41         public NewLayerFromClipboardAction() {
    42                 super(tr("New picture layer from clipboard"), null, null, null, false);
    43         }
    4437
    45         /**
    46          * Action handler
    47          */
    48         public void actionPerformed(ActionEvent arg0) {
    49                 // Create layer from clipboard
    50                 PicLayerFromClipboard layer = new PicLayerFromClipboard();
    51                 // Add layer only if successfully initialized
    52                 try {
    53                         layer.initialize();
    54                 }
    55                 catch (IOException e) {
    56                         // Failed
    57                         System.out.println( "NewLayerFromClipboardAction::actionPerformed - " + e.getMessage() );
    58                         JOptionPane.showMessageDialog(null, e.getMessage() ); 
    59                         return;
    60                 }
    61                 // Add layer
    62                 Main.main.addLayer( layer );
    63         }
     38    /**
     39     * Constructor...
     40     */
     41    public NewLayerFromClipboardAction() {
     42        super(tr("New picture layer from clipboard"), null, null, null, false);
     43    }
     44
     45    /**
     46     * Action handler
     47     */
     48    public void actionPerformed(ActionEvent arg0) {
     49        // Create layer from clipboard
     50        PicLayerFromClipboard layer = new PicLayerFromClipboard();
     51        // Add layer only if successfully initialized
     52        try {
     53            layer.initialize();
     54        }
     55        catch (IOException e) {
     56            // Failed
     57            System.out.println( "NewLayerFromClipboardAction::actionPerformed - " + e.getMessage() );
     58            JOptionPane.showMessageDialog(null, e.getMessage() );
     59            return;
     60        }
     61        // Add layer
     62        Main.main.addLayer( layer );
     63    }
    6464}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/NewLayerFromFileAction.java

    r22549 r23190  
    3939 */
    4040public class NewLayerFromFileAction extends JosmAction {
    41        
    42         /**
    43          * Provides filtering of only image files.
    44          */
    45         private class ImageFileFilter extends FileFilter {
    4641
    47                 @Override
    48                 public boolean accept(File f) {
    49                    
    50                     String ext3 = ( f.getName().length() > 4 ) ?  f.getName().substring( f.getName().length() - 4 ).toLowerCase() : "";
    51                     String ext4 = ( f.getName().length() > 5 ) ?  f.getName().substring( f.getName().length() - 5 ).toLowerCase() : "";
     42    /**
     43     * Provides filtering of only image files.
     44     */
     45    private class ImageFileFilter extends FileFilter {
    5246
    53                     // TODO: check what is supported by Java :)
    54                     return ( f.isDirectory()
    55                         ||      ext3.equals( ".jpg" )
    56                         ||      ext4.equals( ".jpeg" )
    57                         ||      ext3.equals( ".png" )
    58                         );
    59                 }
     47        @Override
     48        public boolean accept(File f) {
     49
     50            String ext3 = ( f.getName().length() > 4 ) ?  f.getName().substring( f.getName().length() - 4 ).toLowerCase() : "";
     51            String ext4 = ( f.getName().length() > 5 ) ?  f.getName().substring( f.getName().length() - 5 ).toLowerCase() : "";
     52
     53            // TODO: check what is supported by Java :)
     54            return ( f.isDirectory()
     55                ||  ext3.equals( ".jpg" )
     56                ||  ext4.equals( ".jpeg" )
     57                ||  ext3.equals( ".png" )
     58                );
     59        }
    6060
    6161
    62                 @Override
    63                 public String getDescription() {
    64                         return tr("Image files");
    65                 }
    66                
    67         }
    68        
    69         /**
    70          * Constructor...
    71          */
    72         public NewLayerFromFileAction() {
    73                 super(tr("New picture layer from file..."), null, null, null, false);
    74         }
     62        @Override
     63        public String getDescription() {
     64            return tr("Image files");
     65        }
    7566
    76         /**
    77          * Action handler
    78          */
    79         public void actionPerformed(ActionEvent arg0) {
    80                
    81                 // Choose a file
    82                 JFileChooser fc = new JFileChooser();
    83                 fc.setAcceptAllFileFilterUsed( false );
    84                 fc.setFileFilter( new ImageFileFilter() );
    85                 int result = fc.showOpenDialog( Main.parent );
    86                
    87                 // Create a layer?
    88                 if ( result == JFileChooser.APPROVE_OPTION ) {
    89                         // Create layer from file
    90                         PicLayerFromFile layer = new PicLayerFromFile( fc.getSelectedFile() );
    91                         // Add layer only if successfully initialized
    92                         try {
    93                                 layer.initialize();
    94                         }
    95                         catch (IOException e) {
    96                                 // Failed
    97                                 System.out.println( "NewLayerFromFileAction::actionPerformed - " + e.getMessage() );
    98                                 JOptionPane.showMessageDialog(null, e.getMessage() ); 
    99                                 return;
    100                         }
    101                         // Add layer
    102                         Main.main.addLayer( layer );
    103                 }
    104                
    105         }
     67    }
     68
     69    /**
     70     * Constructor...
     71     */
     72    public NewLayerFromFileAction() {
     73        super(tr("New picture layer from file..."), null, null, null, false);
     74    }
     75
     76    /**
     77     * Action handler
     78     */
     79    public void actionPerformed(ActionEvent arg0) {
     80
     81        // Choose a file
     82        JFileChooser fc = new JFileChooser();
     83        fc.setAcceptAllFileFilterUsed( false );
     84        fc.setFileFilter( new ImageFileFilter() );
     85        int result = fc.showOpenDialog( Main.parent );
     86
     87        // Create a layer?
     88        if ( result == JFileChooser.APPROVE_OPTION ) {
     89            // Create layer from file
     90            PicLayerFromFile layer = new PicLayerFromFile( fc.getSelectedFile() );
     91            // Add layer only if successfully initialized
     92            try {
     93                layer.initialize();
     94            }
     95            catch (IOException e) {
     96                // Failed
     97                System.out.println( "NewLayerFromFileAction::actionPerformed - " + e.getMessage() );
     98                JOptionPane.showMessageDialog(null, e.getMessage() );
     99                return;
     100            }
     101            // Add layer
     102            Main.main.addLayer( layer );
     103        }
     104
     105    }
    106106}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/PicLayerAbstract.java

    r22549 r23190  
    275275     */
    276276    public void saveCalibration( Properties props ) {
    277         // Save
    278         props.put(INITIAL_POS_X, "" + m_initial_position.getX());
    279         props.put(INITIAL_POS_Y, "" + m_initial_position.getY());
    280         props.put(POSITION_X, "" + m_position.getX());
    281         props.put(POSITION_Y, "" + m_position.getY());
    282         props.put(INITIAL_SCALE, "" + m_initial_scale);
    283         props.put(SCALEX, "" + m_scalex);
    284         props.put(SCALEY, "" + m_scaley);
    285         props.put(ANGLE, "" + m_angle);
     277        // Save
     278        props.put(INITIAL_POS_X, "" + m_initial_position.getX());
     279        props.put(INITIAL_POS_Y, "" + m_initial_position.getY());
     280        props.put(POSITION_X, "" + m_position.getX());
     281        props.put(POSITION_Y, "" + m_position.getY());
     282        props.put(INITIAL_SCALE, "" + m_initial_scale);
     283        props.put(SCALEX, "" + m_scalex);
     284        props.put(SCALEY, "" + m_scaley);
     285        props.put(ANGLE, "" + m_angle);
    286286    }
    287287
     
    292292     */
    293293    public void loadCalibration( Properties props ) {
    294         // Load
    295                 double pos_x = Double.valueOf( props.getProperty(POSITION_X));
    296                 double pos_y = Double.valueOf( props.getProperty(POSITION_Y));
    297                 double in_pos_x = Double.valueOf( props.getProperty(INITIAL_POS_X));
    298                 double in_pos_y = Double.valueOf( props.getProperty(INITIAL_POS_Y));
    299                 double angle = Double.valueOf( props.getProperty(ANGLE));
    300                 double in_scale = Double.valueOf( props.getProperty(INITIAL_SCALE));
    301                 double scale_x = Double.valueOf( props.getProperty(SCALEX));
    302                 double scale_y = Double.valueOf( props.getProperty(SCALEY));
    303                         m_position.setLocation(pos_x, pos_y);
    304                 m_initial_position.setLocation(pos_x, pos_y);
    305                 m_angle = angle;
    306                 m_scalex = scale_x;
    307                 m_scaley = scale_y;
    308                 m_initial_scale = in_scale;
    309                 // Refresh
     294        // Load
     295            double pos_x = Double.valueOf( props.getProperty(POSITION_X));
     296            double pos_y = Double.valueOf( props.getProperty(POSITION_Y));
     297            double in_pos_x = Double.valueOf( props.getProperty(INITIAL_POS_X));
     298            double in_pos_y = Double.valueOf( props.getProperty(INITIAL_POS_Y));
     299            double angle = Double.valueOf( props.getProperty(ANGLE));
     300            double in_scale = Double.valueOf( props.getProperty(INITIAL_SCALE));
     301            double scale_x = Double.valueOf( props.getProperty(SCALEX));
     302            double scale_y = Double.valueOf( props.getProperty(SCALEY));
     303            m_position.setLocation(pos_x, pos_y);
     304            m_initial_position.setLocation(pos_x, pos_y);
     305            m_angle = angle;
     306            m_scalex = scale_x;
     307            m_scaley = scale_y;
     308            m_initial_scale = in_scale;
     309            // Refresh
    310310            Main.map.mapView.repaint();
    311311    }
     
    313313    private class ResetSubmenuAction extends AbstractAction implements LayerAction {
    314314
    315         public ResetSubmenuAction() {
    316                 super(tr("Reset"));
    317                 }
    318 
    319                 public void actionPerformed(ActionEvent e) {
    320                 }
    321 
    322                 public Component createMenuComponent() {
    323                         JMenu reset_submenu = new JMenu(this);
    324                 reset_submenu.add( new ResetPictureAllAction( PicLayerAbstract.this ) );
    325                 reset_submenu.addSeparator();
    326                 reset_submenu.add( new ResetPicturePositionAction( PicLayerAbstract.this ) );
    327                 reset_submenu.add( new ResetPictureAngleAction( PicLayerAbstract.this ) );
    328                 reset_submenu.add( new ResetPictureScaleAction( PicLayerAbstract.this ) );
    329                 return reset_submenu;
    330                 }
    331 
    332                 public boolean supportLayers(List<Layer> layers) {
    333                         return layers.size() == 1 && layers.get(0) instanceof PicLayerAbstract;
    334                 }
     315        public ResetSubmenuAction() {
     316            super(tr("Reset"));
     317        }
     318
     319        public void actionPerformed(ActionEvent e) {
     320        }
     321
     322        public Component createMenuComponent() {
     323            JMenu reset_submenu = new JMenu(this);
     324            reset_submenu.add( new ResetPictureAllAction( PicLayerAbstract.this ) );
     325            reset_submenu.addSeparator();
     326            reset_submenu.add( new ResetPicturePositionAction( PicLayerAbstract.this ) );
     327            reset_submenu.add( new ResetPictureAngleAction( PicLayerAbstract.this ) );
     328            reset_submenu.add( new ResetPictureScaleAction( PicLayerAbstract.this ) );
     329            return reset_submenu;
     330        }
     331
     332        public boolean supportLayers(List<Layer> layers) {
     333            return layers.size() == 1 && layers.get(0) instanceof PicLayerAbstract;
     334        }
    335335
    336336    }
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/PicLayerFromClipboard.java

    r20217 r23190  
    3535public class PicLayerFromClipboard extends PicLayerAbstract {
    3636
    37         @Override
    38         protected Image createImage() throws IOException {
    39                 // Return item
    40                 Image image = null;
    41                 // Access the clipboard
     37    @Override
     38    protected Image createImage() throws IOException {
     39        // Return item
     40        Image image = null;
     41        // Access the clipboard
    4242        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    4343        // Check result
    4444        if ( t == null ) {
    45                 throw new IOException(tr("Nothing in clipboard"));
     45            throw new IOException(tr("Nothing in clipboard"));
    4646        }
    47        
     47
    4848        // TODO: Why is it so slow?
    4949        // Try to make it an image data
     
    5252                image = (Image)t.getTransferData(DataFlavor.imageFlavor);
    5353            } else {
    54                 throw new IOException(tr("The clipboard data is not an image"));
     54                throw new IOException(tr("The clipboard data is not an image"));
    5555            }
    5656        } catch (UnsupportedFlavorException e) {
    57                 throw new IOException( e.getMessage() );
    58         } 
    59        
     57            throw new IOException( e.getMessage() );
     58        }
     59
    6060        return image;
    61         }
     61    }
    6262
    63         @Override
    64         protected String getPicLayerName() {
    65                 return "Clipboard";
    66         }
     63    @Override
     64    protected String getPicLayerName() {
     65        return "Clipboard";
     66    }
    6767
    6868}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/PicLayerFromFile.java

    r17327 r23190  
    3030 */
    3131public class PicLayerFromFile extends PicLayerAbstract {
    32        
    33         // File to load from.
    34         private File m_file;
    35         // Tooltip text
    36         private String m_tooltiptext;
     32
     33    // File to load from.
     34    private File m_file;
     35    // Tooltip text
     36    private String m_tooltiptext;
    3737
    3838    public PicLayerFromFile( File file ) {
    39         // Remember the file
    40         m_file = file;
    41         // Generate tooltip text
    42         m_tooltiptext = m_file.getAbsolutePath();
    43     }   
    44    
    45         @Override
    46         protected Image createImage() throws IOException {
     39        // Remember the file
     40        m_file = file;
     41        // Generate tooltip text
     42        m_tooltiptext = m_file.getAbsolutePath();
     43    }
     44
     45    @Override
     46    protected Image createImage() throws IOException {
    4747        // Try to load file
    48                 Image image = null;
    49                 image = ImageIO.read( m_file );
    50                 return image;
    51         }
     48        Image image = null;
     49        image = ImageIO.read( m_file );
     50        return image;
     51    }
    5252
    53         @Override
    54         protected String getPicLayerName() {
    55                 return m_tooltiptext;
    56         }       
     53    @Override
     54    protected String getPicLayerName() {
     55        return m_tooltiptext;
     56    }
    5757}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/PicLayerPlugin.java

    r20217 r23190  
    5959     */
    6060    public PicLayerPlugin(PluginInformation info) {
    61         super(info);
    62        
     61        super(info);
     62
    6363        // Create menu entry
    6464        if ( Main.main.menu != null ) {
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/ResetPictureAllAction.java

    r20217 r23190  
    3535public class ResetPictureAllAction extends JosmAction {
    3636
    37         // Owner layer of the action
    38         PicLayerAbstract m_owner = null;
    39        
    40         /**
    41         * Constructor
    42         */
    43         public ResetPictureAllAction( PicLayerAbstract owner ) {
    44                 super(tr("All"), null, tr("Resets picture calibration"), null, false);
    45                 // Remember the owner...
    46                 m_owner = owner;
    47         }
    48        
    49         /**
    50         * Action handler
    51         */
    52         public void actionPerformed(ActionEvent arg0) {
    53                 // Reset
    54                 m_owner.resetAngle();
    55                 m_owner.resetPosition();
    56                 m_owner.resetScale();
    57                 // Redraw
     37    // Owner layer of the action
     38    PicLayerAbstract m_owner = null;
     39   
     40    /**
     41    * Constructor
     42    */
     43    public ResetPictureAllAction( PicLayerAbstract owner ) {
     44        super(tr("All"), null, tr("Resets picture calibration"), null, false);
     45        // Remember the owner...
     46        m_owner = owner;
     47    }
     48   
     49    /**
     50    * Action handler
     51    */
     52    public void actionPerformed(ActionEvent arg0) {
     53        // Reset
     54        m_owner.resetAngle();
     55        m_owner.resetPosition();
     56        m_owner.resetScale();
     57        // Redraw
    5858        Main.map.mapView.repaint();
    59         }
     59    }
    6060}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/ResetPictureAngleAction.java

    r20217 r23190  
    3535public class ResetPictureAngleAction extends JosmAction {
    3636
    37         // Owner layer of the action
    38         PicLayerAbstract m_owner = null;
    39        
    40         /**
    41         * Constructor
    42         */
    43         public ResetPictureAngleAction( PicLayerAbstract owner ) {
    44                 super(tr("Angle"), null, tr("Resets picture rotation"), null, false);
    45                 // Remember the owner...
    46                 m_owner = owner;
    47         }
    48        
    49         /**
    50         * Action handler
    51         */
    52         public void actionPerformed(ActionEvent arg0) {
    53                 // Reset
    54                 m_owner.resetAngle();
    55                 // Redraw
     37    // Owner layer of the action
     38    PicLayerAbstract m_owner = null;
     39   
     40    /**
     41    * Constructor
     42    */
     43    public ResetPictureAngleAction( PicLayerAbstract owner ) {
     44        super(tr("Angle"), null, tr("Resets picture rotation"), null, false);
     45        // Remember the owner...
     46        m_owner = owner;
     47    }
     48   
     49    /**
     50    * Action handler
     51    */
     52    public void actionPerformed(ActionEvent arg0) {
     53        // Reset
     54        m_owner.resetAngle();
     55        // Redraw
    5656        Main.map.mapView.repaint();
    57         }
     57    }
    5858}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/ResetPicturePositionAction.java

    r20217 r23190  
    3535public class ResetPicturePositionAction extends JosmAction {
    3636
    37         // Owner layer of the action
    38         PicLayerAbstract m_owner = null;
    39        
    40         /**
    41         * Constructor
    42         */
    43         public ResetPicturePositionAction( PicLayerAbstract owner ) {
    44                 super(tr("Reset position"), null, tr("Resets picture position"), null, false);
    45                 // Remember the owner...
    46                 m_owner = owner;
    47         }
    48        
    49         /**
    50         * Action handler
    51         */
    52         public void actionPerformed(ActionEvent arg0) {
    53                 // Reset
    54                 m_owner.resetPosition();
    55                 // Redraw
     37    // Owner layer of the action
     38    PicLayerAbstract m_owner = null;
     39   
     40    /**
     41    * Constructor
     42    */
     43    public ResetPicturePositionAction( PicLayerAbstract owner ) {
     44        super(tr("Reset position"), null, tr("Resets picture position"), null, false);
     45        // Remember the owner...
     46        m_owner = owner;
     47    }
     48   
     49    /**
     50    * Action handler
     51    */
     52    public void actionPerformed(ActionEvent arg0) {
     53        // Reset
     54        m_owner.resetPosition();
     55        // Redraw
    5656        Main.map.mapView.repaint();
    57         }
     57    }
    5858}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/ResetPictureScaleAction.java

    r20217 r23190  
    3535public class ResetPictureScaleAction extends JosmAction {
    3636
    37         // Owner layer of the action
    38         PicLayerAbstract m_owner = null;
    39        
    40         /**
    41         * Constructor
    42         */
    43         public ResetPictureScaleAction( PicLayerAbstract owner ) {
    44                 super(tr("Scale"), null, tr("Resets picture scale"), null, false);
    45                 // Remember the owner...
    46                 m_owner = owner;
    47         }
    48        
    49         /**
    50         * Action handler
    51         */
    52         public void actionPerformed(ActionEvent arg0) {
    53                 // Reset
    54                 m_owner.resetScale();
    55                 // Redraw
     37    // Owner layer of the action
     38    PicLayerAbstract m_owner = null;
     39   
     40    /**
     41    * Constructor
     42    */
     43    public ResetPictureScaleAction( PicLayerAbstract owner ) {
     44        super(tr("Scale"), null, tr("Resets picture scale"), null, false);
     45        // Remember the owner...
     46        m_owner = owner;
     47    }
     48   
     49    /**
     50    * Action handler
     51    */
     52    public void actionPerformed(ActionEvent arg0) {
     53        // Reset
     54        m_owner.resetScale();
     55        // Redraw
    5656        Main.map.mapView.repaint();
    57         }
     57    }
    5858}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/RotatePictureAction.java

    r20217 r23190  
    3737 * This class handles the input during rotating the picture.
    3838 */
    39 public class RotatePictureAction extends MapMode implements MouseListener, MouseMotionListener 
     39public class RotatePictureAction extends MapMode implements MouseListener, MouseMotionListener
    4040{
    41         // Action ongoing?
    42         private boolean mb_dragging = false;
    43        
    44         // Last mouse position
    45         private int m_prevY;
    46        
    47         // Layer we're working on
    48         private PicLayerAbstract m_currentLayer = null;
    49        
    50         /**
    51          * Constructor
    52          */
    53         public RotatePictureAction(MapFrame frame) {
    54                 super(tr("PicLayer rotate"), "rotate", tr("Drag to rotate the picture"), frame, ImageProvider.getCursor("crosshair", null));
    55                 // TODO Auto-generated constructor stub
    56         }
     41    // Action ongoing?
     42    private boolean mb_dragging = false;
    5743
    58     @Override
     44    // Last mouse position
     45    private int m_prevY;
     46
     47    // Layer we're working on
     48    private PicLayerAbstract m_currentLayer = null;
     49
     50    /**
     51     * Constructor
     52     */
     53    public RotatePictureAction(MapFrame frame) {
     54        super(tr("PicLayer rotate"), "rotate", tr("Drag to rotate the picture"), frame, ImageProvider.getCursor("crosshair", null));
     55        // TODO Auto-generated constructor stub
     56    }
     57
     58    @Override
    5959    public void enterMode() {
    6060        super.enterMode();
     
    6363    }
    6464
    65     @Override 
     65    @Override
    6666    public void exitMode() {
    6767        super.exitMode();
    6868        Main.map.mapView.removeMouseListener(this);
    6969        Main.map.mapView.removeMouseMotionListener(this);
    70     }   
    71        
    72     @Override 
     70    }
     71
     72    @Override
    7373    public void mousePressed(MouseEvent e) {
    74         // Start rotating
    75         if ( Main.map.mapView.getActiveLayer() instanceof PicLayerAbstract ) {
    76                 m_currentLayer = (PicLayerAbstract)Main.map.mapView.getActiveLayer();
    77                
    78                 if ( m_currentLayer != null && e.getButton() == MouseEvent.BUTTON1 ) {
    79                         mb_dragging = true;
    80                         m_prevY=e.getY();
    81                 }
    82         }
    83     }   
    84    
    85     @Override 
     74        // Start rotating
     75        if ( Main.map.mapView.getActiveLayer() instanceof PicLayerAbstract ) {
     76            m_currentLayer = (PicLayerAbstract)Main.map.mapView.getActiveLayer();
     77
     78            if ( m_currentLayer != null && e.getButton() == MouseEvent.BUTTON1 ) {
     79                mb_dragging = true;
     80                m_prevY=e.getY();
     81            }
     82        }
     83    }
     84
     85    @Override
    8686    public void mouseDragged(MouseEvent e) {
    87         // Rotate the picture
     87        // Rotate the picture
    8888        if(mb_dragging) {
    8989            // TODO: Magic number
     
    9292            Main.map.mapView.repaint();
    9393        }
    94     }   
    95    
     94    }
     95
    9696    @Override public void mouseReleased(MouseEvent e) {
    97         // End rotating
    98         mb_dragging = false;
    99     }   
     97        // End rotating
     98        mb_dragging = false;
     99    }
    100100
    101101}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/SavePictureCalibrationAction.java

    r20217 r23190  
    4343public class SavePictureCalibrationAction extends JosmAction {
    4444
    45         // Owner layer of the action
    46         PicLayerAbstract m_owner = null;
    47        
    48         /**
    49         * Constructor
    50         */
    51         public SavePictureCalibrationAction( PicLayerAbstract owner ) {
    52                 super(tr("Save Picture Calibration..."), null, tr("Saves calibration data to a file"), null, false);
    53                 // Remember the owner...
    54                 m_owner = owner;
    55         }
    56        
    57         /**
    58         * Action handler
    59         */
    60         public void actionPerformed(ActionEvent arg0) {
    61                 // Save dialog
    62                 final JFileChooser fc = new JFileChooser();
    63                 fc.setAcceptAllFileFilterUsed( false );
    64                 fc.setFileFilter( new CalibrationFileFilter() );
    65                 fc.setSelectedFile( new File(m_owner.getPicLayerName() + CalibrationFileFilter.EXTENSION));
    66                 int result = fc.showSaveDialog( Main.parent );
     45    // Owner layer of the action
     46    PicLayerAbstract m_owner = null;
     47   
     48    /**
     49    * Constructor
     50    */
     51    public SavePictureCalibrationAction( PicLayerAbstract owner ) {
     52        super(tr("Save Picture Calibration..."), null, tr("Saves calibration data to a file"), null, false);
     53        // Remember the owner...
     54        m_owner = owner;
     55    }
     56   
     57    /**
     58    * Action handler
     59    */
     60    public void actionPerformed(ActionEvent arg0) {
     61        // Save dialog
     62        final JFileChooser fc = new JFileChooser();
     63        fc.setAcceptAllFileFilterUsed( false );
     64        fc.setFileFilter( new CalibrationFileFilter() );
     65        fc.setSelectedFile( new File(m_owner.getPicLayerName() + CalibrationFileFilter.EXTENSION));
     66        int result = fc.showSaveDialog( Main.parent );
    6767
    68                 if ( result == JFileChooser.APPROVE_OPTION ) {
    69                         // Check file extension and force it to be valid
    70                         File file = fc.getSelectedFile();
    71                         String path = file.getAbsolutePath();
    72                         if ( path.length() < CalibrationFileFilter.EXTENSION.length()
    73                                 || !path.substring( path.length() - 4 ).equals(CalibrationFileFilter.EXTENSION)) {
    74                                 file = new File( path + CalibrationFileFilter.EXTENSION );
    75                         }
    76                                                
    77                         // Save
    78                         Properties props = new Properties();
    79                         m_owner.saveCalibration(props);
    80                         try {
    81                                 props.store(new FileOutputStream(file), tr("JOSM PicLayer plugin calibration data"));
    82                         } catch (Exception e) {
    83                                 // Error
    84                                 e.printStackTrace();
    85                                 JOptionPane.showMessageDialog(Main.parent , tr("Saving file failed: {0}", e.getMessage()));
    86                         }
    87                 }       
    88         }
     68        if ( result == JFileChooser.APPROVE_OPTION ) {
     69            // Check file extension and force it to be valid
     70            File file = fc.getSelectedFile();
     71            String path = file.getAbsolutePath();
     72            if ( path.length() < CalibrationFileFilter.EXTENSION.length()
     73                || !path.substring( path.length() - 4 ).equals(CalibrationFileFilter.EXTENSION)) {
     74                file = new File( path + CalibrationFileFilter.EXTENSION );
     75            }
     76                       
     77            // Save
     78            Properties props = new Properties();
     79            m_owner.saveCalibration(props);
     80            try {
     81                props.store(new FileOutputStream(file), tr("JOSM PicLayer plugin calibration data"));
     82            } catch (Exception e) {
     83                // Error
     84                e.printStackTrace();
     85                JOptionPane.showMessageDialog(Main.parent , tr("Saving file failed: {0}", e.getMessage()));
     86            }
     87        }   
     88    }
    8989}
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/ScalePictureActionAbstract.java

    r17321 r23190  
    3535 * This class handles the input during scaling the picture.
    3636 */
    37 public abstract class ScalePictureActionAbstract extends MapMode implements MouseListener, MouseMotionListener 
     37public abstract class ScalePictureActionAbstract extends MapMode implements MouseListener, MouseMotionListener
    3838{
    39         // Scaling ongoing?
    40         private boolean mb_dragging = false;
    41        
    42         // Last mouse position
    43         private int m_prevY;
    44        
    45         // Layer we're working on
    46         protected PicLayerAbstract m_currentLayer = null;
    47        
    48         /**
    49          * Constructor
    50          */
    51         public ScalePictureActionAbstract (String name, String icon, String tooltip, MapFrame frame) {
    52                 super(name, icon, tooltip, frame, ImageProvider.getCursor("crosshair", null));
    53                 // TODO Auto-generated constructor stub
    54         }
     39    // Scaling ongoing?
     40    private boolean mb_dragging = false;
    5541
    56     @Override
     42    // Last mouse position
     43    private int m_prevY;
     44
     45    // Layer we're working on
     46    protected PicLayerAbstract m_currentLayer = null;
     47
     48    /**
     49     * Constructor
     50     */
     51    public ScalePictureActionAbstract (String name, String icon, String tooltip, MapFrame frame) {
     52        super(name, icon, tooltip, frame, ImageProvider.getCursor("crosshair", null));
     53        // TODO Auto-generated constructor stub
     54    }
     55
     56    @Override
    5757    public void enterMode() {
    5858        super.enterMode();
     
    6161    }
    6262
    63     @Override 
     63    @Override
    6464    public void exitMode() {
    6565        super.exitMode();
    6666        Main.map.mapView.removeMouseListener(this);
    6767        Main.map.mapView.removeMouseMotionListener(this);
    68     }   
    69        
    70     @Override 
     68    }
     69
     70    @Override
    7171    public void mousePressed(MouseEvent e) {
    72         // Start scaling
    73         if ( Main.map.mapView.getActiveLayer() instanceof PicLayerAbstract ) {
    74                 m_currentLayer = (PicLayerAbstract)Main.map.mapView.getActiveLayer();
    75                
    76                 if ( m_currentLayer != null && e.getButton() == MouseEvent.BUTTON1 ) {
    77                         mb_dragging = true;
    78                         m_prevY = e.getY();
    79                 }
    80         }
    81     }   
    82    
    83     @Override 
     72        // Start scaling
     73        if ( Main.map.mapView.getActiveLayer() instanceof PicLayerAbstract ) {
     74            m_currentLayer = (PicLayerAbstract)Main.map.mapView.getActiveLayer();
     75
     76            if ( m_currentLayer != null && e.getButton() == MouseEvent.BUTTON1 ) {
     77                mb_dragging = true;
     78                m_prevY = e.getY();
     79            }
     80        }
     81    }
     82
     83    @Override
    8484    public void mouseDragged(MouseEvent e) {
    85         // Scale the picture
     85        // Scale the picture
    8686        if(mb_dragging) {
    8787            doTheScale( ( e.getY() - m_prevY ) / 500.0 );
     
    9090        }
    9191    }
    92    
    93     @Override 
     92
     93    @Override
    9494    public void mouseReleased(MouseEvent e) {
    95         // Stop scaling
    96         mb_dragging = false;
     95        // Stop scaling
     96        mb_dragging = false;
    9797    }
    98    
     98
    9999    /**
    100100    * Does the actual scaling in the inherited class.
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/ScaleXPictureAction.java

    r20217 r23190  
    3333 * This class handles the input during scaling the picture.
    3434 */
    35 public class ScaleXPictureAction extends ScalePictureActionAbstract 
     35public class ScaleXPictureAction extends ScalePictureActionAbstract
    3636{
    37         /*
    38         * Constructor
    39         */
    40         public ScaleXPictureAction(MapFrame frame) {
    41                 super(tr("PicLayer scale X"), "scale_x", tr("Drag to scale the picture in the X Axis"), frame);
    42                 // TODO Auto-generated constructor stub
    43         }
     37    /*
     38    * Constructor
     39    */
     40    public ScaleXPictureAction(MapFrame frame) {
     41        super(tr("PicLayer scale X"), "scale_x", tr("Drag to scale the picture in the X Axis"), frame);
     42        // TODO Auto-generated constructor stub
     43    }
    4444
    45         public void doTheScale( double scale ) {
     45    public void doTheScale( double scale ) {
    4646            m_currentLayer.scalePictureBy( scale, 0.0 );
    4747        }
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/ScaleXYPictureAction.java

    r20217 r23190  
    3333 * This class handles the input during scaling the picture.
    3434 */
    35 public class ScaleXYPictureAction extends ScalePictureActionAbstract 
     35public class ScaleXYPictureAction extends ScalePictureActionAbstract
    3636{
    37         /*
    38         * Constructor
    39         */
    40         public ScaleXYPictureAction(MapFrame frame) {
    41                 super(tr("PicLayer scale"), "scale", tr("Drag to scale the picture in the X and Y Axis"), frame);
    42                 // TODO Auto-generated constructor stub
    43         }
     37    /*
     38    * Constructor
     39    */
     40    public ScaleXYPictureAction(MapFrame frame) {
     41        super(tr("PicLayer scale"), "scale", tr("Drag to scale the picture in the X and Y Axis"), frame);
     42        // TODO Auto-generated constructor stub
     43    }
    4444
    45         public void doTheScale( double scale ) {
     45    public void doTheScale( double scale ) {
    4646            m_currentLayer.scalePictureBy( scale, scale );
    4747        }
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/ScaleYPictureAction.java

    r20217 r23190  
    3333 * This class handles the input during scaling the picture.
    3434 */
    35 public class ScaleYPictureAction extends ScalePictureActionAbstract 
     35public class ScaleYPictureAction extends ScalePictureActionAbstract
    3636{
    37         /*
    38         * Constructor
    39         */
    40         public ScaleYPictureAction(MapFrame frame) {
    41                 super(tr("PicLayer scale Y"), "scale_y", tr("Drag to scale the picture in the Y Axis"), frame);
    42                 // TODO Auto-generated constructor stub
    43         }
     37    /*
     38    * Constructor
     39    */
     40    public ScaleYPictureAction(MapFrame frame) {
     41        super(tr("PicLayer scale Y"), "scale_y", tr("Drag to scale the picture in the Y Axis"), frame);
     42        // TODO Auto-generated constructor stub
     43    }
    4444
    45         public void doTheScale( double scale ) {
     45    public void doTheScale( double scale ) {
    4646            m_currentLayer.scalePictureBy( 0.0, scale );
    4747        }
  • applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapKey.java

    r16161 r23190  
    11/**
    2  * 
     2 *
    33 */
    44package org.openstreetmap.josm.plugins.slippymap;
     
    99 * {@link #equals(Object)} and also {@link #toString()}.
    1010 * </p>
    11  * 
     11 *
    1212 * @author LuVar <lubomir.varga@freemap.sk>
    1313 * @author Dave Hansen <dave@sr71.net>
     
    1515 */
    1616public class SlippyMapKey {
    17         private final int x;
    18         private final int y;
    19         private final int level;
    20        
    21         /**
    22         * <p>
    23         * Constructs key for hashmaps for some tile describedy by X and Y position. X and Y are tiles
    24         * positions on discrete map.
    25         * </p>
    26          *
    27          * @param x     x position in tiles table
    28          * @param y     y position in tiles table
    29         */
    30         public final boolean valid;
    31         public SlippyMapKey(int x, int y, int level) {
    32                 this.x = x;
    33                 this.y = y;
    34                 this.level = level;
    35                 if (level <= 0 || x < 0 || y < 0) {
    36                         this.valid = false;
    37                         System.err.println("invalid SlippyMapKey("+level+", "+x+", "+y+")");
    38                 } else {
    39                         this.valid = true;
    40                 }
    41         }
    42        
    43         /**
    44         * <p>
    45         * Returns true ONLY if x and y are equals.
    46         * </p>
    47          *
    48         * @see java.lang.Object#equals(java.lang.Object)
    49         */
    50         @Override
    51         public boolean equals(Object obj) {
    52                 if (obj instanceof SlippyMapKey) {
    53                         SlippyMapKey smk = (SlippyMapKey) obj;
    54                         if((smk.x == this.x) && (smk.y == this.y) && (smk.level == this.level)) {
    55                                 return true;
    56                         }
    57                 }
    58                 return false;
    59         }
    60        
    61         /**
    62          * @return      return new Integer(this.x + this.y * 10000).hashCode();
    63         * @see java.lang.Object#hashCode()
    64         */
    65         @Override
    66         public int hashCode() {
    67                 return new Integer(this.x + this.y * 10000 + this.level * 100000).hashCode();
    68         }
    69        
    70         /**
    71         * @see java.lang.Object#toString()
    72         */
    73         @Override
    74         public String toString() {
    75                 return "SlippyMapKey(x=" + this.x + ",y=" + this.y + ",level=" + level + ")";
    76         }
    77        
     17    private final int x;
     18    private final int y;
     19    private final int level;
     20
     21    /**
     22    * <p>
     23    * Constructs key for hashmaps for some tile describedy by X and Y position. X and Y are tiles
     24    * positions on discrete map.
     25    * </p>
     26     *
     27     * @param x x position in tiles table
     28     * @param y y position in tiles table
     29    */
     30    public final boolean valid;
     31    public SlippyMapKey(int x, int y, int level) {
     32        this.x = x;
     33        this.y = y;
     34        this.level = level;
     35        if (level <= 0 || x < 0 || y < 0) {
     36            this.valid = false;
     37            System.err.println("invalid SlippyMapKey("+level+", "+x+", "+y+")");
     38        } else {
     39            this.valid = true;
     40        }
     41    }
     42
     43    /**
     44    * <p>
     45    * Returns true ONLY if x and y are equals.
     46    * </p>
     47     *
     48    * @see java.lang.Object#equals(java.lang.Object)
     49    */
     50    @Override
     51    public boolean equals(Object obj) {
     52        if (obj instanceof SlippyMapKey) {
     53            SlippyMapKey smk = (SlippyMapKey) obj;
     54            if((smk.x == this.x) && (smk.y == this.y) && (smk.level == this.level)) {
     55                return true;
     56            }
     57        }
     58        return false;
     59    }
     60
     61    /**
     62     * @return  return new Integer(this.x + this.y * 10000).hashCode();
     63    * @see java.lang.Object#hashCode()
     64    */
     65    @Override
     66    public int hashCode() {
     67        return new Integer(this.x + this.y * 10000 + this.level * 100000).hashCode();
     68    }
     69
     70    /**
     71    * @see java.lang.Object#toString()
     72    */
     73    @Override
     74    public String toString() {
     75        return "SlippyMapKey(x=" + this.x + ",y=" + this.y + ",level=" + level + ")";
     76    }
     77
    7878}
  • applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapLayer.java

    r22848 r23190  
    212212        // FIXME: currently ran in errors
    213213
    214                 tileOptionMenu.add(new JMenuItem(
     214        tileOptionMenu.add(new JMenuItem(
    215215                new AbstractAction(tr("Snap to tile size")) {
    216216                    public void actionPerformed(ActionEvent ae) {
     
    252252                MapView.addLayerChangeListener(new LayerChangeListener() {
    253253                    public void activeLayerChange(Layer oldLayer, Layer newLayer) {
    254                         //
     254                        //
    255255                    }
    256256
    257257                    public void layerAdded(Layer newLayer) {
    258                         //
     258                        //
    259259                    }
    260260
    261261                    public void layerRemoved(Layer oldLayer) {
    262                         MapView.removeLayerChangeListener(this);
     262                        MapView.removeLayerChangeListener(this);
    263263                    }
    264264                });
  • applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapPlugin.java

    r22848 r23190  
    2121    public SlippyMapPlugin(PluginInformation info)
    2222    {
    23         super(info);
    24         Main.pref.addPreferenceChangeListener(this);
     23        super(info);
     24        Main.pref.addPreferenceChangeListener(this);
    2525    }
    2626
    2727    @Override
    28         public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame)
     28    public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame)
    2929    {
    3030        if (newFrame != null && SlippyMapPreferences.getMapSource() != SlippyMapPreferences.NO_DEFAULT_TILE_SOURCE) {
     
    5353     */
    5454    public void preferenceChanged(PreferenceChangeEvent event) {
    55         if (!Main.isDisplayingMapView()) {
    56                 return;
    57         }
    58         List<SlippyMapLayer> layes = Main.map.mapView.getLayersOfType(SlippyMapLayer.class);
    59         assert layes.size() <= 1;
    60         SlippyMapLayer layer = layes.isEmpty()?null:layes.get(0);
     55        if (!Main.isDisplayingMapView()) {
     56            return;
     57        }
     58        List<SlippyMapLayer> layes = Main.map.mapView.getLayersOfType(SlippyMapLayer.class);
     59        assert layes.size() <= 1;
     60        SlippyMapLayer layer = layes.isEmpty()?null:layes.get(0);
    6161
    6262        if (event.getKey().equals(SlippyMapPreferences.PREFERENCE_TILE_SOURCE)) {
    63                 if (layer == null && SlippyMapPreferences.getMapSource() != SlippyMapPreferences.NO_DEFAULT_TILE_SOURCE) {
    64                         Main.map.mapView.addLayer(new SlippyMapLayer());
    65                 } else if (layer != null && SlippyMapPreferences.getMapSource() == SlippyMapPreferences.NO_DEFAULT_TILE_SOURCE) {
    66                         Main.map.mapView.removeLayer(layer);
    67                 } else if (layer == null && SlippyMapPreferences.getMapSource() == SlippyMapPreferences.NO_DEFAULT_TILE_SOURCE) {
    68                         // Do nothing
    69                 } else {
    70                         layer.newTileStorage();
    71                 }
     63            if (layer == null && SlippyMapPreferences.getMapSource() != SlippyMapPreferences.NO_DEFAULT_TILE_SOURCE) {
     64                Main.map.mapView.addLayer(new SlippyMapLayer());
     65            } else if (layer != null && SlippyMapPreferences.getMapSource() == SlippyMapPreferences.NO_DEFAULT_TILE_SOURCE) {
     66                Main.map.mapView.removeLayer(layer);
     67            } else if (layer == null && SlippyMapPreferences.getMapSource() == SlippyMapPreferences.NO_DEFAULT_TILE_SOURCE) {
     68                // Do nothing
     69            } else {
     70                layer.newTileStorage();
     71            }
    7272        } else  if (event.getKey().startsWith(SlippyMapPreferences.PREFERENCE_PREFIX) && layer != null) {
    7373            // System.err.println(this + ".preferenceChanged('" + key + "', '"
  • applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapPreferenceSetting.java

    r22848 r23190  
    114114     * Actualy this method loads and sets this params:<br>
    115115     * <ul>
    116      *  <li>autozoom - {@link #autozoomActive} - {@link SlippyMapPreferences#getAutozoom()}</li>
    117      *  <li>autoload - {@link #autoloadTiles} - {@link SlippyMapPreferences#getAutoloadTiles()}</li>
    118      *  <li>maxZoomLvl - {@link #maxZoomLvl} - {@link SlippyMapPreferences#getMaxZoomLvl()}</li>
    119      *  <li>minZoomLvl - {@link #minZoomLvl} - {@link SlippyMapPreferences#getMaxZoomLvl()}</li>
     116     *  <li>autozoom - {@link #autozoomActive} - {@link SlippyMapPreferences#getAutozoom()}</li>
     117     *  <li>autoload - {@link #autoloadTiles} - {@link SlippyMapPreferences#getAutoloadTiles()}</li>
     118     *  <li>maxZoomLvl - {@link #maxZoomLvl} - {@link SlippyMapPreferences#getMaxZoomLvl()}</li>
     119     *  <li>minZoomLvl - {@link #minZoomLvl} - {@link SlippyMapPreferences#getMaxZoomLvl()}</li>
    120120     * </ul>
    121121     * </p>
     
    139139    public boolean ok()
    140140    {
    141         SlippyMapPreferences.setMapSource((TileSource)this.tileSourceCombo.getSelectedItem());
     141        SlippyMapPreferences.setMapSource((TileSource)this.tileSourceCombo.getSelectedItem());
    142142        SlippyMapPreferences.setAutozoom(this.autozoomActive.isSelected());
    143143        SlippyMapPreferences.setAutoloadTiles(this.autoloadTiles.isSelected());
  • applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapPreferences.java

    r22848 r23190  
    2121public class SlippyMapPreferences
    2222{
    23         public static final String NO_DEFAULT_TILE_SOURCE_NAME = "{%no_default%}";
     23    public static final String NO_DEFAULT_TILE_SOURCE_NAME = "{%no_default%}";
    2424    public static final String PREFERENCE_PREFIX   = "slippymap";
    2525
     
    4747    public static TileSource getMapSource(String name)
    4848    {
    49         if (NO_DEFAULT_TILE_SOURCE_NAME.equals(name)) {
    50                 return NO_DEFAULT_TILE_SOURCE; // User don't want to load slippy layer on startup
    51         }
     49        if (NO_DEFAULT_TILE_SOURCE_NAME.equals(name)) {
     50            return NO_DEFAULT_TILE_SOURCE; // User don't want to load slippy layer on startup
     51        }
    5252
    5353        List<TileSource> sources = SlippyMapPreferences.getAllMapSources();
     
    6060        for (TileSource s : sources) {
    6161            if (name.equals(s.getName()))
    62                 return s;
     62                return s;
    6363        }
    6464
     
    6767
    6868    public static void setMapSource(TileSource source) {
    69         Main.pref.put(SlippyMapPreferences.PREFERENCE_TILE_SOURCE, source == NO_DEFAULT_TILE_SOURCE?NO_DEFAULT_TILE_SOURCE_NAME:source.getName());
     69        Main.pref.put(SlippyMapPreferences.PREFERENCE_TILE_SOURCE, source == NO_DEFAULT_TILE_SOURCE?NO_DEFAULT_TILE_SOURCE_NAME:source.getName());
    7070    }
    7171
     
    7676        if (autozoom == null || "".equals(autozoom))
    7777        {
    78                 autozoom = "true";
     78            autozoom = "true";
    7979            Main.pref.put(PREFERENCE_AUTOZOOM, autozoom);
    8080        }
     
    8484
    8585    public static void setAutozoom(boolean autozoom) {
    86         Main.pref.put(SlippyMapPreferences.PREFERENCE_AUTOZOOM, autozoom);
     86        Main.pref.put(SlippyMapPreferences.PREFERENCE_AUTOZOOM, autozoom);
    8787    }
    8888
    8989    public static void setDrawDebug(boolean drawDebug) {
    90         Main.pref.put(SlippyMapPreferences.PREFERENCE_DRAW_DEBUG, drawDebug);
     90        Main.pref.put(SlippyMapPreferences.PREFERENCE_DRAW_DEBUG, drawDebug);
    9191    }
    9292
    9393    public static void setLastZoom(int zoom) {
    94         Main.pref.put(SlippyMapPreferences.PREFERENCE_LAST_ZOOM, ""+zoom);
     94        Main.pref.put(SlippyMapPreferences.PREFERENCE_LAST_ZOOM, ""+zoom);
    9595    }
    9696    public static int getLastZoom() {
    97         int ret = -1;
     97        int ret = -1;
    9898        String pref = Main.pref.get(SlippyMapPreferences.PREFERENCE_LAST_ZOOM);
    9999        try {
     
    110110        if (drawDebug == null || "".equals(drawDebug))
    111111        {
    112                 drawDebug = "false";
     112            drawDebug = "false";
    113113            Main.pref.put(PREFERENCE_DRAW_DEBUG, drawDebug);
    114114        }
     
    123123        if (autoloadTiles == null || "".equals(autoloadTiles))
    124124        {
    125                 autoloadTiles = "true";
     125            autoloadTiles = "true";
    126126            Main.pref.put(PREFERENCE_AUTOLOADTILES, autoloadTiles);
    127127        }
     
    131131
    132132    public static void setFadeBackground(float fadeBackground) {
    133         Main.pref.put(SlippyMapPreferences.PREFERENCE_FADE_BACKGROUND, fadeBackground + "");
     133        Main.pref.put(SlippyMapPreferences.PREFERENCE_FADE_BACKGROUND, fadeBackground + "");
    134134    }
    135135
    136136    /**
    137137     *
    138      * @return  number between 0 and 1, inclusive
     138     * @return  number between 0 and 1, inclusive
    139139     */
    140140    public static float getFadeBackground() {
     
    143143        if (fadeBackground == null || "".equals(fadeBackground))
    144144        {
    145                 fadeBackground = "0.0";
     145            fadeBackground = "0.0";
    146146            Main.pref.put(PREFERENCE_FADE_BACKGROUND, fadeBackground);
    147147        }
     
    149149        float parsed;
    150150        try {
    151                 parsed = Float.parseFloat(fadeBackground);
     151            parsed = Float.parseFloat(fadeBackground);
    152152        } catch (Exception ex) {
    153                 setFadeBackground(0.1f);
    154                 System.out.println("Error while parsing setting fade background to float! returning 0.1, because of error:");
    155                 ex.printStackTrace(System.out);
    156                 return 0.1f;
     153            setFadeBackground(0.1f);
     154            System.out.println("Error while parsing setting fade background to float! returning 0.1, because of error:");
     155            ex.printStackTrace(System.out);
     156            return 0.1f;
    157157        }
    158158        if(parsed < 0f) {
    159                 parsed = 0f;
     159            parsed = 0f;
    160160        } else {
    161                 if(parsed > 1f) {
    162                 parsed = 1f;
     161            if(parsed > 1f) {
     162                parsed = 1f;
    163163            }
    164164        }
     
    167167
    168168    public static void setAutoloadTiles(boolean autoloadTiles) {
    169         Main.pref.put(SlippyMapPreferences.PREFERENCE_AUTOLOADTILES, autoloadTiles);
     169        Main.pref.put(SlippyMapPreferences.PREFERENCE_AUTOLOADTILES, autoloadTiles);
    170170    }
    171171
     
    174174        int pref;
    175175        try {
    176                 //Should we use Main.pref.getInteger(str)?
    177                 pref = Main.pref.getInteger(prefName, def);
     176            //Should we use Main.pref.getInteger(str)?
     177            pref = Main.pref.getInteger(prefName, def);
    178178        } catch (Exception ex) {
    179179            String str = Main.pref.get(prefName);
    180180            Main.pref.put(prefName, null);
    181                 throw new RuntimeException("Problem while converting string to int. "
     181            throw new RuntimeException("Problem while converting string to int. "
    182182                                       + "Converting value of preferences "
    183183                                       + prefName + ". Value=\"" + str
     
    190190    static int checkMaxZoomLvl(int maxZoomLvl)
    191191    {
    192         if(maxZoomLvl > MAX_ZOOM) {
    193                 System.err.println("MaxZoomLvl shouldnt be more than 30! Setting to 30.");
    194                 maxZoomLvl = MAX_ZOOM;
    195         }
    196         if(maxZoomLvl < SlippyMapPreferences.__getMinZoomLvl()) {
    197                 System.err.println("maxZoomLvl shouldnt be more than minZoomLvl! Setting to minZoomLvl.");
    198                 maxZoomLvl = SlippyMapPreferences.__getMinZoomLvl();
    199         }
     192        if(maxZoomLvl > MAX_ZOOM) {
     193            System.err.println("MaxZoomLvl shouldnt be more than 30! Setting to 30.");
     194            maxZoomLvl = MAX_ZOOM;
     195        }
     196        if(maxZoomLvl < SlippyMapPreferences.__getMinZoomLvl()) {
     197            System.err.println("maxZoomLvl shouldnt be more than minZoomLvl! Setting to minZoomLvl.");
     198            maxZoomLvl = SlippyMapPreferences.__getMinZoomLvl();
     199        }
    200200        TileSource ts = getMapSource();
    201201        if (ts != null && ts.getMaxZoom() < SlippyMapPreferences.__getMinZoomLvl()) {
    202                 System.err.println("decreasing maxZoomLvl to match new tile source");
     202            System.err.println("decreasing maxZoomLvl to match new tile source");
    203203            maxZoomLvl = ts.getMaxZoom();
    204204        }
     
    214214    public static void setMaxZoomLvl(int maxZoomLvl) {
    215215        maxZoomLvl = checkMaxZoomLvl(maxZoomLvl);
    216         Main.pref.put(SlippyMapPreferences.PREFERENCE_MAX_ZOOM_LVL, "" + maxZoomLvl);
     216        Main.pref.put(SlippyMapPreferences.PREFERENCE_MAX_ZOOM_LVL, "" + maxZoomLvl);
    217217    }
    218218
     
    220220    {
    221221        if(minZoomLvl < MIN_ZOOM) {
    222                 System.err.println("minZoomLvl shouldnt be lees than "+MIN_ZOOM+"! Setting to that.");
    223                 minZoomLvl = MIN_ZOOM;
    224         }
    225         if(minZoomLvl > SlippyMapPreferences.getMaxZoomLvl()) {
    226                 System.err.println("minZoomLvl shouldnt be more than maxZoomLvl! Setting to maxZoomLvl.");
    227                 minZoomLvl = SlippyMapPreferences.getMaxZoomLvl();
    228         }
     222            System.err.println("minZoomLvl shouldnt be lees than "+MIN_ZOOM+"! Setting to that.");
     223            minZoomLvl = MIN_ZOOM;
     224        }
     225        if(minZoomLvl > SlippyMapPreferences.getMaxZoomLvl()) {
     226            System.err.println("minZoomLvl shouldnt be more than maxZoomLvl! Setting to maxZoomLvl.");
     227            minZoomLvl = SlippyMapPreferences.getMaxZoomLvl();
     228        }
    229229        return minZoomLvl;
    230230    }
     
    242242    public static void setMinZoomLvl(int minZoomLvl) {
    243243        minZoomLvl = checkMinZoomLvl(minZoomLvl);
    244         Main.pref.put(SlippyMapPreferences.PREFERENCE_MIN_ZOOM_LVL, "" + minZoomLvl);
     244        Main.pref.put(SlippyMapPreferences.PREFERENCE_MIN_ZOOM_LVL, "" + minZoomLvl);
    245245    }
    246246
    247247    public static TileSource NO_DEFAULT_TILE_SOURCE = new AbstractOsmTileSource(tr("(none)"), "") {
    248                 public TileUpdate getTileUpdate() {
    249                         return null;
    250                 }
     248        public TileUpdate getTileUpdate() {
     249            return null;
     250        }
    251251    };
    252252
     
    282282
    283283        @Override
    284                 public int getMaxZoom() {
     284        public int getMaxZoom() {
    285285            return 21;
    286286        }
    287287
    288288        @Override
    289                 public String getTilePath(int zoom, int tilex, int tiley) {
     289        public String getTilePath(int zoom, int tilex, int tiley) {
    290290            return "z=" + zoom + "&x=" + tilex + "&y=" + tiley;
    291291        }
     
    303303
    304304        @Override
    305                 public int getMaxZoom() {
     305        public int getMaxZoom() {
    306306            return 21;
    307307        }
    308308
    309309        @Override
    310                 public String getTilePath(int zoom, int tilex, int tiley) {
    311                 return "/" + zoom + "/" + tilex + "/" + tiley + ".png";
     310        public String getTilePath(int zoom, int tilex, int tiley) {
     311            return "/" + zoom + "/" + tilex + "/" + tiley + ".png";
    312312        }
    313313
  • applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersAddLayerAction.java

    r18542 r23190  
    2121
    2222    public WalkingPapersAddLayerAction() {
    23         super(tr("Scanned Map..."), "walkingpapers", 
    24                 tr("Display a map that was previously scanned and uploaded to walking-papers.org"), null, false);
     23        super(tr("Scanned Map..."), "walkingpapers",
     24            tr("Display a map that was previously scanned and uploaded to walking-papers.org"), null, false);
    2525    }
    2626
    2727    public void actionPerformed(ActionEvent e) {
    28         String wpid = JOptionPane.showInputDialog(Main.parent, 
    29                 tr("Enter a walking-papers.org URL or ID (the bit after the ?id= in the URL)"),
    30                         Main.pref.get("walkingpapers.last-used-id"));
     28        String wpid = JOptionPane.showInputDialog(Main.parent,
     29            tr("Enter a walking-papers.org URL or ID (the bit after the ?id= in the URL)"),
     30                Main.pref.get("walkingpapers.last-used-id"));
    3131
    3232        if (wpid == null || wpid.equals("")) return;
     
    4242        Pattern spanPattern = Pattern.compile("<span class=\"(\\S+)\">(\\S+)</span>");
    4343        Matcher m;
    44        
     44
    4545        double north = 0;
    4646        double south = 0;
     
    5252
    5353        try {
    54                 BufferedReader r = new BufferedReader(new InputStreamReader(new URL(wpUrl).openStream(), "utf-8"));
    55                 for (String line = r.readLine(); line != null; line = r.readLine()) {
    56                         m = spanPattern.matcher(line);
    57                         if (m.find()) {
    58                                 if ("tile".equals(m.group(1))) tile = m.group(2);
    59                                 else if ("north".equals(m.group(1))) north = Double.parseDouble(m.group(2));
    60                                 else if ("south".equals(m.group(1))) south = Double.parseDouble(m.group(2));
    61                                 else if ("east".equals(m.group(1))) east = Double.parseDouble(m.group(2));
    62                                 else if ("west".equals(m.group(1))) west = Double.parseDouble(m.group(2));
    63                                 else if ("minzoom".equals(m.group(1))) minz = Integer.parseInt(m.group(2));
    64                                 else if ("maxzoom".equals(m.group(1))) maxz = Integer.parseInt(m.group(2));
    65                         }
    66                 }
    67                 r.close();
    68                 if ((tile == null) || (north == 0 && south == 0) || (east == 0 && west == 0)) throw new Exception();
     54            BufferedReader r = new BufferedReader(new InputStreamReader(new URL(wpUrl).openStream(), "utf-8"));
     55            for (String line = r.readLine(); line != null; line = r.readLine()) {
     56                m = spanPattern.matcher(line);
     57                if (m.find()) {
     58                    if ("tile".equals(m.group(1))) tile = m.group(2);
     59                    else if ("north".equals(m.group(1))) north = Double.parseDouble(m.group(2));
     60                    else if ("south".equals(m.group(1))) south = Double.parseDouble(m.group(2));
     61                    else if ("east".equals(m.group(1))) east = Double.parseDouble(m.group(2));
     62                    else if ("west".equals(m.group(1))) west = Double.parseDouble(m.group(2));
     63                    else if ("minzoom".equals(m.group(1))) minz = Integer.parseInt(m.group(2));
     64                    else if ("maxzoom".equals(m.group(1))) maxz = Integer.parseInt(m.group(2));
     65                }
     66            }
     67            r.close();
     68            if ((tile == null) || (north == 0 && south == 0) || (east == 0 && west == 0)) throw new Exception();
    6969        } catch (Exception ex) {
    70                 JOptionPane.showMessageDialog(Main.parent,tr("Could not read information from walking-papers.org the id \"{0}\"", mungedWpId));
    71                 return;
     70            JOptionPane.showMessageDialog(Main.parent,tr("Could not read information from walking-papers.org the id \"{0}\"", mungedWpId));
     71            return;
    7272        }
    7373
     
    8282
    8383        Bounds b = new Bounds(new LatLon(south, west), new LatLon(north, east));
    84        
     84
    8585        WalkingPapersLayer wpl = new WalkingPapersLayer(mungedWpId, tile, b, minz, maxz);
    8686        Main.main.addLayer(wpl);
  • applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersKey.java

    r16522 r23190  
    11/**
    2  * 
     2 *
    33 */
    44package org.openstreetmap.josm.plugins.walkingpapers;
     
    99 * {@link #equals(Object)} and also {@link #toString()}.
    1010 * </p>
    11  * 
     11 *
    1212 * @author LuVar <lubomir.varga@freemap.sk>
    1313 * @author Dave Hansen <dave@sr71.net>
     
    1515 */
    1616public class WalkingPapersKey {
    17         private final int x;
    18         private final int y;
    19         private final int level;
    20        
    21         /**
    22         * <p>
    23         * Constructs key for hashmaps for some tile describedy by X and Y position. X and Y are tiles
    24         * positions on discrete map.
    25         * </p>
    26          *
    27          * @param x     x position in tiles table
    28          * @param y     y position in tiles table
    29         */
    30         public final boolean valid;
    31         public WalkingPapersKey(int level, int x, int y) {
    32                 this.x = x;
    33                 this.y = y;
    34                 this.level = level;
    35                 if (level <= 0 || x < 0 || y < 0) {
    36                         this.valid = false;
    37                         System.err.println("invalid WalkingPapersKey("+level+", "+x+", "+y+")");
    38                 } else {
    39                         this.valid = true;
    40                 }
    41         }
    42        
    43         /**
    44         * <p>
    45         * Returns true ONLY if x and y are equals.
    46         * </p>
    47          *
    48         * @see java.lang.Object#equals(java.lang.Object)
    49         */
    50         @Override
    51         public boolean equals(Object obj) {
    52                 if (obj instanceof WalkingPapersKey) {
    53                         WalkingPapersKey smk = (WalkingPapersKey) obj;
    54                         if((smk.x == this.x) && (smk.y == this.y) && (smk.level == this.level)) {
    55                                 return true;
    56                         }
    57                 }
    58                 return false;
    59         }
    60        
    61         /**
    62          * @return      return new Integer(this.x + this.y * 10000).hashCode();
    63         * @see java.lang.Object#hashCode()
    64         */
    65         @Override
    66         public int hashCode() {
    67                 return new Integer(this.x + this.y * 10000 + this.level * 100000).hashCode();
    68         }
    69        
    70         /**
    71         * @see java.lang.Object#toString()
    72         */
    73         @Override
    74         public String toString() {
    75                 return "WalkingPapersKey(x=" + this.x + ",y=" + this.y + ",level=" + level + ")";
    76         }
    77        
     17    private final int x;
     18    private final int y;
     19    private final int level;
     20
     21    /**
     22    * <p>
     23    * Constructs key for hashmaps for some tile describedy by X and Y position. X and Y are tiles
     24    * positions on discrete map.
     25    * </p>
     26     *
     27     * @param x x position in tiles table
     28     * @param y y position in tiles table
     29    */
     30    public final boolean valid;
     31    public WalkingPapersKey(int level, int x, int y) {
     32        this.x = x;
     33        this.y = y;
     34        this.level = level;
     35        if (level <= 0 || x < 0 || y < 0) {
     36            this.valid = false;
     37            System.err.println("invalid WalkingPapersKey("+level+", "+x+", "+y+")");
     38        } else {
     39            this.valid = true;
     40        }
     41    }
     42
     43    /**
     44    * <p>
     45    * Returns true ONLY if x and y are equals.
     46    * </p>
     47     *
     48    * @see java.lang.Object#equals(java.lang.Object)
     49    */
     50    @Override
     51    public boolean equals(Object obj) {
     52        if (obj instanceof WalkingPapersKey) {
     53            WalkingPapersKey smk = (WalkingPapersKey) obj;
     54            if((smk.x == this.x) && (smk.y == this.y) && (smk.level == this.level)) {
     55                return true;
     56            }
     57        }
     58        return false;
     59    }
     60
     61    /**
     62     * @return  return new Integer(this.x + this.y * 10000).hashCode();
     63    * @see java.lang.Object#hashCode()
     64    */
     65    @Override
     66    public int hashCode() {
     67        return new Integer(this.x + this.y * 10000 + this.level * 100000).hashCode();
     68    }
     69
     70    /**
     71    * @see java.lang.Object#toString()
     72    */
     73    @Override
     74    public String toString() {
     75        return "WalkingPapersKey(x=" + this.x + ",y=" + this.y + ",level=" + level + ")";
     76    }
     77
    7878}
  • applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersLayer.java

    r22549 r23190  
    3636 */
    3737public class WalkingPapersLayer extends Layer implements ImageObserver {
    38         /**
    39         * Actual zoom lvl. Initial zoom lvl is set to
    40         * {@link WalkingPapersPreferences#getMinZoomLvl()}.
    41         */
    42         private int currentZoomLevel;
    43         private HashMap<WalkingPapersKey, WalkingPapersTile> tileStorage = null;
    44 
    45         private Point[][] pixelpos = new Point[21][21];
    46         private LatLon lastTopLeft;
    47         private LatLon lastBotRight;
    48         private int viewportMinX, viewportMaxX, viewportMinY, viewportMaxY;
    49         private Image bufferImage;
    50         private boolean needRedraw;
    51 
    52         private int minzoom, maxzoom;
    53         private Bounds printBounds;
    54         private String tileUrlTemplate;
    55         private String walkingPapersId;
    56 
    57         @SuppressWarnings("serial")
    58         public WalkingPapersLayer(String id, String tile, Bounds b, int minz, int maxz) {
    59                 super(tr("Walking Papers: {0}", id));
    60                 setBackgroundLayer(true);
    61                 walkingPapersId = id;
    62 
    63                 tileUrlTemplate = tile;
    64                 this.printBounds = b;
    65                 this.minzoom = minz; this.maxzoom = maxz;
    66                 currentZoomLevel = minz;
    67 
    68                 clearTileStorage();
    69 
    70             MapView.addLayerChangeListener(new LayerChangeListener() {
    71                 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
    72                         // if user changes to a walking papers layer, zoom there just as if
    73                         // it was newly added
    74                         layerAdded(newLayer);
    75                 }
    76 
    77                 public void layerAdded(Layer newLayer) {
    78                         // only do something if we are affected
    79                         if (newLayer != WalkingPapersLayer.this) return;
    80                         BoundingXYVisitor bbox = new BoundingXYVisitor();
    81                         bbox.visit(printBounds);
    82                         Main.map.mapView.recalculateCenterScale(bbox);
    83                         needRedraw = true;
    84                 }
    85 
    86                 public void layerRemoved(Layer oldLayer) {
    87                         if (oldLayer == WalkingPapersLayer.this) {
    88                                 MapView.removeLayerChangeListener(this);
    89                         }
    90                 }
    91             });
    92         }
    93 
    94         /**
    95         * Zoom in, go closer to map.
    96         */
    97         public void increaseZoomLevel() {
    98                 if (currentZoomLevel < maxzoom) {
    99                         currentZoomLevel++;
    100                         needRedraw = true;
    101                 }
    102         }
    103 
    104         /**
    105         * Zoom out from map.
    106         */
    107         public void decreaseZoomLevel() {
    108                 if (currentZoomLevel > minzoom) {
    109                         currentZoomLevel--;
    110                         needRedraw = true;
    111                 }
    112         }
    113 
    114         public void clearTileStorage() {
    115                 tileStorage = new HashMap<WalkingPapersKey, WalkingPapersTile>();
    116                 checkTileStorage();
    117         }
    118 
    119         static class TileTimeComp implements Comparator<WalkingPapersTile> {
    120                 public int compare(WalkingPapersTile s1, WalkingPapersTile s2) {
    121                         long t1 = s1.access_time();
    122                         long t2 = s2.access_time();
    123                         if (s1 == s2) return 0;
    124                         if (t1 == t2) {
    125                                 t1 = s1.hashCode();
    126                                 t2 = s2.hashCode();
    127                         }
    128                         if (t1 < t2) return -1;
    129                         return 1;
    130                 }
    131         }
    132 
    133         long lastCheck = 0;
    134         /**
    135         * <p>
    136         * Check if tiles.size() is not more than max_nr_tiles. If yes, oldest tiles by timestamp
    137         * are fired out from cache.
    138         * </p>
    139         */
    140         public void checkTileStorage() {
    141                 long now = System.currentTimeMillis();
    142                 if (now - lastCheck < 1000) return;
    143                 lastCheck = now;
    144                 TreeSet<WalkingPapersTile> tiles = new TreeSet<WalkingPapersTile>(new TileTimeComp());
    145                 tiles.addAll(tileStorage.values());
    146                 int max_nr_tiles = 100;
    147                 if (tiles.size() < max_nr_tiles) {
    148                         return;
    149                 }
    150                 int dropCount = tiles.size() - max_nr_tiles;;
    151                 for (WalkingPapersTile t : tiles) {
    152                         if (dropCount <= 0)
    153                                 break;
    154                         t.dropImage();
    155                         dropCount--;
    156                 }
    157         }
    158 
    159         void loadSingleTile(WalkingPapersTile tile) {
    160                 tile.loadImage();
    161                 this.checkTileStorage();
    162         }
    163 
    164         /*
    165         * Attempt to approximate how much the image is
    166         * being scaled.  For instance, a 100x100 image
    167         * being scaled to 50x50 would return 0.25.
    168         */
    169         Double getImageScaling(Image img, Point p0, Point p1) {
    170                 int realWidth = img.getWidth(this);
    171                 int realHeight = img.getHeight(this);
    172                 if (realWidth == -1 || realHeight == -1)
    173                                 return null;
    174                 int drawWidth = p1.x - p0.x;
    175                 int drawHeight = p1.x - p0.x;
    176 
    177                 double drawArea = drawWidth * drawHeight;
    178                 double realArea = realWidth * realHeight;
    179 
    180                 return drawArea / realArea;
    181         }
    182 
    183         /**
    184      */
    185         @Override
    186         public void paint(Graphics2D g, MapView mv, Bounds bounds) {
    187                 LatLon topLeft = mv.getLatLon(0, 0);
    188                 LatLon botRight = mv.getLatLon(mv.getWidth(), mv.getHeight());
    189                 Graphics2D oldg = g;
    190 
    191                 if (botRight.lon() == 0.0 || botRight.lat() == 0) {
    192                                 // probably still initializing
    193                                 return;
    194                 }
    195                 if (lastTopLeft != null && lastBotRight != null
    196                                 && topLeft.equalsEpsilon(lastTopLeft)
    197                                 && botRight.equalsEpsilon(lastBotRight) && bufferImage != null
    198                                 && mv.getWidth() == bufferImage.getWidth(null)
    199                                 && mv.getHeight() == bufferImage.getHeight(null) && !needRedraw) {
    200 
    201                         g.drawImage(bufferImage, 0, 0, null);
    202                         return;
    203                 }
    204 
    205                 needRedraw = false;
    206                 lastTopLeft = topLeft;
    207                 lastBotRight = botRight;
    208                 bufferImage = mv.createImage(mv.getWidth(), mv.getHeight());
    209                 g = (Graphics2D) bufferImage.getGraphics();
     38    /**
     39    * Actual zoom lvl. Initial zoom lvl is set to
     40    * {@link WalkingPapersPreferences#getMinZoomLvl()}.
     41    */
     42    private int currentZoomLevel;
     43    private HashMap<WalkingPapersKey, WalkingPapersTile> tileStorage = null;
     44
     45    private Point[][] pixelpos = new Point[21][21];
     46    private LatLon lastTopLeft;
     47    private LatLon lastBotRight;
     48    private int viewportMinX, viewportMaxX, viewportMinY, viewportMaxY;
     49    private Image bufferImage;
     50    private boolean needRedraw;
     51
     52    private int minzoom, maxzoom;
     53    private Bounds printBounds;
     54    private String tileUrlTemplate;
     55    private String walkingPapersId;
     56
     57    @SuppressWarnings("serial")
     58    public WalkingPapersLayer(String id, String tile, Bounds b, int minz, int maxz) {
     59        super(tr("Walking Papers: {0}", id));
     60        setBackgroundLayer(true);
     61        walkingPapersId = id;
     62
     63        tileUrlTemplate = tile;
     64        this.printBounds = b;
     65        this.minzoom = minz; this.maxzoom = maxz;
     66        currentZoomLevel = minz;
     67
     68        clearTileStorage();
     69
     70        MapView.addLayerChangeListener(new LayerChangeListener() {
     71            public void activeLayerChange(Layer oldLayer, Layer newLayer) {
     72                // if user changes to a walking papers layer, zoom there just as if
     73                // it was newly added
     74                layerAdded(newLayer);
     75            }
     76
     77            public void layerAdded(Layer newLayer) {
     78                // only do something if we are affected
     79                if (newLayer != WalkingPapersLayer.this) return;
     80                BoundingXYVisitor bbox = new BoundingXYVisitor();
     81                bbox.visit(printBounds);
     82                Main.map.mapView.recalculateCenterScale(bbox);
     83                needRedraw = true;
     84            }
     85
     86            public void layerRemoved(Layer oldLayer) {
     87                if (oldLayer == WalkingPapersLayer.this) {
     88                    MapView.removeLayerChangeListener(this);
     89                }
     90            }
     91        });
     92    }
     93
     94    /**
     95    * Zoom in, go closer to map.
     96    */
     97    public void increaseZoomLevel() {
     98        if (currentZoomLevel < maxzoom) {
     99            currentZoomLevel++;
     100            needRedraw = true;
     101        }
     102    }
     103
     104    /**
     105    * Zoom out from map.
     106    */
     107    public void decreaseZoomLevel() {
     108        if (currentZoomLevel > minzoom) {
     109            currentZoomLevel--;
     110            needRedraw = true;
     111        }
     112    }
     113
     114    public void clearTileStorage() {
     115        tileStorage = new HashMap<WalkingPapersKey, WalkingPapersTile>();
     116        checkTileStorage();
     117    }
     118
     119    static class TileTimeComp implements Comparator<WalkingPapersTile> {
     120        public int compare(WalkingPapersTile s1, WalkingPapersTile s2) {
     121            long t1 = s1.access_time();
     122            long t2 = s2.access_time();
     123            if (s1 == s2) return 0;
     124            if (t1 == t2) {
     125                t1 = s1.hashCode();
     126                t2 = s2.hashCode();
     127            }
     128            if (t1 < t2) return -1;
     129            return 1;
     130        }
     131    }
     132
     133    long lastCheck = 0;
     134    /**
     135    * <p>
     136    * Check if tiles.size() is not more than max_nr_tiles. If yes, oldest tiles by timestamp
     137    * are fired out from cache.
     138    * </p>
     139    */
     140    public void checkTileStorage() {
     141        long now = System.currentTimeMillis();
     142        if (now - lastCheck < 1000) return;
     143        lastCheck = now;
     144        TreeSet<WalkingPapersTile> tiles = new TreeSet<WalkingPapersTile>(new TileTimeComp());
     145        tiles.addAll(tileStorage.values());
     146        int max_nr_tiles = 100;
     147        if (tiles.size() < max_nr_tiles) {
     148            return;
     149        }
     150        int dropCount = tiles.size() - max_nr_tiles;;
     151        for (WalkingPapersTile t : tiles) {
     152            if (dropCount <= 0)
     153                break;
     154            t.dropImage();
     155            dropCount--;
     156        }
     157    }
     158
     159    void loadSingleTile(WalkingPapersTile tile) {
     160        tile.loadImage();
     161        this.checkTileStorage();
     162    }
     163
     164    /*
     165    * Attempt to approximate how much the image is
     166    * being scaled.  For instance, a 100x100 image
     167    * being scaled to 50x50 would return 0.25.
     168    */
     169    Double getImageScaling(Image img, Point p0, Point p1) {
     170        int realWidth = img.getWidth(this);
     171        int realHeight = img.getHeight(this);
     172        if (realWidth == -1 || realHeight == -1)
     173                return null;
     174        int drawWidth = p1.x - p0.x;
     175        int drawHeight = p1.x - p0.x;
     176
     177        double drawArea = drawWidth * drawHeight;
     178        double realArea = realWidth * realHeight;
     179
     180        return drawArea / realArea;
     181    }
     182
     183    /**
     184     */
     185    @Override
     186    public void paint(Graphics2D g, MapView mv, Bounds bounds) {
     187        LatLon topLeft = mv.getLatLon(0, 0);
     188        LatLon botRight = mv.getLatLon(mv.getWidth(), mv.getHeight());
     189        Graphics2D oldg = g;
     190
     191        if (botRight.lon() == 0.0 || botRight.lat() == 0) {
     192                // probably still initializing
     193                return;
     194        }
     195        if (lastTopLeft != null && lastBotRight != null
     196                && topLeft.equalsEpsilon(lastTopLeft)
     197                && botRight.equalsEpsilon(lastBotRight) && bufferImage != null
     198                && mv.getWidth() == bufferImage.getWidth(null)
     199                && mv.getHeight() == bufferImage.getHeight(null) && !needRedraw) {
     200
     201            g.drawImage(bufferImage, 0, 0, null);
     202            return;
     203        }
     204
     205        needRedraw = false;
     206        lastTopLeft = topLeft;
     207        lastBotRight = botRight;
     208        bufferImage = mv.createImage(mv.getWidth(), mv.getHeight());
     209        g = (Graphics2D) bufferImage.getGraphics();
    210210
    211211        if (!LatLon.isValidLat(topLeft.lat())  ||
     
    215215            return;
    216216
    217                 viewportMinX = lonToTileX(topLeft.lon());
    218                 viewportMaxX = lonToTileX(botRight.lon());
    219                 viewportMinY = latToTileY(topLeft.lat());
    220                 viewportMaxY = latToTileY(botRight.lat());
    221 
    222                 if (viewportMinX > viewportMaxX) {
    223                         int tmp = viewportMinX;
    224                         viewportMinX = viewportMaxX;
    225                         viewportMaxX = tmp;
    226                 }
    227                 if (viewportMinY > viewportMaxY) {
    228                         int tmp = viewportMinY;
    229                         viewportMinY = viewportMaxY;
    230                         viewportMaxY = tmp;
    231                 }
    232 
    233                 if (viewportMaxX-viewportMinX > 18) return;
    234                 if (viewportMaxY-viewportMinY > 18) return;
    235 
    236                 for (int x = viewportMinX - 1; x <= viewportMaxX + 1; x++) {
    237                         double lon = tileXToLon(x);
    238                         for (int y = viewportMinY - 1; y <= viewportMaxY + 1; y++) {
    239                                 LatLon tmpLL = new LatLon(tileYToLat(y), lon);
    240                                 pixelpos[x - viewportMinX + 1][y - viewportMinY + 1] = mv.getPoint(Main.proj
    241                                                 .latlon2eastNorth(tmpLL));
    242                         }
    243                 }
    244 
    245                 g.setColor(Color.DARK_GRAY);
    246 
    247                 Double imageScale = null;
    248                 int count = 0;
    249 
    250                 for (int x = viewportMinX-1; x <= viewportMaxX; x++) {
    251 
    252                         for (int y = viewportMinY-1; y <= viewportMaxY; y++) {
    253                                 WalkingPapersKey key = new WalkingPapersKey(currentZoomLevel, x, y);
    254                                 WalkingPapersTile tile;
    255                                 tile = tileStorage.get(key);
    256                                 if (!key.valid) continue;
    257                                 if (tile == null) {
    258                                         // check if tile is in range
    259                                         Bounds tileBounds = new Bounds(new LatLon(tileYToLat(y+1), tileXToLon(x)),
    260                                                 new LatLon(tileYToLat(y), tileXToLon(x+1)));
    261                                         if (!tileBounds.asRect().intersects(printBounds.asRect())) continue;
    262                                         tile = new WalkingPapersTile(x, y, currentZoomLevel, this);
    263                                         tileStorage.put(key, tile);
    264                                         loadSingleTile(tile);
    265                                         checkTileStorage();
    266                                 }
    267                                 Image img = tile.getImage();
    268 
    269                                 if (img != null) {
    270                                         Point p = pixelpos[x - viewportMinX + 1][y - viewportMinY + 1];
    271                                         Point p2 = pixelpos[x - viewportMinX + 2][y - viewportMinY + 2];
    272                                         g.drawImage(img, p.x, p.y, p2.x - p.x, p2.y - p.y, this);
    273                                         if (imageScale == null)
    274                                                 imageScale = getImageScaling(img, p, p2);
    275                                         count++;
    276                                 }
    277                         }
    278                 }
    279 
    280                 if (count == 0)
    281                 {
    282                         //System.out.println("no images on " + walkingPapersId + ", return");
    283                         return;
    284                 }
    285 
    286                 oldg.drawImage(bufferImage, 0, 0, null);
    287 
    288                 if (imageScale != null) {
    289                         // If each source image pixel is being stretched into > 3
    290                         // drawn pixels, zoom in... getting too pixelated
    291                         if (imageScale > 3) {
    292                                 increaseZoomLevel();
    293                                 this.paint(oldg, mv, bounds);
    294                         }
    295 
    296                         // If each source image pixel is being squished into > 0.32
    297                         // of a drawn pixels, zoom out.
    298                         else if (imageScale < 0.32) {
    299                                 decreaseZoomLevel();
    300                                 this.paint(oldg, mv, bounds);
    301                         }
    302                 }
    303         }// end of paint metod
    304 
    305         WalkingPapersTile getTileForPixelpos(int px, int py) {
    306                 int tilex = viewportMaxX;
    307                 int tiley = viewportMaxY;
    308                 for (int x = viewportMinX; x <= viewportMaxX; x++) {
    309                         if (pixelpos[x - viewportMinX + 1][0].x > px) {
    310                                 tilex = x - 1;
    311                                 break;
    312                         }
    313                 }
    314 
    315                 if (tilex == -1) return null;
    316 
    317                 for (int y = viewportMinY; y <= viewportMaxY; y++) {
    318                         if (pixelpos[0][y - viewportMinY + 1].y > py) {
    319                                 tiley = y - 1;
    320                                 break;
    321                         }
    322                 }
    323 
    324                 if (tiley == -1) return null;
    325 
    326                 WalkingPapersKey key = new WalkingPapersKey(currentZoomLevel, tilex, tiley);
    327                 if (!key.valid) {
    328                         System.err.println("getTileForPixelpos("+px+","+py+") made invalid key");
    329                         return null;
    330                 }
    331                 WalkingPapersTile tile = tileStorage.get(key);
    332                 if (tile == null)
    333                         tileStorage.put(key, tile = new WalkingPapersTile(tilex, tiley, currentZoomLevel, this));
    334                 checkTileStorage();
    335                 return tile;
    336         }
    337 
    338         @Override
    339         public Icon getIcon() {
    340                 return ImageProvider.get("walkingpapers");
    341         }
    342 
    343         @Override
    344         public Object getInfoComponent() {
    345                 return getToolTipText();
    346         }
    347 
    348         @Override
    349         public Action[] getMenuEntries() {
    350                 return new Action[] {
    351                                 LayerListDialog.getInstance().createShowHideLayerAction(),
    352                                 LayerListDialog.getInstance().createDeleteLayerAction(),
    353                                 SeparatorLayerAction.INSTANCE,
    354                                 // color,
    355                                 // new JMenuItem(new RenameLayerAction(associatedFile, this)),
    356                                 SeparatorLayerAction.INSTANCE,
    357                                 new LayerListPopup.InfoAction(this) };
    358         }
    359 
    360         @Override
    361         public String getToolTipText() {
    362                 return tr("Walking Papers layer ({0}) in zoom {1}", this.getWalkingPapersId(), currentZoomLevel);
    363         }
    364 
    365         @Override
    366         public boolean isMergable(Layer other) {
    367                 return false;
    368         }
    369 
    370         @Override
    371         public void mergeFrom(Layer from) {
    372         }
    373 
    374         @Override
    375         public void visitBoundingBox(BoundingXYVisitor v) {
     217        viewportMinX = lonToTileX(topLeft.lon());
     218        viewportMaxX = lonToTileX(botRight.lon());
     219        viewportMinY = latToTileY(topLeft.lat());
     220        viewportMaxY = latToTileY(botRight.lat());
     221
     222        if (viewportMinX > viewportMaxX) {
     223            int tmp = viewportMinX;
     224            viewportMinX = viewportMaxX;
     225            viewportMaxX = tmp;
     226        }
     227        if (viewportMinY > viewportMaxY) {
     228            int tmp = viewportMinY;
     229            viewportMinY = viewportMaxY;
     230            viewportMaxY = tmp;
     231        }
     232
     233        if (viewportMaxX-viewportMinX > 18) return;
     234        if (viewportMaxY-viewportMinY > 18) return;
     235
     236        for (int x = viewportMinX - 1; x <= viewportMaxX + 1; x++) {
     237            double lon = tileXToLon(x);
     238            for (int y = viewportMinY - 1; y <= viewportMaxY + 1; y++) {
     239                LatLon tmpLL = new LatLon(tileYToLat(y), lon);
     240                pixelpos[x - viewportMinX + 1][y - viewportMinY + 1] = mv.getPoint(Main.proj
     241                        .latlon2eastNorth(tmpLL));
     242            }
     243        }
     244
     245        g.setColor(Color.DARK_GRAY);
     246
     247        Double imageScale = null;
     248        int count = 0;
     249
     250        for (int x = viewportMinX-1; x <= viewportMaxX; x++) {
     251
     252            for (int y = viewportMinY-1; y <= viewportMaxY; y++) {
     253                WalkingPapersKey key = new WalkingPapersKey(currentZoomLevel, x, y);
     254                WalkingPapersTile tile;
     255                tile = tileStorage.get(key);
     256                if (!key.valid) continue;
     257                if (tile == null) {
     258                    // check if tile is in range
     259                    Bounds tileBounds = new Bounds(new LatLon(tileYToLat(y+1), tileXToLon(x)),
     260                        new LatLon(tileYToLat(y), tileXToLon(x+1)));
     261                    if (!tileBounds.asRect().intersects(printBounds.asRect())) continue;
     262                    tile = new WalkingPapersTile(x, y, currentZoomLevel, this);
     263                    tileStorage.put(key, tile);
     264                    loadSingleTile(tile);
     265                    checkTileStorage();
     266                }
     267                Image img = tile.getImage();
     268
     269                if (img != null) {
     270                    Point p = pixelpos[x - viewportMinX + 1][y - viewportMinY + 1];
     271                    Point p2 = pixelpos[x - viewportMinX + 2][y - viewportMinY + 2];
     272                    g.drawImage(img, p.x, p.y, p2.x - p.x, p2.y - p.y, this);
     273                    if (imageScale == null)
     274                        imageScale = getImageScaling(img, p, p2);
     275                    count++;
     276                }
     277            }
     278        }
     279
     280        if (count == 0)
     281        {
     282            //System.out.println("no images on " + walkingPapersId + ", return");
     283            return;
     284        }
     285
     286        oldg.drawImage(bufferImage, 0, 0, null);
     287
     288        if (imageScale != null) {
     289            // If each source image pixel is being stretched into > 3
     290            // drawn pixels, zoom in... getting too pixelated
     291            if (imageScale > 3) {
     292                increaseZoomLevel();
     293                this.paint(oldg, mv, bounds);
     294            }
     295
     296            // If each source image pixel is being squished into > 0.32
     297            // of a drawn pixels, zoom out.
     298            else if (imageScale < 0.32) {
     299                decreaseZoomLevel();
     300                this.paint(oldg, mv, bounds);
     301            }
     302        }
     303    }// end of paint metod
     304
     305    WalkingPapersTile getTileForPixelpos(int px, int py) {
     306        int tilex = viewportMaxX;
     307        int tiley = viewportMaxY;
     308        for (int x = viewportMinX; x <= viewportMaxX; x++) {
     309            if (pixelpos[x - viewportMinX + 1][0].x > px) {
     310                tilex = x - 1;
     311                break;
     312            }
     313        }
     314
     315        if (tilex == -1) return null;
     316
     317        for (int y = viewportMinY; y <= viewportMaxY; y++) {
     318            if (pixelpos[0][y - viewportMinY + 1].y > py) {
     319                tiley = y - 1;
     320                break;
     321            }
     322        }
     323
     324        if (tiley == -1) return null;
     325
     326        WalkingPapersKey key = new WalkingPapersKey(currentZoomLevel, tilex, tiley);
     327        if (!key.valid) {
     328            System.err.println("getTileForPixelpos("+px+","+py+") made invalid key");
     329            return null;
     330        }
     331        WalkingPapersTile tile = tileStorage.get(key);
     332        if (tile == null)
     333            tileStorage.put(key, tile = new WalkingPapersTile(tilex, tiley, currentZoomLevel, this));
     334        checkTileStorage();
     335        return tile;
     336    }
     337
     338    @Override
     339    public Icon getIcon() {
     340        return ImageProvider.get("walkingpapers");
     341    }
     342
     343    @Override
     344    public Object getInfoComponent() {
     345        return getToolTipText();
     346    }
     347
     348    @Override
     349    public Action[] getMenuEntries() {
     350        return new Action[] {
     351                LayerListDialog.getInstance().createShowHideLayerAction(),
     352                LayerListDialog.getInstance().createDeleteLayerAction(),
     353                SeparatorLayerAction.INSTANCE,
     354                // color,
     355                // new JMenuItem(new RenameLayerAction(associatedFile, this)),
     356                SeparatorLayerAction.INSTANCE,
     357                new LayerListPopup.InfoAction(this) };
     358    }
     359
     360    @Override
     361    public String getToolTipText() {
     362        return tr("Walking Papers layer ({0}) in zoom {1}", this.getWalkingPapersId(), currentZoomLevel);
     363    }
     364
     365    @Override
     366    public boolean isMergable(Layer other) {
     367        return false;
     368    }
     369
     370    @Override
     371    public void mergeFrom(Layer from) {
     372    }
     373
     374    @Override
     375    public void visitBoundingBox(BoundingXYVisitor v) {
    376376        if (printBounds != null)
    377377            v.visit(printBounds);
    378         }
    379 
    380         private int latToTileY(double lat) {
    381                 double l = lat / 180 * Math.PI;
    382                 double pf = Math.log(Math.tan(l) + (1 / Math.cos(l)));
    383                 return (int) (Math.pow(2.0, currentZoomLevel - 1) * (Math.PI - pf) / Math.PI);
    384         }
    385 
    386         private int lonToTileX(double lon) {
    387                 return (int) (Math.pow(2.0, currentZoomLevel - 3) * (lon + 180.0) / 45.0);
    388         }
    389 
    390         private double tileYToLat(int y) {
    391                 return Math.atan(Math.sinh(Math.PI
    392                                 - (Math.PI * y / Math.pow(2.0, currentZoomLevel - 1))))
    393                                 * 180 / Math.PI;
    394         }
    395 
    396         private double tileXToLon(int x) {
    397                 return x * 45.0 / Math.pow(2.0, currentZoomLevel - 3) - 180.0;
    398         }
    399 
    400         public boolean imageUpdate(Image img, int infoflags, int x, int y,
    401                         int width, int height) {
    402                 boolean done = ((infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0);
    403                 if ((infoflags & ERROR) != 0) return false;
    404                 // Repaint immediately if we are done, otherwise batch up
    405                 // repaint requests every 100 milliseconds
    406                 needRedraw = true;
    407                 Main.map.repaint(done ? 0 : 100);
    408                 return !done;
    409         }
    410 
    411         public String getWalkingPapersId() {
    412                 return walkingPapersId;
    413         }
    414 
    415         public URL formatImageUrl(int x, int y, int z) {
    416                 String urlstr = tileUrlTemplate.
    417                         replace("{x}", String.valueOf(x)).
    418                         replace("{y}", String.valueOf(y)).
    419                         replace("{z}", String.valueOf(z));
    420                 try {
    421                         return new URL(urlstr);
    422                 } catch (Exception ex) {
    423                         return null;
    424                 }
    425         }
     378    }
     379
     380    private int latToTileY(double lat) {
     381        double l = lat / 180 * Math.PI;
     382        double pf = Math.log(Math.tan(l) + (1 / Math.cos(l)));
     383        return (int) (Math.pow(2.0, currentZoomLevel - 1) * (Math.PI - pf) / Math.PI);
     384    }
     385
     386    private int lonToTileX(double lon) {
     387        return (int) (Math.pow(2.0, currentZoomLevel - 3) * (lon + 180.0) / 45.0);
     388    }
     389
     390    private double tileYToLat(int y) {
     391        return Math.atan(Math.sinh(Math.PI
     392                - (Math.PI * y / Math.pow(2.0, currentZoomLevel - 1))))
     393                * 180 / Math.PI;
     394    }
     395
     396    private double tileXToLon(int x) {
     397        return x * 45.0 / Math.pow(2.0, currentZoomLevel - 3) - 180.0;
     398    }
     399
     400    public boolean imageUpdate(Image img, int infoflags, int x, int y,
     401            int width, int height) {
     402        boolean done = ((infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0);
     403        if ((infoflags & ERROR) != 0) return false;
     404        // Repaint immediately if we are done, otherwise batch up
     405        // repaint requests every 100 milliseconds
     406        needRedraw = true;
     407        Main.map.repaint(done ? 0 : 100);
     408        return !done;
     409    }
     410
     411    public String getWalkingPapersId() {
     412        return walkingPapersId;
     413    }
     414
     415    public URL formatImageUrl(int x, int y, int z) {
     416        String urlstr = tileUrlTemplate.
     417            replace("{x}", String.valueOf(x)).
     418            replace("{y}", String.valueOf(y)).
     419            replace("{z}", String.valueOf(z));
     420        try {
     421            return new URL(urlstr);
     422        } catch (Exception ex) {
     423            return null;
     424        }
     425    }
    426426
    427427}
  • applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersPlugin.java

    r19487 r23190  
    2626    public WalkingPapersPlugin(PluginInformation info)
    2727    {
    28         super(info);
     28        super(info);
    2929        MainMenu menu = Main.main.menu;
    3030        walkingPapersMenu = menu.addMenu(marktr("Walking Papers"), KeyEvent.VK_K, menu.defaultMenuPos, ht("/Plugin/WalkingPapers"));
  • applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersTile.java

    r16549 r23190  
    77/**
    88 * Class that contains information about one single slippy map tile.
    9  * 
     9 *
    1010 * @author Frederik Ramm <frederik@remote.org>
    1111 * @author LuVar <lubomir.varga@freemap.sk>
    1212 * @author Dave Hansen <dave@sr71.net>
    13  * 
     13 *
    1414 */
    1515public class WalkingPapersTile {
    1616    private Image tileImage;
    17         long timestamp;
     17    long timestamp;
    1818
    1919    int x;
    2020    int y;
    2121    int z;
    22    
     22
    2323    WalkingPapersLayer parentLayer;
    2424
     
    2929        this.z = z;
    3030        parentLayer = parent;
    31                 timestamp = System.currentTimeMillis();
     31        timestamp = System.currentTimeMillis();
    3232    }
    3333
    3434    public URL getImageUrl() {
    35         return parentLayer.formatImageUrl(x, y, z);
     35        return parentLayer.formatImageUrl(x, y, z);
    3636    }
    3737
     
    3939        URL imageUrl = this.getImageUrl();
    4040        tileImage = Toolkit.getDefaultToolkit().createImage(imageUrl);
    41                 Toolkit.getDefaultToolkit().sync();
    42                 timestamp = System.currentTimeMillis();
     41        Toolkit.getDefaultToolkit().sync();
     42        timestamp = System.currentTimeMillis();
    4343    }
    4444
     
    4949
    5050    public void dropImage() {
    51                 tileImage = null;
    52                 //  This should work in theory but doesn't seem to actually
    53                 //  reduce the X server memory usage
    54                 //tileImage.flush();
     51        tileImage = null;
     52        //  This should work in theory but doesn't seem to actually
     53        //  reduce the X server memory usage
     54        //tileImage.flush();
    5555    }
    5656
  • applications/editors/josm/plugins/waypoint_search/src/org/openstreetmap/josm/plugins/waypointSearch/Engine.java

    r22661 r23190  
    99
    1010public class Engine {
    11        
    12         public List<Marker> searchGpxWaypoints(String waypointSearchPattern) {
    13                 List<Marker> returnList = new ArrayList<Marker>();
    14                 if (gpxLayersExist()) {
    15                         //Loop over marker (waypoint) layers.. it could be more than one
    16                         for (Iterator<MarkerLayer> layerIterator = Main.map.mapView.getLayersOfType(MarkerLayer.class).iterator(); layerIterator.hasNext();) {
    17                                 //loop over each marker (waypoint)
    18                                 for (Iterator<Marker> markerIterator = layerIterator.next().data.iterator(); markerIterator.hasNext();) {
    19                                         Marker marker = markerIterator.next();
    20                                         if (Pattern.matches(".*\\Q"+waypointSearchPattern.toLowerCase()+"\\E.*", marker.getText().toLowerCase())) {
    21                                                 returnList.add(marker);
    22                                         }
    23                                 }                               
    24                         }
    25                 }
    26                 return returnList;
    27         }       
    28                
    29                
    30                
    31        
     11   
     12    public List<Marker> searchGpxWaypoints(String waypointSearchPattern) {
     13        List<Marker> returnList = new ArrayList<Marker>();
     14        if (gpxLayersExist()) {
     15            //Loop over marker (waypoint) layers.. it could be more than one
     16            for (Iterator<MarkerLayer> layerIterator = Main.map.mapView.getLayersOfType(MarkerLayer.class).iterator(); layerIterator.hasNext();) {
     17                //loop over each marker (waypoint)
     18                for (Iterator<Marker> markerIterator = layerIterator.next().data.iterator(); markerIterator.hasNext();) {
     19                    Marker marker = markerIterator.next();
     20                    if (Pattern.matches(".*\\Q"+waypointSearchPattern.toLowerCase()+"\\E.*", marker.getText().toLowerCase())) {
     21                        returnList.add(marker);
     22                    }
     23                }               
     24            }
     25        }
     26        return returnList;
     27    }   
     28       
     29       
     30       
     31   
    3232
    33        
    34        
    35        
     33   
     34   
     35   
    3636    public boolean gpxLayersExist() {
    37           boolean rv = false;
    38           if (Main.map != null) {
    39                   if (Main.map.mapView.hasLayers()) {
    40                           if (Main.map.mapView.getLayersOfType(MarkerLayer.class).size()>0) {
    41                                   rv = true;
    42                           }
    43                   }
    44           }
    45           return rv;
     37      boolean rv = false;
     38      if (Main.map != null) {
     39          if (Main.map.mapView.hasLayers()) {
     40              if (Main.map.mapView.getLayersOfType(MarkerLayer.class).size()>0) {
     41                  rv = true;
     42              }
     43          }
     44      }
     45      return rv;
    4646    }
    47        
    48        
    49        
     47   
     48   
     49   
    5050}
  • applications/editors/josm/plugins/waypoint_search/src/org/openstreetmap/josm/plugins/waypointSearch/SelectWaypointDialog.java

    r23180 r23190  
    2020public class SelectWaypointDialog extends ToggleDialog implements KeyListener, MouseListener {
    2121
    22         private JTextField searchPattern = new JTextField(20);
    23         private DefaultListModel listModel = new DefaultListModel();
    24         private JList searchResult = new JList(listModel);
    25         private List<Marker> SearchResultObjectCache = new ArrayList<Marker>();
    26         private boolean first_time_search = true;
    27         private Engine engine = new Engine();
    28        
    29        
    30         public SelectWaypointDialog(String name, String iconName, String tooltip,
    31                         Shortcut shortcut, int preferredHeight) {
    32                 super(name, iconName, tooltip, shortcut, preferredHeight);
    33                 build();
    34         }
    35        
     22    private JTextField searchPattern = new JTextField(20);
     23    private DefaultListModel listModel = new DefaultListModel();
     24    private JList searchResult = new JList(listModel);
     25    private List<Marker> SearchResultObjectCache = new ArrayList<Marker>();
     26    private boolean first_time_search = true;
     27    private Engine engine = new Engine();
     28   
     29   
     30    public SelectWaypointDialog(String name, String iconName, String tooltip,
     31            Shortcut shortcut, int preferredHeight) {
     32        super(name, iconName, tooltip, shortcut, preferredHeight);
     33        build();
     34    }
     35   
    3636
    3737    protected void build() {
    38         //add panel - all the gui of the plugin goes in here
    39         JPanel panel = new JPanel(new BorderLayout());
    40        
    41         //search field
    42         searchPattern.setText(tr("Enter search expression here.."));
    43         searchPattern.addKeyListener(this);
    44         searchPattern.addMouseListener(this);
    45         panel.add(searchPattern,BorderLayout.NORTH);
    46        
    47         //add result table
    48         searchResult.setLayoutOrientation(JList.VERTICAL);
    49         searchResult.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    50         searchResult.addMouseListener(this);
    51         JScrollPane scrollPane = new JScrollPane(searchResult);
    52         scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    53         panel.add(scrollPane,BorderLayout.CENTER);
    54        
    55         //add label
    56         JLabel label = new JLabel(tr("Select waypoint to move map"));
    57         panel.add(label,BorderLayout.SOUTH);
    58        
    59         //add panel to JOSM gui
    60         add(panel,BorderLayout.CENTER);
     38        //add panel - all the gui of the plugin goes in here
     39        JPanel panel = new JPanel(new BorderLayout());
     40       
     41        //search field
     42        searchPattern.setText(tr("Enter search expression here.."));
     43        searchPattern.addKeyListener(this);
     44        searchPattern.addMouseListener(this);
     45        panel.add(searchPattern,BorderLayout.NORTH);
     46       
     47        //add result table
     48        searchResult.setLayoutOrientation(JList.VERTICAL);
     49        searchResult.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
     50        searchResult.addMouseListener(this);
     51        JScrollPane scrollPane = new JScrollPane(searchResult);
     52        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     53        panel.add(scrollPane,BorderLayout.CENTER);
     54       
     55        //add label
     56        JLabel label = new JLabel(tr("Select waypoint to move map"));
     57        panel.add(label,BorderLayout.SOUTH);
     58       
     59        //add panel to JOSM gui
     60        add(panel,BorderLayout.CENTER);
    6161    }
    6262
     
    7878   
    7979
    80         @Override
    81         public void keyPressed(KeyEvent arg0) {
    82                 // TODO Auto-generated method stub
    83         }
     80    @Override
     81    public void keyPressed(KeyEvent arg0) {
     82        // TODO Auto-generated method stub
     83    }
    8484
    8585
    86         @Override
    87         public void keyReleased(KeyEvent arg0) {
    88                 // TODO Auto-generated method stub
    89                 updateSearchResults();
    90         }
     86    @Override
     87    public void keyReleased(KeyEvent arg0) {
     88        // TODO Auto-generated method stub
     89        updateSearchResults();
     90    }
    9191
    9292
     
    9797
    9898
    99         @Override
    100         public void mouseClicked(MouseEvent e) {
    101                 if (e.getSource()==searchResult) {
    102                         //click on the search result box
    103                         Marker marker = SearchResultObjectCache.get(searchResult.getSelectedIndex());
    104                         Main.map.mapView.zoomTo(marker.getCoor());
    105                 } else {
    106                         //click on the text field (input search expression)
    107                 }
    108         }
     99    @Override
     100    public void mouseClicked(MouseEvent e) {
     101        if (e.getSource()==searchResult) {
     102            //click on the search result box
     103            Marker marker = SearchResultObjectCache.get(searchResult.getSelectedIndex());
     104            Main.map.mapView.zoomTo(marker.getCoor());
     105        } else {
     106            //click on the text field (input search expression)
     107        }
     108    }
    109109
    110110
    111         @Override
    112         public void mouseEntered(MouseEvent arg0) {
    113                 // TODO Auto-generated method stub
    114                
    115         }
     111    @Override
     112    public void mouseEntered(MouseEvent arg0) {
     113        // TODO Auto-generated method stub
     114       
     115    }
    116116
    117117
    118         @Override
    119         public void mouseExited(MouseEvent arg0) {
    120                 // TODO Auto-generated method stub
    121                
    122         }
     118    @Override
     119    public void mouseExited(MouseEvent arg0) {
     120        // TODO Auto-generated method stub
     121       
     122    }
    123123
    124124
    125         @Override
    126         public void mousePressed(MouseEvent arg0) {
    127                 if (searchPattern.getSelectedText()==null) {
    128                         searchPattern.selectAll();
    129                 }
    130                
    131         }
     125    @Override
     126    public void mousePressed(MouseEvent arg0) {
     127        if (searchPattern.getSelectedText()==null) {
     128            searchPattern.selectAll();
     129        }
     130       
     131    }
    132132
    133133
    134         @Override
    135         public void mouseReleased(MouseEvent arg0) {
    136                 // TODO Auto-generated method stub
    137                
    138         }
     134    @Override
     135    public void mouseReleased(MouseEvent arg0) {
     136        // TODO Auto-generated method stub
     137       
     138    }
    139139}
  • applications/editors/josm/plugins/waypoint_search/src/org/openstreetmap/josm/plugins/waypointSearch/WaypointSearchPlugin.java

    r23180 r23190  
    1010
    1111public class WaypointSearchPlugin extends Plugin implements LayerChangeListener  {
    12         /**
     12    /**
    1313    * Will be invoked by JOSM to bootstrap the plugin
    1414    *
    1515    * @param info  information about the plugin and its local installation   
    1616    */
    17         private Engine engine = new Engine();
    18         private SelectWaypointDialog waypointDialog = new SelectWaypointDialog(tr("Waypoint search"), "ToolbarIcon", tr("Search after waypoint. Click and move the map view to the waypoint."), null, 100);
    19        
     17    private Engine engine = new Engine();
     18    private SelectWaypointDialog waypointDialog = new SelectWaypointDialog(tr("Waypoint search"), "ToolbarIcon", tr("Search after waypoint. Click and move the map view to the waypoint."), null, 100);
     19   
    2020    public WaypointSearchPlugin(PluginInformation info) {
    2121       super(info);
     
    2323    }
    2424     
    25         @Override
    26         public void activeLayerChange(Layer oldLayer, Layer newLayer) {
    27                 // TODO Auto-generated method stub
    28                
    29         }
     25    @Override
     26    public void activeLayerChange(Layer oldLayer, Layer newLayer) {
     27        // TODO Auto-generated method stub
     28       
     29    }
    3030
    3131       
     
    4444
    4545
    46         @Override
    47         public void layerRemoved(Layer oldLayer) {
    48                 if (!engine.gpxLayersExist()) {
    49                         waypointDialog.updateSearchResults();
    50                 }       
    51         }
     46    @Override
     47    public void layerRemoved(Layer oldLayer) {
     48        if (!engine.gpxLayersExist()) {
     49            waypointDialog.updateSearchResults();
     50        }   
     51    }
    5252 
    5353}
  • applications/editors/josm/plugins/wms-turbo-challenge2/src/wmsturbochallenge/EngineSound.java

    r19990 r23190  
    1717
    1818class engine {
    19         public engine() {
    20                 rpm = 0.0;
    21         }
     19    public engine() {
     20        rpm = 0.0;
     21    }
    2222
    23         public void start() {
    24                 rpm = 0.3;
    25                 speed = 0.0;
    26                 n = 0;
     23    public void start() {
     24        rpm = 0.3;
     25        speed = 0.0;
     26        n = 0;
    2727
    28                 if (output != null)
    29                         stop();
     28        if (output != null)
     29            stop();
    3030
    31                 AudioFormat output_format =
    32                         new AudioFormat(S_RATE, 16, 1, true, true);
    33                 DataLine.Info info =
    34                         new DataLine.Info(SourceDataLine.class, output_format);
     31        AudioFormat output_format =
     32            new AudioFormat(S_RATE, 16, 1, true, true);
     33        DataLine.Info info =
     34            new DataLine.Info(SourceDataLine.class, output_format);
    3535
    36                 /* Get the data line, open it and initialise the device */
    37                 try {
    38                         output = (SourceDataLine) AudioSystem.getLine(info);
    39                         output.open(output_format);
    40                         output.start();
    41                         frames_written = 0;
    42                         reschedule(0);
    43                 } catch (Exception e) {
    44                         output = null;
    45                         System.out.println("Audio not available: " +
    46                                         e.getClass().getSimpleName());
    47                 }
    48         }
     36        /* Get the data line, open it and initialise the device */
     37        try {
     38            output = (SourceDataLine) AudioSystem.getLine(info);
     39            output.open(output_format);
     40            output.start();
     41            frames_written = 0;
     42            reschedule(0);
     43        } catch (Exception e) {
     44            output = null;
     45            System.out.println("Audio not available: " +
     46                    e.getClass().getSimpleName());
     47        }
     48    }
    4949
    50         public void stop() {
    51                 rpm = 0.0;
    52                 n = 0;
     50    public void stop() {
     51        rpm = 0.0;
     52        n = 0;
    5353
    54                 if (output == null)
    55                         return;
     54        if (output == null)
     55            return;
    5656
    57                 tick.cancel();
    58                 tick.purge();
     57        tick.cancel();
     58        tick.purge();
    5959
    60                 output.stop();
    61                 output.flush();
    62                 output.close();
    63                 output = null;
    64         }
     60        output.stop();
     61        output.flush();
     62        output.close();
     63        output = null;
     64    }
    6565
    66         public void set_speed(double speed) {
    67                 /* This engine is equipped with an automatic gear box that
    68                 * switches gears when the RPM becomes too high or too low.  */
    69                 double new_speed = Math.abs(speed);
    70                 double accel = new_speed - this.speed;
    71                 this.speed = new_speed;
     66    public void set_speed(double speed) {
     67        /* This engine is equipped with an automatic gear box that
     68        * switches gears when the RPM becomes too high or too low.  */
     69        double new_speed = Math.abs(speed);
     70        double accel = new_speed - this.speed;
     71        this.speed = new_speed;
    7272
    73                 if (accel > 0.05)
    74                         accel = 0.05;
    75                 else if (accel < -0.05)
    76                         accel = -0.05;
    77                 rpm += accel;
     73        if (accel > 0.05)
     74            accel = 0.05;
     75        else if (accel < -0.05)
     76            accel = -0.05;
     77        rpm += accel;
    7878
    79                 if (accel > 0.0 && rpm > 1.0 + n * 0.2 && speed > 0.0) {
    80                         rpm = 0.3 + n * 0.2;
    81                         n ++;
    82                 } else if (accel < 0.0 && rpm < 0.3) {
    83                         if (n > 0) {
    84                                 rpm = 0.7 + n * 0.1;
    85                                 n --;
    86                         } else
    87                                 rpm = 0.2;
    88                 }
    89                 if (speed < 2.0)
    90                         n = 0;
    91         }
     79        if (accel > 0.0 && rpm > 1.0 + n * 0.2 && speed > 0.0) {
     80            rpm = 0.3 + n * 0.2;
     81            n ++;
     82        } else if (accel < 0.0 && rpm < 0.3) {
     83            if (n > 0) {
     84                rpm = 0.7 + n * 0.1;
     85                n --;
     86            } else
     87                rpm = 0.2;
     88        }
     89        if (speed < 2.0)
     90            n = 0;
     91    }
    9292
    93         public boolean is_on() {
    94                 return output != null;
    95         }
     93    public boolean is_on() {
     94        return output != null;
     95    }
    9696
    97         protected double speed;
    98         protected double rpm;
    99         protected int n;
     97    protected double speed;
     98    protected double rpm;
     99    protected int n;
    100100
    101         protected SourceDataLine output = null;
    102         protected long frames_written;
    103         protected Timer tick = new Timer();
     101    protected SourceDataLine output = null;
     102    protected long frames_written;
     103    protected Timer tick = new Timer();
    104104
    105         /* Audio parameters.  */
    106         protected static final int S_RATE = 44100;
    107         protected static final int MIN_BUFFER = 4096;
    108         protected static final double volume = 0.3;
     105    /* Audio parameters.  */
     106    protected static final int S_RATE = 44100;
     107    protected static final int MIN_BUFFER = 4096;
     108    protected static final double volume = 0.3;
    109109
    110         protected class audio_task extends TimerTask {
    111                 public void run() {
    112                         if (output == null)
    113                                 return;
     110    protected class audio_task extends TimerTask {
     111        public void run() {
     112            if (output == null)
     113                return;
    114114
    115                         /* If more than a two buffers left to play,
    116                         * reschedule and try to wake up closer to the
    117                         * end of already written data.  */
    118                         long frames_current = output.getLongFramePosition();
    119                         if (frames_current < frames_written - MIN_BUFFER * 2) {
    120                                 reschedule(frames_current);
    121                                 return;
    122                         }
     115            /* If more than a two buffers left to play,
     116            * reschedule and try to wake up closer to the
     117            * end of already written data.  */
     118            long frames_current = output.getLongFramePosition();
     119            if (frames_current < frames_written - MIN_BUFFER * 2) {
     120                reschedule(frames_current);
     121                return;
     122            }
    123123
    124                         /* Build a new buffer */
    125                         /* double freq = 20 * Math.pow(1.3, rpm * 5.0); */
    126                         double freq = (rpm - 0.1) * 160.0;
    127                         int wavelen = (int) (S_RATE / freq);
    128                         int bufferlen = MIN_BUFFER - (MIN_BUFFER % wavelen) +
    129                                 wavelen;
    130                         int value = (int) (0x7fff * volume);
     124            /* Build a new buffer */
     125            /* double freq = 20 * Math.pow(1.3, rpm * 5.0); */
     126            double freq = (rpm - 0.1) * 160.0;
     127            int wavelen = (int) (S_RATE / freq);
     128            int bufferlen = MIN_BUFFER - (MIN_BUFFER % wavelen) +
     129                wavelen;
     130            int value = (int) (0x7fff * volume);
    131131
    132                         bufferlen *= 2;
    133                         byte[] buffer = new byte[bufferlen];
    134                         for (int b = 0; b < bufferlen; ) {
    135                                 int j;
    136                                 for (j = wavelen / 2; j > 0; j --) {
    137                                         buffer[b ++] = (byte) (value >> 8);
    138                                         buffer[b ++] = (byte) (value & 0xff);
    139                                 }
    140                                 value = 0x10000 - value;
    141                                 for (j = wavelen - wavelen / 2; j > 0; j --) {
    142                                         buffer[b ++] = (byte) (value >> 8);
    143                                         buffer[b ++] = (byte) (value & 0xff);
    144                                 }
    145                                 value = 0x10000 - value;
    146                         }
     132            bufferlen *= 2;
     133            byte[] buffer = new byte[bufferlen];
     134            for (int b = 0; b < bufferlen; ) {
     135                int j;
     136                for (j = wavelen / 2; j > 0; j --) {
     137                    buffer[b ++] = (byte) (value >> 8);
     138                    buffer[b ++] = (byte) (value & 0xff);
     139                }
     140                value = 0x10000 - value;
     141                for (j = wavelen - wavelen / 2; j > 0; j --) {
     142                    buffer[b ++] = (byte) (value >> 8);
     143                    buffer[b ++] = (byte) (value & 0xff);
     144                }
     145                value = 0x10000 - value;
     146            }
    147147
    148                         frames_written +=
    149                                 output.write(buffer, 0, bufferlen) / 2;
     148            frames_written +=
     149                output.write(buffer, 0, bufferlen) / 2;
    150150
    151                         reschedule(frames_current);
    152                 }
    153         }
     151            reschedule(frames_current);
     152        }
     153    }
    154154
    155         protected void reschedule(long frames) {
    156                 /* Send a new buffer as close to the end of the
    157                 * currently playing buffer as possible (aim at
    158                 * about half into the last frame).  */
    159                 long delay = (frames_written - frames - MIN_BUFFER / 2) *
    160                         1000 / S_RATE;
    161                 if (delay < 0)
    162                         delay = 0;
    163                 tick.schedule(new audio_task(), delay);
    164         }
     155    protected void reschedule(long frames) {
     156        /* Send a new buffer as close to the end of the
     157        * currently playing buffer as possible (aim at
     158        * about half into the last frame).  */
     159        long delay = (frames_written - frames - MIN_BUFFER / 2) *
     160            1000 / S_RATE;
     161        if (delay < 0)
     162            delay = 0;
     163        tick.schedule(new audio_task(), delay);
     164    }
    165165}
  • applications/editors/josm/plugins/wms-turbo-challenge2/src/wmsturbochallenge/FakeMapView.java

    r21477 r23190  
    2626
    2727class fake_map_view extends MapView {
    28         public ProjectionBounds view_bounds;
    29         public MapView parent;
     28    public ProjectionBounds view_bounds;
     29    public MapView parent;
    3030
    31         public Graphics2D graphics;
    32         public BufferedImage ground_image;
    33         public int ground_width = -1;
    34         public int ground_height = -1;
    35         public double scale;
    36         public double max_east_west;
     31    public Graphics2D graphics;
     32    public BufferedImage ground_image;
     33    public int ground_width = -1;
     34    public int ground_height = -1;
     35    public double scale;
     36    public double max_east_west;
    3737
    38         public fake_map_view(MapView parent, double scale) {
    39                 super(null); //TODO MapView constructor contains registering listeners and other code, that probably shouldn't be called in fake map view
    40                 this.parent = parent;
    41                 this.scale = scale;
     38    public fake_map_view(MapView parent, double scale) {
     39        super(null); //TODO MapView constructor contains registering listeners and other code, that probably shouldn't be called in fake map view
     40        this.parent = parent;
     41        this.scale = scale;
    4242
    43                 ProjectionBounds parent_bounds = parent.getProjectionBounds();
    44                 max_east_west =
    45                         parent_bounds.max.east() - parent_bounds.min.east();
    46         }
     43        ProjectionBounds parent_bounds = parent.getProjectionBounds();
     44        max_east_west =
     45            parent_bounds.max.east() - parent_bounds.min.east();
     46    }
    4747
    48         public void setProjectionBounds(ProjectionBounds bounds) {
    49                 view_bounds = bounds;
     48    public void setProjectionBounds(ProjectionBounds bounds) {
     49        view_bounds = bounds;
    5050
    51                 if (bounds.max.east() - bounds.min.east() > max_east_west) {
    52                         max_east_west = bounds.max.east() - bounds.min.east();
     51        if (bounds.max.east() - bounds.min.east() > max_east_west) {
     52            max_east_west = bounds.max.east() - bounds.min.east();
    5353
    54                         /* We need to set the parent MapView's bounds (i.e.
    55                         * zoom level) to the same as ours max possible
    56                         * bounds to avoid WMSLayer thinking we're zoomed
    57                         * out more than we are or it'll pop up an annoying
    58                         * "requested area is too large" popup.
    59                         */
    60                         EastNorth parent_center = parent.getCenter();
    61                         parent.zoomTo(new ProjectionBounds(
    62                                         new EastNorth(
    63                                                 parent_center.east() -
    64                                                 max_east_west / 2,
    65                                                 parent_center.north()),
    66                                         new EastNorth(
    67                                                 parent_center.east() +
    68                                                 max_east_west / 2,
    69                                                 parent_center.north())));
     54            /* We need to set the parent MapView's bounds (i.e.
     55            * zoom level) to the same as ours max possible
     56            * bounds to avoid WMSLayer thinking we're zoomed
     57            * out more than we are or it'll pop up an annoying
     58            * "requested area is too large" popup.
     59            */
     60            EastNorth parent_center = parent.getCenter();
     61            parent.zoomTo(new ProjectionBounds(
     62                    new EastNorth(
     63                        parent_center.east() -
     64                        max_east_west / 2,
     65                        parent_center.north()),
     66                    new EastNorth(
     67                        parent_center.east() +
     68                        max_east_west / 2,
     69                        parent_center.north())));
    7070
    71                         /* Request again because NavigatableContent adds
    72                         * a border just to be sure.
    73                         */
    74                         ProjectionBounds new_bounds =
    75                                 parent.getProjectionBounds();
    76                         max_east_west =
    77                                 new_bounds.max.east() - new_bounds.min.east();
    78                 }
     71            /* Request again because NavigatableContent adds
     72            * a border just to be sure.
     73            */
     74            ProjectionBounds new_bounds =
     75                parent.getProjectionBounds();
     76            max_east_west =
     77                new_bounds.max.east() - new_bounds.min.east();
     78        }
    7979
    80                 Point vmin = getPoint(bounds.min);
    81                 Point vmax = getPoint(bounds.max);
    82                 int w = vmax.x + 1;
    83                 int h = vmin.y + 1;
     80        Point vmin = getPoint(bounds.min);
     81        Point vmax = getPoint(bounds.max);
     82        int w = vmax.x + 1;
     83        int h = vmin.y + 1;
    8484
    85                 if (w <= ground_width && h <= ground_height) {
    86                         graphics.setClip(0, 0, w, h);
    87                         return;
    88                 }
     85        if (w <= ground_width && h <= ground_height) {
     86            graphics.setClip(0, 0, w, h);
     87            return;
     88        }
    8989
    90                 if (w > ground_width)
    91                         ground_width = w;
    92                 if (h > ground_height)
    93                         ground_height = h;
     90        if (w > ground_width)
     91            ground_width = w;
     92        if (h > ground_height)
     93            ground_height = h;
    9494
    95                 ground_image = new BufferedImage(ground_width,
    96                                 ground_height,
    97                                 BufferedImage.TYPE_INT_RGB);
    98                 graphics = ground_image.createGraphics();
    99                 graphics.setClip(0, 0, w, h);
    100         }
     95        ground_image = new BufferedImage(ground_width,
     96                ground_height,
     97                BufferedImage.TYPE_INT_RGB);
     98        graphics = ground_image.createGraphics();
     99        graphics.setClip(0, 0, w, h);
     100    }
    101101
    102         public ProjectionBounds getProjectionBounds() {
    103                 return view_bounds;
    104         }
     102    public ProjectionBounds getProjectionBounds() {
     103        return view_bounds;
     104    }
    105105
    106         public Point getPoint(EastNorth p) {
    107                 double x = p.east() - view_bounds.min.east();
    108                 double y = view_bounds.max.north() - p.north();
    109                 x /= this.scale;
    110                 y /= this.scale;
     106    public Point getPoint(EastNorth p) {
     107        double x = p.east() - view_bounds.min.east();
     108        double y = view_bounds.max.north() - p.north();
     109        x /= this.scale;
     110        y /= this.scale;
    111111
    112                 return new Point((int) x, (int) y);
    113         }
     112        return new Point((int) x, (int) y);
     113    }
    114114
    115         public EastNorth getEastNorth(int x, int y) {
    116                 return new EastNorth(
    117                         view_bounds.min.east() + x * this.scale,
    118                         view_bounds.min.north() - y * this.scale);
    119         }
     115    public EastNorth getEastNorth(int x, int y) {
     116        return new EastNorth(
     117            view_bounds.min.east() + x * this.scale,
     118            view_bounds.min.north() - y * this.scale);
     119    }
    120120
    121         public boolean isVisible(int x, int y) {
    122                 return true;
    123         }
     121    public boolean isVisible(int x, int y) {
     122        return true;
     123    }
    124124
    125         public Graphics getGraphics() {
    126                 return graphics;
    127         }
     125    public Graphics getGraphics() {
     126        return graphics;
     127    }
    128128
    129         public void repaint() {
    130         }
     129    public void repaint() {
     130    }
    131131}
  • applications/editors/josm/plugins/wms-turbo-challenge2/src/wmsturbochallenge/GameWindow.java

    r19990 r23190  
    4242
    4343public class GameWindow extends JFrame implements ActionListener {
    44         public GameWindow(Layer ground) {
    45                 setTitle("The Ultimate WMS Super-speed Turbo Challenge II");
    46                 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    47                 setUndecorated(true);
    48                 setSize(s.getScreenSize().width, s.getScreenSize().height);
    49                 setLocationRelativeTo(null);
    50                 setResizable(false);
    51 
    52                 while (s.getScreenSize().width < width * scale ||
    53                                 s.getScreenSize().height < height * scale)
    54                         scale --;
    55                 add(panel);
    56 
    57                 setVisible(true);
    58 
    59                 /* TODO: "Intro" screen perhaps with "Hall of Fame" */
    60 
    61                 screen_image = new BufferedImage(width, height,
    62                                 BufferedImage.TYPE_INT_RGB);
    63                 screen = screen_image.getGraphics();
    64 
    65                 this.ground = ground;
    66                 ground_view = new fake_map_view(Main.map.mapView, 0.0000001);
    67 
    68                 /* Retrieve start position */
    69                 EastNorth start = ground_view.parent.getCenter();
    70                 lat = start.north();
    71                 lon = start.east();
    72 
    73                 addKeyListener(new TAdapter());
    74 
    75                 timer = new Timer(80, this);
    76                 timer.start();
    77 
    78                 car_gps = new gps();
    79                 car_gps.start();
    80 
    81                 car_engine = new engine();
    82                 car_engine.start();
    83 
    84                 for (int i = 0; i < maxsprites; i ++)
    85                         sprites[i] = new sprite_pos();
    86 
    87                 generate_sky();
    88         }
    89 
    90         protected engine car_engine;
    91 
    92         protected gps car_gps;
    93         protected class gps extends Timer implements ActionListener {
    94                 public gps() {
    95                         super(1000, null);
    96                         addActionListener(this);
    97 
    98                         trackSegs = new ArrayList<Collection<WayPoint>>();
    99                 }
    100 
    101                 protected Collection<WayPoint> segment;
    102                 protected Collection<Collection<WayPoint>> trackSegs;
    103 
    104                 public void actionPerformed(ActionEvent e) {
    105                         /* We should count the satellites here, see if we
    106                         * have a fix and add any distortions.  */
    107 
    108                         segment.add(new WayPoint(Main.proj.eastNorth2latlon(
    109                                         new EastNorth(lon, lat))));
    110                 }
    111 
    112                 public void start() {
    113                         super.start();
    114 
    115                         /* Start recording */
    116                         segment = new ArrayList<WayPoint>();
    117                         trackSegs.add(segment);
    118                         actionPerformed(null);
    119                 }
    120 
    121                 public void save_trace() {
    122                         int len = 0;
    123                         for (Collection<WayPoint> seg : trackSegs)
    124                                 len += seg.size();
    125 
    126                         /* Don't save traces shorter than 5s */
    127                         if (len <= 5)
    128                                 return;
    129 
    130                         GpxData data = new GpxData();
    131                         data.tracks.add(new ImmutableGpxTrack(trackSegs,
    132                                                 new HashMap<String, Object>()));
    133 
    134                         ground_view.parent.addLayer(
    135                                         new GpxLayer(data, "Car GPS trace"));
    136                 }
    137         }
    138 
    139         /* These are EastNorth, not actual LatLon */
    140         protected double lat, lon;
    141         /* Camera's altitude above surface (same units as lat/lon above) */
    142         protected double ele = 0.000003;
    143         /* Cut off at ~75px from bottom of the screen */
    144         protected double horizon = 0.63;
    145         /* Car's distance from the camera lens */
    146         protected double cardist = ele * 3;
    147 
    148         /* Pixels per pixel, the bigger the more oldschool :-)  */
    149         protected int scale = 5;
    150 
    151         protected BufferedImage screen_image;
    152         protected Graphics screen;
    153         protected int width = 320;
    154         protected int height = 200;
    155         protected int centre = width / 2;
    156 
    157         double maxdist = ele / (horizon - 0.6);
    158         double realwidth = maxdist * width / height;
    159         double pixelperlat = 1.0 * width / realwidth;
    160         double sratio = 0.85;
    161         protected int sw = (int) (2 * Math.PI * maxdist * pixelperlat * sratio);
    162 
    163         /* TODO: figure out how to load these dynamically after splash
    164         * screen is shown */
    165         protected static final ImageIcon car[] = new ImageIcon[] {
    166                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    167                                         WMSRacer.class.getResource(
    168                                                 "/images/car0-l.png"))),
    169                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    170                                         WMSRacer.class.getResource(
    171                                                 "/images/car0.png"))),
    172                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    173                                         WMSRacer.class.getResource(
    174                                                 "/images/car0-r.png"))),
    175                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    176                                         WMSRacer.class.getResource(
    177                                                 "/images/car1-l.png"))),
    178                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    179                                         WMSRacer.class.getResource(
    180                                                 "/images/car1.png"))),
    181                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    182                                         WMSRacer.class.getResource(
    183                                                 "/images/car1-r.png"))),
    184         };
    185         protected static final ImageIcon bg[] = new ImageIcon[] {
    186                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    187                                         WMSRacer.class.getResource(
    188                                                 "/images/bg0.png"))),
    189         };
    190         protected static final ImageIcon skyline[] = new ImageIcon[] {
    191                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    192                                         WMSRacer.class.getResource(
    193                                                 "/images/horizon.png"))),
    194         };
    195         protected static final ImageIcon cactus[] = new ImageIcon[] {
    196                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    197                                         WMSRacer.class.getResource(
    198                                                 "/images/cactus0.png"))),
    199                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    200                                         WMSRacer.class.getResource(
    201                                                 "/images/cactus1.png"))),
    202                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    203                                         WMSRacer.class.getResource(
    204                                                 "/images/cactus2.png"))),
    205         };
    206         protected static final ImageIcon cloud[] = new ImageIcon[] {
    207                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    208                                         WMSRacer.class.getResource(
    209                                                 "/images/cloud0.png"))),
    210                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    211                                         WMSRacer.class.getResource(
    212                                                 "/images/cloud1.png"))),
    213                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    214                                         WMSRacer.class.getResource(
    215                                                 "/images/cloud2.png"))),
    216                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    217                                         WMSRacer.class.getResource(
    218                                                 "/images/cloud3.png"))),
    219                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    220                                         WMSRacer.class.getResource(
    221                                                 "/images/cloud4.png"))),
    222         };
    223         protected static final ImageIcon aircraft[] = new ImageIcon[] {
    224                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(
    225                                         WMSRacer.class.getResource(
    226                                                 "/images/aircraft0.png"))),
    227         };
    228         protected static final ImageIcon loading = new ImageIcon(
    229                         Toolkit.getDefaultToolkit().createImage(
    230                                         WMSRacer.class.getResource(
    231                                                 "/images/loading.png")));
    232         protected static Toolkit s = Toolkit.getDefaultToolkit();
    233         protected int current_bg = 0;
    234         protected int current_car = 0;
    235         protected boolean cacti_on = true;
    236         protected List<EastNorth> cacti = new ArrayList<EastNorth>();
    237         protected List<EastNorth> todelete = new ArrayList<EastNorth>();
    238         protected int splashframe = -1;
    239         protected EastNorth splashcactus;
    240 
    241         protected Layer ground;
    242         protected double heading = 0.0;
    243         protected double wheelangle = 0.0;
    244         protected double speed = 0.0;
    245         protected boolean key_down[] = new boolean[] {
    246                 false, false, false, false, };
    247 
    248         protected void move() {
    249                 /* Left */
    250                 /* (At high speeds make more gentle turns) */
    251                 if (key_down[0])
    252                         wheelangle -= 0.1 / (1.0 + Math.abs(speed));
    253                 /* Right */
    254                 if (key_down[1])
    255                         wheelangle += 0.1 / (1.0 + Math.abs(speed));
    256                 if (wheelangle > 0.3)
    257                         wheelangle = 0.3; /* Radians */
    258                 if (wheelangle < -0.3)
    259                         wheelangle = -0.3;
    260 
    261                 wheelangle *= 0.7;
    262 
    263                 /* Up */
    264                 if (key_down[2])
    265                         speed += speed >= 0.0 ? 1.0 / (2.0 + speed) : 0.5;
    266                 /* Down */
    267                 if (key_down[3]) {
    268                         if (speed >= 0.5) /* Brake (TODO: sound) */
    269                                 speed -= 0.5;
    270                         else if (speed >= 0.01) /* Brake (TODO: sound) */
    271                                 speed = 0.0;
    272                         else /* Reverse */
    273                                 speed -= 0.5 / (4.0 - speed);
    274                 }
    275 
    276                 speed *= 0.97;
    277                 car_engine.set_speed(speed);
    278 
    279                 if (speed > -0.1 && speed < 0.1)
    280                         speed = 0;
    281 
    282                 heading += wheelangle * speed;
    283 
    284                 boolean chop = false;
    285                 double newlat = lat + Math.cos(heading) * speed * ele * 0.2;
    286                 double newlon = lon + Math.sin(heading) * speed * ele * 0.2;
    287                 for (EastNorth pos : cacti) {
    288                         double alat = Math.abs(pos.north() - newlat);
    289                         double alon = Math.abs(pos.east() - newlon);
    290                         if (alat + alon < ele * 1.0) {
    291                                 if (Math.abs(speed) < 2.0) {
    292                                         if (speed > 0.0)
    293                                                 speed = -0.5;
    294                                         else
    295                                                 speed = 0.3;
    296                                         newlat = lat;
    297                                         newlon = lon;
    298                                         break;
    299                                 }
    300 
    301                                 chop = true;
    302                                 splashframe = 0;
    303                                 splashcactus = pos;
    304                                 todelete.add(pos);
    305                         }
    306                 }
    307 
    308                 lat = newlat;
    309                 lon = newlon;
    310 
    311                 /* Seed a new cactus if we're moving.
    312                 * TODO: hook into data layers and avoid putting the cactus on
    313                 * the road!
    314                 */
    315                 if (cacti_on && Math.random() * 30.0 < speed) {
    316                         double left_x = maxdist * (width - centre) / height;
    317                         double right_x = maxdist * (0 - centre) / height;
    318                         double x = left_x + Math.random() * (right_x - left_x);
    319                         double clat = lat + (maxdist - cardist) *
    320                                 Math.cos(heading) - x * Math.sin(heading);
    321                         double clon = lon + (maxdist - cardist) *
    322                                 Math.sin(heading) + x * Math.cos(heading);
    323 
    324                         cacti.add(new EastNorth(clon, clat));
    325                         chop = true;
    326                 }
    327 
    328                 /* Chop down any cactus far enough that it can't
    329                 * be seen.  ``If a cactus falls in a forest and
    330                 * there is nobody around did it make a sound?''
    331                 */
    332                 if (chop) {
    333                         for (EastNorth pos : cacti) {
    334                                 double alat = Math.abs(pos.north() - lat);
    335                                 double alon = Math.abs(pos.east() - lon);
    336                                 if (alat + alon > 2 * maxdist)
    337                                         todelete.add(pos);
    338                         }
    339                         cacti.removeAll(todelete);
    340                         todelete = new ArrayList<EastNorth>();
    341                 }
    342         }
    343 
    344         int frame;
    345         boolean downloading = false;
    346         protected void screen_repaint() {
    347                 /* Draw background first */
    348                 sky_paint();
    349 
    350                 /* On top of it project the floor */
    351                 ground_paint();
    352 
    353                 /* Messages */
    354                 frame ++;
    355                 if ((frame & 8) == 0 && downloading)
    356                         screen.drawImage(loading.getImage(), centre -
    357                                         loading.getIconWidth() / 2, 50, this);
    358 
    359                 /* Sprites */
    360                 sprites_paint();
    361         }
    362 
    363         static double max3(double x[]) {
    364                 return x[0] > x[1] ? x[2] > x[0] ? x[2] : x[0] :
    365                         (x[2] > x[1] ? x[2] : x[1]);
    366         }
    367         static double min3(double x[]) {
    368                 return x[0] < x[1] ? x[2] < x[0] ? x[2] : x[0] :
    369                         (x[2] < x[1] ? x[2] : x[1]);
    370         }
    371 
    372         protected void ground_paint() {
    373                 double sin = Math.sin(heading);
    374                 double cos = Math.cos(heading);
    375 
    376                 /* First calculate the bounding box for the visible area.
    377                 * The area will be (nearly) a triangle, so calculate the
    378                 * EastNorth for the three corners and make a bounding box.
    379                 */
    380                 double left_x = maxdist * (width - centre) / height;
    381                 double right_x = maxdist * (0 - centre) / height;
    382                 double e_lat[] = new double[] {
    383                         lat + (maxdist - cardist) * cos - left_x * sin,
    384                         lat + (maxdist - cardist) * cos - right_x * sin,
    385                         lat - cardist * cos, };
    386                 double e_lon[] = new double[] {
    387                         lon + (maxdist - cardist) * sin + left_x * cos,
    388                         lon + (maxdist - cardist) * sin + right_x * cos,
    389                         lon - cardist * sin, };
    390                 ground_view.setProjectionBounds(new ProjectionBounds(
    391                                 new EastNorth(min3(e_lon), min3(e_lat)),
    392                                 new EastNorth(max3(e_lon), max3(e_lat))));
    393 
    394                 /* If the layer is a WMS layer, check if any tiles are
    395                 * missing */
    396                 if (ground instanceof wmsplugin.WMSLayer) {
    397                         wmsplugin.WMSLayer wms = (wmsplugin.WMSLayer) ground;
    398                         downloading = wms.hasAutoDownload() && (
    399                                         null == wms.findImage(new EastNorth(
    400                                                         e_lon[0], e_lat[0])) ||
    401                                         null == wms.findImage(new EastNorth(
    402                                                         e_lon[0], e_lat[0])) ||
    403                                         null == wms.findImage(new EastNorth(
    404                                                         e_lon[0], e_lat[0])));
    405                 }
    406 
    407                 /* Request the image from ground layer */
    408                 ground.paint(ground_view.graphics, ground_view, null);
    409 
    410                 for (int y = (int) (height * horizon + 0.1); y < height; y ++) {
    411                         /* Assume a 60 deg vertical Field of View when
    412                         * calculating the distance at given pixel.  */
    413                         double dist = ele / (1.0 * y / height - 0.6);
    414                         double lat_off = lat + (dist - cardist) * cos;
    415                         double lon_off = lon + (dist - cardist) * sin;
    416 
    417                         for (int x = 0; x < width; x ++) {
    418                                 double p_x = dist * (x - centre) / height;
    419 
    420                                 EastNorth en = new EastNorth(
    421                                                 lon_off + p_x * cos,
    422                                                 lat_off - p_x * sin);
    423 
    424                                 Point pt = ground_view.getPoint(en);
    425 
    426                                 int rgb = ground_view.ground_image.getRGB(
    427                                                 pt.x, pt.y);
    428                                 screen_image.setRGB(x, y, rgb);
    429                         }
    430                 }
    431         }
    432 
    433         protected BufferedImage sky_image;
    434         protected Graphics sky;
    435         public void generate_sky() {
    436                 sky_image = new BufferedImage(sw, 70,
    437                                 BufferedImage.TYPE_INT_ARGB);
    438                 sky = sky_image.getGraphics();
    439 
    440                 int n = (int) (Math.random() * sw * 0.03);
    441                 for (int i = 0; i < n; i ++) {
    442                         int t = (int) (Math.random() * 5.0);
    443                         int x = (int) (Math.random() *
    444                                         (sw - cloud[t].getIconWidth()));
    445                         int y = (int) ((1 - Math.random() * Math.random()) *
    446                                         (70 - cloud[t].getIconHeight()));
    447                         sky.drawImage(cloud[t].getImage(), x, y, this);
    448                 }
    449 
    450                 if (Math.random() < 0.5) {
    451                         int t = 0;
    452                         int x = (int) (300 + Math.random() * (sw - 500 -
    453                                                 aircraft[t].getIconWidth()));
    454                         sky.drawImage(aircraft[t].getImage(), x, 0, this);
    455                 }
    456         }
    457 
    458         public void sky_paint() {
    459                 /* for x -> 0, lim sin(x) / x = 1 */
    460                 int hx = (int) (-heading * maxdist * pixelperlat);
    461                 int hw = skyline[current_bg].getIconWidth();
    462                 hx = ((hx % hw) - hw) % hw;
    463 
    464                 int sx = (int) (-heading * maxdist * pixelperlat * sratio);
    465                 sx = ((sx % sw) - sw) % sw;
    466 
    467                 screen.drawImage(bg[current_bg].getImage(), 0, 0, this);
    468                 screen.drawImage(sky_image, sx, 50, this);
    469                 if (sw + sx < width)
    470                         screen.drawImage(sky_image, sx + sw, 50, this);
    471                 screen.drawImage(skyline[current_bg].getImage(), hx, 66, this);
    472                 if (hw + hx < width)
    473                         screen.drawImage(skyline[current_bg].getImage(),
    474                                         hx + hw, 66, this);
    475         }
    476 
    477         protected class sprite_pos implements Comparable {
    478                 double dist;
    479 
    480                 int x, y, sx, sy;
    481                 Image sprite;
    482 
    483                 public sprite_pos() {
    484                 }
    485 
    486                 public int compareTo(Object x) {
    487                         sprite_pos other = (sprite_pos) x;
    488                         return (int) ((other.dist - this.dist) * 1000000.0);
    489                 }
    490         }
    491 
    492         /* sizes decides how many zoom levels the sprites have.  We
    493         * could do just normal scalling according to distance but
    494         * that's not what old games did, they had prescaled sprites
    495         * for the different distances and you could see the feature
    496         * grow discretely as you approached it.  */
    497         protected final static int sizes = 8;
    498 
    499         protected final static int maxsprites = 32;
    500         protected sprite_pos sprites[] = new sprite_pos[maxsprites];
    501 
    502         protected void sprites_paint() {
    503                 /* The vehicle */
    504                 int orientation = (wheelangle > -0.02 ? wheelangle < 0.02 ?
    505                                 1 : 2 : 0) + current_car * 3;
    506                 sprites[0].sprite = car[orientation].getImage();
    507                 sprites[0].dist = cardist;
    508                 sprites[0].sx = car[orientation].getIconWidth();
    509                 sprites[0].x = centre - sprites[0].sx / 2;
    510                 sprites[0].sy = car[orientation].getIconHeight();
    511                 sprites[0].y = height - sprites[0].sy - 10; /* TODO */
    512 
    513                 /* The cacti */
    514                 double sin = Math.sin(-heading);
    515                 double cos = Math.cos(-heading);
    516                 int i = 1;
    517 
    518                 for (EastNorth ll : cacti) {
    519                         double clat = ll.north() - lat;
    520                         double clon = ll.east() - lon;
    521                         double dist = (clat * cos - clon * sin) + cardist;
    522                         double p_x = clat * sin + clon * cos;
    523 
    524                         if (dist * 8 <= cardist || dist > maxdist)
    525                                 continue;
    526 
    527                         int x = (int) (p_x * height / dist + centre);
    528                         int y = (int) ((ele / dist + 0.6) * height);
    529 
    530                         if (i >= maxsprites)
    531                                 break;
    532                         if (x < -10 || x > width + 10)
    533                                 continue;
    534 
    535                         int type = (((int) (ll.north() * 10000000.0) & 31) % 3);
    536                         int sx = cactus[type].getIconWidth();
    537                         int sy = cactus[type].getIconHeight();
    538 
    539                         sprite_pos pos = sprites[i ++];
    540                         pos.dist = dist;
    541                         pos.sprite = cactus[type].getImage();
    542                         pos.sx = (int) (sx * cardist * 0.7 / dist);
    543                         pos.sy = (int) (sy * cardist * 0.7 / dist);
    544                         pos.x = x - pos.sx / 2;
    545                         pos.y = y - pos.sy;
    546                 }
    547 
    548                 Arrays.sort(sprites, 0, i);
    549                 for (sprite_pos sprite : sprites)
    550                         if (i --> 0)
    551                                 screen.drawImage(sprite.sprite,
    552                                                 sprite.x, sprite.y,
    553                                                 sprite.sx, sprite.sy, this);
    554                         else
    555                                 break;
    556 
    557                 if (splashframe >= 0) {
    558                         splashframe ++;
    559                         if (splashframe >= 8)
    560                                 splashframe = -1;
    561 
    562                         int type = (((int) (splashcactus.north() *
    563                                                         10000000.0) & 31) % 3);
    564                         int sx = cactus[type].getIconWidth();
    565                         int sy = cactus[type].getIconHeight();
    566                         Image image = cactus[type].getImage();
    567 
    568                         for (i = 0; i < 50; i ++) {
    569                                 int x = (int) (Math.random() * sx);
    570                                 int y = (int) (Math.random() * sy);
    571                                 int w = (int) (Math.random() * 20);
    572                                 int h = (int) (Math.random() * 20);
    573                                 int nx = centre + splashframe * (x - sx / 2);
    574                                 int ny = height - splashframe * (sy - y);
    575                                 int nw = w + splashframe;
    576                                 int nh = h + splashframe;
    577 
    578                                 screen.drawImage(image,
    579                                                 nx, ny, nx + nw, ny + nh,
    580                                                 x, y, x + w, y + h, this);
    581                         }
    582                 }
    583         }
    584 
    585         public boolean no_super_repaint = false;
    586         protected class GamePanel extends JPanel {
    587                 public GamePanel() {
    588                         setBackground(Color.BLACK);
    589                         setDoubleBuffered(true);
    590                 }
    591 
    592                 public void paint(Graphics g) {
    593                         int w = (int) getSize().getWidth();
    594                         int h = (int) getSize().getHeight();
    595 
    596                         if (no_super_repaint)
    597                                 no_super_repaint = false;
    598                         else
    599                                 super.paint(g);
    600 
    601                         g.drawImage(screen_image, (w - width * scale) / 2,
    602                                         (h - height * scale) / 2,
    603                                         width * scale, height * scale, this);
    604 
    605                         Toolkit.getDefaultToolkit().sync();
    606                 }
    607         }
    608         JPanel panel = new GamePanel();
    609 
    610         protected void quit() {
    611                 timer.stop();
    612 
    613                 car_engine.stop();
    614 
    615                 car_gps.stop();
    616                 car_gps.save_trace();
    617 
    618                 setVisible(false);
    619                 panel = null;
    620                 screen_image = null;
    621                 screen = null;
    622                 dispose();
    623         }
    624 
    625         /*
    626         * Supposedly a thread drawing frames and sleeping in a loop is
    627         * better than for animating than swing Timers.  For the moment
    628         * I'll use a timer because I don't want to deal with all the
    629         * potential threading issues.
    630         */
    631         protected Timer timer;
    632         public void actionPerformed(ActionEvent e) {
    633                 move();
    634                 screen_repaint();
    635 
    636                 no_super_repaint = true;
    637                 panel.repaint();
    638         }
    639 
    640         protected class TAdapter extends KeyAdapter {
    641                 public void keyPressed(KeyEvent e) {
    642                         int key = e.getKeyCode();
    643 
    644                         if (key == KeyEvent.VK_LEFT && !key_down[0]) {
    645                                 wheelangle -= 0.02;
    646                                 key_down[0] = true;
    647                         }
    648 
    649                         if (key == KeyEvent.VK_RIGHT && !key_down[1]) {
    650                                 wheelangle += 0.02;
    651                                 key_down[1] = true;
    652                         }
    653 
    654                         if (key == KeyEvent.VK_UP)
    655                                 key_down[2] = true;
    656 
    657                         if (key == KeyEvent.VK_DOWN)
    658                                 key_down[3] = true;
    659 
    660                         if (key == KeyEvent.VK_ESCAPE)
    661                                 quit();
    662 
    663                         /* Toggle sound */
    664                         if (key == KeyEvent.VK_S) {
    665                                 if (car_engine.is_on())
    666                                         car_engine.stop();
    667                                 else
    668                                         car_engine.start();
    669                         }
    670 
    671                         /* Toggle cacti */
    672                         if (key == KeyEvent.VK_C) {
    673                                 cacti_on = !cacti_on;
    674                                 if (!cacti_on)
    675                                         cacti = new ArrayList<EastNorth>();
    676                         }
    677 
    678                         /* Switch vehicle */
    679                         if (key == KeyEvent.VK_V)
    680                                 if (current_car ++>= 1)
    681                                         current_car = 0;
    682                 }
    683 
    684                 public void keyReleased(KeyEvent e) {
    685                         int key = e.getKeyCode();
    686 
    687                         if (key == KeyEvent.VK_LEFT)
    688                                 key_down[0] = false;
    689 
    690                         if (key == KeyEvent.VK_RIGHT)
    691                                 key_down[1] = false;
    692 
    693                         if (key == KeyEvent.VK_UP)
    694                                 key_down[2] = false;
    695 
    696                         if (key == KeyEvent.VK_DOWN)
    697                                 key_down[3] = false;
    698                 }
    699         }
    700         protected fake_map_view ground_view;
     44    public GameWindow(Layer ground) {
     45        setTitle("The Ultimate WMS Super-speed Turbo Challenge II");
     46        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
     47        setUndecorated(true);
     48        setSize(s.getScreenSize().width, s.getScreenSize().height);
     49        setLocationRelativeTo(null);
     50        setResizable(false);
     51
     52        while (s.getScreenSize().width < width * scale ||
     53                s.getScreenSize().height < height * scale)
     54            scale --;
     55        add(panel);
     56
     57        setVisible(true);
     58
     59        /* TODO: "Intro" screen perhaps with "Hall of Fame" */
     60
     61        screen_image = new BufferedImage(width, height,
     62                BufferedImage.TYPE_INT_RGB);
     63        screen = screen_image.getGraphics();
     64
     65        this.ground = ground;
     66        ground_view = new fake_map_view(Main.map.mapView, 0.0000001);
     67
     68        /* Retrieve start position */
     69        EastNorth start = ground_view.parent.getCenter();
     70        lat = start.north();
     71        lon = start.east();
     72
     73        addKeyListener(new TAdapter());
     74
     75        timer = new Timer(80, this);
     76        timer.start();
     77
     78        car_gps = new gps();
     79        car_gps.start();
     80
     81        car_engine = new engine();
     82        car_engine.start();
     83
     84        for (int i = 0; i < maxsprites; i ++)
     85            sprites[i] = new sprite_pos();
     86
     87        generate_sky();
     88    }
     89
     90    protected engine car_engine;
     91
     92    protected gps car_gps;
     93    protected class gps extends Timer implements ActionListener {
     94        public gps() {
     95            super(1000, null);
     96            addActionListener(this);
     97
     98            trackSegs = new ArrayList<Collection<WayPoint>>();
     99        }
     100
     101        protected Collection<WayPoint> segment;
     102        protected Collection<Collection<WayPoint>> trackSegs;
     103
     104        public void actionPerformed(ActionEvent e) {
     105            /* We should count the satellites here, see if we
     106            * have a fix and add any distortions.  */
     107
     108            segment.add(new WayPoint(Main.proj.eastNorth2latlon(
     109                    new EastNorth(lon, lat))));
     110        }
     111
     112        public void start() {
     113            super.start();
     114
     115            /* Start recording */
     116            segment = new ArrayList<WayPoint>();
     117            trackSegs.add(segment);
     118            actionPerformed(null);
     119        }
     120
     121        public void save_trace() {
     122            int len = 0;
     123            for (Collection<WayPoint> seg : trackSegs)
     124                len += seg.size();
     125
     126            /* Don't save traces shorter than 5s */
     127            if (len <= 5)
     128                return;
     129
     130            GpxData data = new GpxData();
     131            data.tracks.add(new ImmutableGpxTrack(trackSegs,
     132                        new HashMap<String, Object>()));
     133
     134            ground_view.parent.addLayer(
     135                    new GpxLayer(data, "Car GPS trace"));
     136        }
     137    }
     138
     139    /* These are EastNorth, not actual LatLon */
     140    protected double lat, lon;
     141    /* Camera's altitude above surface (same units as lat/lon above) */
     142    protected double ele = 0.000003;
     143    /* Cut off at ~75px from bottom of the screen */
     144    protected double horizon = 0.63;
     145    /* Car's distance from the camera lens */
     146    protected double cardist = ele * 3;
     147
     148    /* Pixels per pixel, the bigger the more oldschool :-)  */
     149    protected int scale = 5;
     150
     151    protected BufferedImage screen_image;
     152    protected Graphics screen;
     153    protected int width = 320;
     154    protected int height = 200;
     155    protected int centre = width / 2;
     156
     157    double maxdist = ele / (horizon - 0.6);
     158    double realwidth = maxdist * width / height;
     159    double pixelperlat = 1.0 * width / realwidth;
     160    double sratio = 0.85;
     161    protected int sw = (int) (2 * Math.PI * maxdist * pixelperlat * sratio);
     162
     163    /* TODO: figure out how to load these dynamically after splash
     164    * screen is shown */
     165    protected static final ImageIcon car[] = new ImageIcon[] {
     166            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     167                    WMSRacer.class.getResource(
     168                        "/images/car0-l.png"))),
     169            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     170                    WMSRacer.class.getResource(
     171                        "/images/car0.png"))),
     172            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     173                    WMSRacer.class.getResource(
     174                        "/images/car0-r.png"))),
     175            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     176                    WMSRacer.class.getResource(
     177                        "/images/car1-l.png"))),
     178            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     179                    WMSRacer.class.getResource(
     180                        "/images/car1.png"))),
     181            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     182                    WMSRacer.class.getResource(
     183                        "/images/car1-r.png"))),
     184    };
     185    protected static final ImageIcon bg[] = new ImageIcon[] {
     186            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     187                    WMSRacer.class.getResource(
     188                        "/images/bg0.png"))),
     189    };
     190    protected static final ImageIcon skyline[] = new ImageIcon[] {
     191            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     192                    WMSRacer.class.getResource(
     193                        "/images/horizon.png"))),
     194    };
     195    protected static final ImageIcon cactus[] = new ImageIcon[] {
     196            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     197                    WMSRacer.class.getResource(
     198                        "/images/cactus0.png"))),
     199            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     200                    WMSRacer.class.getResource(
     201                        "/images/cactus1.png"))),
     202            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     203                    WMSRacer.class.getResource(
     204                        "/images/cactus2.png"))),
     205    };
     206    protected static final ImageIcon cloud[] = new ImageIcon[] {
     207            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     208                    WMSRacer.class.getResource(
     209                        "/images/cloud0.png"))),
     210            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     211                    WMSRacer.class.getResource(
     212                        "/images/cloud1.png"))),
     213            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     214                    WMSRacer.class.getResource(
     215                        "/images/cloud2.png"))),
     216            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     217                    WMSRacer.class.getResource(
     218                        "/images/cloud3.png"))),
     219            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     220                    WMSRacer.class.getResource(
     221                        "/images/cloud4.png"))),
     222    };
     223    protected static final ImageIcon aircraft[] = new ImageIcon[] {
     224            new ImageIcon(Toolkit.getDefaultToolkit().createImage(
     225                    WMSRacer.class.getResource(
     226                        "/images/aircraft0.png"))),
     227    };
     228    protected static final ImageIcon loading = new ImageIcon(
     229            Toolkit.getDefaultToolkit().createImage(
     230                    WMSRacer.class.getResource(
     231                        "/images/loading.png")));
     232    protected static Toolkit s = Toolkit.getDefaultToolkit();
     233    protected int current_bg = 0;
     234    protected int current_car = 0;
     235    protected boolean cacti_on = true;
     236    protected List<EastNorth> cacti = new ArrayList<EastNorth>();
     237    protected List<EastNorth> todelete = new ArrayList<EastNorth>();
     238    protected int splashframe = -1;
     239    protected EastNorth splashcactus;
     240
     241    protected Layer ground;
     242    protected double heading = 0.0;
     243    protected double wheelangle = 0.0;
     244    protected double speed = 0.0;
     245    protected boolean key_down[] = new boolean[] {
     246        false, false, false, false, };
     247
     248    protected void move() {
     249        /* Left */
     250        /* (At high speeds make more gentle turns) */
     251        if (key_down[0])
     252            wheelangle -= 0.1 / (1.0 + Math.abs(speed));
     253        /* Right */
     254        if (key_down[1])
     255            wheelangle += 0.1 / (1.0 + Math.abs(speed));
     256        if (wheelangle > 0.3)
     257            wheelangle = 0.3; /* Radians */
     258        if (wheelangle < -0.3)
     259            wheelangle = -0.3;
     260
     261        wheelangle *= 0.7;
     262
     263        /* Up */
     264        if (key_down[2])
     265            speed += speed >= 0.0 ? 1.0 / (2.0 + speed) : 0.5;
     266        /* Down */
     267        if (key_down[3]) {
     268            if (speed >= 0.5) /* Brake (TODO: sound) */
     269                speed -= 0.5;
     270            else if (speed >= 0.01) /* Brake (TODO: sound) */
     271                speed = 0.0;
     272            else /* Reverse */
     273                speed -= 0.5 / (4.0 - speed);
     274        }
     275
     276        speed *= 0.97;
     277        car_engine.set_speed(speed);
     278
     279        if (speed > -0.1 && speed < 0.1)
     280            speed = 0;
     281
     282        heading += wheelangle * speed;
     283
     284        boolean chop = false;
     285        double newlat = lat + Math.cos(heading) * speed * ele * 0.2;
     286        double newlon = lon + Math.sin(heading) * speed * ele * 0.2;
     287        for (EastNorth pos : cacti) {
     288            double alat = Math.abs(pos.north() - newlat);
     289            double alon = Math.abs(pos.east() - newlon);
     290            if (alat + alon < ele * 1.0) {
     291                if (Math.abs(speed) < 2.0) {
     292                    if (speed > 0.0)
     293                        speed = -0.5;
     294                    else
     295                        speed = 0.3;
     296                    newlat = lat;
     297                    newlon = lon;
     298                    break;
     299                }
     300
     301                chop = true;
     302                splashframe = 0;
     303                splashcactus = pos;
     304                todelete.add(pos);
     305            }
     306        }
     307
     308        lat = newlat;
     309        lon = newlon;
     310
     311        /* Seed a new cactus if we're moving.
     312        * TODO: hook into data layers and avoid putting the cactus on
     313        * the road!
     314        */
     315        if (cacti_on && Math.random() * 30.0 < speed) {
     316            double left_x = maxdist * (width - centre) / height;
     317            double right_x = maxdist * (0 - centre) / height;
     318            double x = left_x + Math.random() * (right_x - left_x);
     319            double clat = lat + (maxdist - cardist) *
     320                Math.cos(heading) - x * Math.sin(heading);
     321            double clon = lon + (maxdist - cardist) *
     322                Math.sin(heading) + x * Math.cos(heading);
     323
     324            cacti.add(new EastNorth(clon, clat));
     325            chop = true;
     326        }
     327
     328        /* Chop down any cactus far enough that it can't
     329        * be seen.  ``If a cactus falls in a forest and
     330        * there is nobody around did it make a sound?''
     331        */
     332        if (chop) {
     333            for (EastNorth pos : cacti) {
     334                double alat = Math.abs(pos.north() - lat);
     335                double alon = Math.abs(pos.east() - lon);
     336                if (alat + alon > 2 * maxdist)
     337                    todelete.add(pos);
     338            }
     339            cacti.removeAll(todelete);
     340            todelete = new ArrayList<EastNorth>();
     341        }
     342    }
     343
     344    int frame;
     345    boolean downloading = false;
     346    protected void screen_repaint() {
     347        /* Draw background first */
     348        sky_paint();
     349
     350        /* On top of it project the floor */
     351        ground_paint();
     352
     353        /* Messages */
     354        frame ++;
     355        if ((frame & 8) == 0 && downloading)
     356            screen.drawImage(loading.getImage(), centre -
     357                    loading.getIconWidth() / 2, 50, this);
     358
     359        /* Sprites */
     360        sprites_paint();
     361    }
     362
     363    static double max3(double x[]) {
     364        return x[0] > x[1] ? x[2] > x[0] ? x[2] : x[0] :
     365            (x[2] > x[1] ? x[2] : x[1]);
     366    }
     367    static double min3(double x[]) {
     368        return x[0] < x[1] ? x[2] < x[0] ? x[2] : x[0] :
     369            (x[2] < x[1] ? x[2] : x[1]);
     370    }
     371
     372    protected void ground_paint() {
     373        double sin = Math.sin(heading);
     374        double cos = Math.cos(heading);
     375
     376        /* First calculate the bounding box for the visible area.
     377        * The area will be (nearly) a triangle, so calculate the
     378        * EastNorth for the three corners and make a bounding box.
     379        */
     380        double left_x = maxdist * (width - centre) / height;
     381        double right_x = maxdist * (0 - centre) / height;
     382        double e_lat[] = new double[] {
     383            lat + (maxdist - cardist) * cos - left_x * sin,
     384            lat + (maxdist - cardist) * cos - right_x * sin,
     385            lat - cardist * cos, };
     386        double e_lon[] = new double[] {
     387            lon + (maxdist - cardist) * sin + left_x * cos,
     388            lon + (maxdist - cardist) * sin + right_x * cos,
     389            lon - cardist * sin, };
     390        ground_view.setProjectionBounds(new ProjectionBounds(
     391                new EastNorth(min3(e_lon), min3(e_lat)),
     392                new EastNorth(max3(e_lon), max3(e_lat))));
     393
     394        /* If the layer is a WMS layer, check if any tiles are
     395        * missing */
     396        if (ground instanceof wmsplugin.WMSLayer) {
     397            wmsplugin.WMSLayer wms = (wmsplugin.WMSLayer) ground;
     398            downloading = wms.hasAutoDownload() && (
     399                    null == wms.findImage(new EastNorth(
     400                            e_lon[0], e_lat[0])) ||
     401                    null == wms.findImage(new EastNorth(
     402                            e_lon[0], e_lat[0])) ||
     403                    null == wms.findImage(new EastNorth(
     404                            e_lon[0], e_lat[0])));
     405        }
     406
     407        /* Request the image from ground layer */
     408        ground.paint(ground_view.graphics, ground_view, null);
     409
     410        for (int y = (int) (height * horizon + 0.1); y < height; y ++) {
     411            /* Assume a 60 deg vertical Field of View when
     412            * calculating the distance at given pixel.  */
     413            double dist = ele / (1.0 * y / height - 0.6);
     414            double lat_off = lat + (dist - cardist) * cos;
     415            double lon_off = lon + (dist - cardist) * sin;
     416
     417            for (int x = 0; x < width; x ++) {
     418                double p_x = dist * (x - centre) / height;
     419
     420                EastNorth en = new EastNorth(
     421                        lon_off + p_x * cos,
     422                        lat_off - p_x * sin);
     423
     424                Point pt = ground_view.getPoint(en);
     425
     426                int rgb = ground_view.ground_image.getRGB(
     427                        pt.x, pt.y);
     428                screen_image.setRGB(x, y, rgb);
     429            }
     430        }
     431    }
     432
     433    protected BufferedImage sky_image;
     434    protected Graphics sky;
     435    public void generate_sky() {
     436        sky_image = new BufferedImage(sw, 70,
     437                BufferedImage.TYPE_INT_ARGB);
     438        sky = sky_image.getGraphics();
     439
     440        int n = (int) (Math.random() * sw * 0.03);
     441        for (int i = 0; i < n; i ++) {
     442            int t = (int) (Math.random() * 5.0);
     443            int x = (int) (Math.random() *
     444                    (sw - cloud[t].getIconWidth()));
     445            int y = (int) ((1 - Math.random() * Math.random()) *
     446                    (70 - cloud[t].getIconHeight()));
     447            sky.drawImage(cloud[t].getImage(), x, y, this);
     448        }
     449
     450        if (Math.random() < 0.5) {
     451            int t = 0;
     452            int x = (int) (300 + Math.random() * (sw - 500 -
     453                        aircraft[t].getIconWidth()));
     454            sky.drawImage(aircraft[t].getImage(), x, 0, this);
     455        }
     456    }
     457
     458    public void sky_paint() {
     459        /* for x -> 0, lim sin(x) / x = 1 */
     460        int hx = (int) (-heading * maxdist * pixelperlat);
     461        int hw = skyline[current_bg].getIconWidth();
     462        hx = ((hx % hw) - hw) % hw;
     463
     464        int sx = (int) (-heading * maxdist * pixelperlat * sratio);
     465        sx = ((sx % sw) - sw) % sw;
     466
     467        screen.drawImage(bg[current_bg].getImage(), 0, 0, this);
     468        screen.drawImage(sky_image, sx, 50, this);
     469        if (sw + sx < width)
     470            screen.drawImage(sky_image, sx + sw, 50, this);
     471        screen.drawImage(skyline[current_bg].getImage(), hx, 66, this);
     472        if (hw + hx < width)
     473            screen.drawImage(skyline[current_bg].getImage(),
     474                    hx + hw, 66, this);
     475    }
     476
     477    protected class sprite_pos implements Comparable {
     478        double dist;
     479
     480        int x, y, sx, sy;
     481        Image sprite;
     482
     483        public sprite_pos() {
     484        }
     485
     486        public int compareTo(Object x) {
     487            sprite_pos other = (sprite_pos) x;
     488            return (int) ((other.dist - this.dist) * 1000000.0);
     489        }
     490    }
     491
     492    /* sizes decides how many zoom levels the sprites have.  We
     493    * could do just normal scalling according to distance but
     494    * that's not what old games did, they had prescaled sprites
     495    * for the different distances and you could see the feature
     496    * grow discretely as you approached it.  */
     497    protected final static int sizes = 8;
     498
     499    protected final static int maxsprites = 32;
     500    protected sprite_pos sprites[] = new sprite_pos[maxsprites];
     501
     502    protected void sprites_paint() {
     503        /* The vehicle */
     504        int orientation = (wheelangle > -0.02 ? wheelangle < 0.02 ?
     505                1 : 2 : 0) + current_car * 3;
     506        sprites[0].sprite = car[orientation].getImage();
     507        sprites[0].dist = cardist;
     508        sprites[0].sx = car[orientation].getIconWidth();
     509        sprites[0].x = centre - sprites[0].sx / 2;
     510        sprites[0].sy = car[orientation].getIconHeight();
     511        sprites[0].y = height - sprites[0].sy - 10; /* TODO */
     512
     513        /* The cacti */
     514        double sin = Math.sin(-heading);
     515        double cos = Math.cos(-heading);
     516        int i = 1;
     517
     518        for (EastNorth ll : cacti) {
     519            double clat = ll.north() - lat;
     520            double clon = ll.east() - lon;
     521            double dist = (clat * cos - clon * sin) + cardist;
     522            double p_x = clat * sin + clon * cos;
     523
     524            if (dist * 8 <= cardist || dist > maxdist)
     525                continue;
     526
     527            int x = (int) (p_x * height / dist + centre);
     528            int y = (int) ((ele / dist + 0.6) * height);
     529
     530            if (i >= maxsprites)
     531                break;
     532            if (x < -10 || x > width + 10)
     533                continue;
     534
     535            int type = (((int) (ll.north() * 10000000.0) & 31) % 3);
     536            int sx = cactus[type].getIconWidth();
     537            int sy = cactus[type].getIconHeight();
     538
     539            sprite_pos pos = sprites[i ++];
     540            pos.dist = dist;
     541            pos.sprite = cactus[type].getImage();
     542            pos.sx = (int) (sx * cardist * 0.7 / dist);
     543            pos.sy = (int) (sy * cardist * 0.7 / dist);
     544            pos.x = x - pos.sx / 2;
     545            pos.y = y - pos.sy;
     546        }
     547
     548        Arrays.sort(sprites, 0, i);
     549        for (sprite_pos sprite : sprites)
     550            if (i --> 0)
     551                screen.drawImage(sprite.sprite,
     552                        sprite.x, sprite.y,
     553                        sprite.sx, sprite.sy, this);
     554            else
     555                break;
     556
     557        if (splashframe >= 0) {
     558            splashframe ++;
     559            if (splashframe >= 8)
     560                splashframe = -1;
     561
     562            int type = (((int) (splashcactus.north() *
     563                            10000000.0) & 31) % 3);
     564            int sx = cactus[type].getIconWidth();
     565            int sy = cactus[type].getIconHeight();
     566            Image image = cactus[type].getImage();
     567
     568            for (i = 0; i < 50; i ++) {
     569                int x = (int) (Math.random() * sx);
     570                int y = (int) (Math.random() * sy);
     571                int w = (int) (Math.random() * 20);
     572                int h = (int) (Math.random() * 20);
     573                int nx = centre + splashframe * (x - sx / 2);
     574                int ny = height - splashframe * (sy - y);
     575                int nw = w + splashframe;
     576                int nh = h + splashframe;
     577
     578                screen.drawImage(image,
     579                        nx, ny, nx + nw, ny + nh,
     580                        x, y, x + w, y + h, this);
     581            }
     582        }
     583    }
     584
     585    public boolean no_super_repaint = false;
     586    protected class GamePanel extends JPanel {
     587        public GamePanel() {
     588            setBackground(Color.BLACK);
     589            setDoubleBuffered(true);
     590        }
     591
     592        public void paint(Graphics g) {
     593            int w = (int) getSize().getWidth();
     594            int h = (int) getSize().getHeight();
     595
     596            if (no_super_repaint)
     597                no_super_repaint = false;
     598            else
     599                super.paint(g);
     600
     601            g.drawImage(screen_image, (w - width * scale) / 2,
     602                    (h - height * scale) / 2,
     603                    width * scale, height * scale, this);
     604
     605            Toolkit.getDefaultToolkit().sync();
     606        }
     607    }
     608    JPanel panel = new GamePanel();
     609
     610    protected void quit() {
     611        timer.stop();
     612
     613        car_engine.stop();
     614
     615        car_gps.stop();
     616        car_gps.save_trace();
     617
     618        setVisible(false);
     619        panel = null;
     620        screen_image = null;
     621        screen = null;
     622        dispose();
     623    }
     624
     625    /*
     626    * Supposedly a thread drawing frames and sleeping in a loop is
     627    * better than for animating than swing Timers.  For the moment
     628    * I'll use a timer because I don't want to deal with all the
     629    * potential threading issues.
     630    */
     631    protected Timer timer;
     632    public void actionPerformed(ActionEvent e) {
     633        move();
     634        screen_repaint();
     635
     636        no_super_repaint = true;
     637        panel.repaint();
     638    }
     639
     640    protected class TAdapter extends KeyAdapter {
     641        public void keyPressed(KeyEvent e) {
     642            int key = e.getKeyCode();
     643
     644            if (key == KeyEvent.VK_LEFT && !key_down[0]) {
     645                wheelangle -= 0.02;
     646                key_down[0] = true;
     647            }
     648
     649            if (key == KeyEvent.VK_RIGHT && !key_down[1]) {
     650                wheelangle += 0.02;
     651                key_down[1] = true;
     652            }
     653
     654            if (key == KeyEvent.VK_UP)
     655                key_down[2] = true;
     656
     657            if (key == KeyEvent.VK_DOWN)
     658                key_down[3] = true;
     659
     660            if (key == KeyEvent.VK_ESCAPE)
     661                quit();
     662
     663            /* Toggle sound */
     664            if (key == KeyEvent.VK_S) {
     665                if (car_engine.is_on())
     666                    car_engine.stop();
     667                else
     668                    car_engine.start();
     669            }
     670
     671            /* Toggle cacti */
     672            if (key == KeyEvent.VK_C) {
     673                cacti_on = !cacti_on;
     674                if (!cacti_on)
     675                    cacti = new ArrayList<EastNorth>();
     676            }
     677
     678            /* Switch vehicle */
     679            if (key == KeyEvent.VK_V)
     680                if (current_car ++>= 1)
     681                    current_car = 0;
     682        }
     683
     684        public void keyReleased(KeyEvent e) {
     685            int key = e.getKeyCode();
     686
     687            if (key == KeyEvent.VK_LEFT)
     688                key_down[0] = false;
     689
     690            if (key == KeyEvent.VK_RIGHT)
     691                key_down[1] = false;
     692
     693            if (key == KeyEvent.VK_UP)
     694                key_down[2] = false;
     695
     696            if (key == KeyEvent.VK_DOWN)
     697                key_down[3] = false;
     698        }
     699    }
     700    protected fake_map_view ground_view;
    701701}
  • applications/editors/josm/plugins/wms-turbo-challenge2/src/wmsturbochallenge/WMSRacer.java

    r21761 r23190  
    2020
    2121public class WMSRacer extends Plugin implements LayerChangeListener {
    22         public WMSRacer(PluginInformation info) {
    23                 super(info);
    24                 driveAction.updateEnabledState();
     22    public WMSRacer(PluginInformation info) {
     23        super(info);
     24        driveAction.updateEnabledState();
    2525
    26                 JMenu toolsMenu = Main.main.menu.toolsMenu;
    27                 toolsMenu.addSeparator();
    28                 toolsMenu.add(new JMenuItem(driveAction));
    29         }
     26        JMenu toolsMenu = Main.main.menu.toolsMenu;
     27        toolsMenu.addSeparator();
     28        toolsMenu.add(new JMenuItem(driveAction));
     29    }
    3030
    31         /* Rather than add an action or main menu entry we should add
    32         * an entry in the new layer's context menus in layerAdded
    33         * but there doesn't seem to be any way to do that :( */
    34         protected class DriveAction extends JosmAction {
    35                 public MapFrame frame = null;
    36                 public Layer currentLayer = null;
    37                 protected Layer groundLayer = null;
     31    /* Rather than add an action or main menu entry we should add
     32    * an entry in the new layer's context menus in layerAdded
     33    * but there doesn't seem to be any way to do that :( */
     34    protected class DriveAction extends JosmAction {
     35        public MapFrame frame = null;
     36        public Layer currentLayer = null;
     37        protected Layer groundLayer = null;
    3838
    39                 public DriveAction() {
    40                         super("Go driving", "wmsracer",
    41                                         "Drive a race car on this layer",
    42                                         null, true);
    43                         setEnabled(false);
    44                 }
     39        public DriveAction() {
     40            super("Go driving", "wmsracer",
     41                    "Drive a race car on this layer",
     42                    null, true);
     43            setEnabled(false);
     44        }
    4545
    46                 public void actionPerformed(ActionEvent ev) {
    47                         if (groundLayer == null ||
    48                                         !groundLayer.isBackgroundLayer())
    49                                 return;
     46        public void actionPerformed(ActionEvent ev) {
     47            if (groundLayer == null ||
     48                    !groundLayer.isBackgroundLayer())
     49                return;
    5050
    51                         new GameWindow(groundLayer);
    52                 }
     51            new GameWindow(groundLayer);
     52        }
    5353
    54                 public void updateEnabledState() {
    55                         if (frame == null) {
    56                                 groundLayer = null;
    57                                 setEnabled(false);
    58                                 return;
    59                         }
     54        public void updateEnabledState() {
     55            if (frame == null) {
     56                groundLayer = null;
     57                setEnabled(false);
     58                return;
     59            }
    6060
    61                         if (currentLayer != null &&
    62                                         currentLayer.isBackgroundLayer()) {
    63                                 groundLayer = currentLayer;
    64                                 setEnabled(true);
    65                                 return;
    66                         }
     61            if (currentLayer != null &&
     62                    currentLayer.isBackgroundLayer()) {
     63                groundLayer = currentLayer;
     64                setEnabled(true);
     65                return;
     66            }
    6767
    68                         /* TODO: should only iterate through visible layers?
    69                         * or only wms layers? or perhaps we should allow
    70                         * driving on data/gpx layers too, or the full layer
    71                         * stack (by calling mapView.paint() instead of
    72                         * layer.paint()?  Nah.
    73                         * (Note that for GPX or Data layers we could do
    74                         * some clever rendering directly on our perspectivic
    75                         * pseudo-3d surface by defining a strange projection
    76                         * like that or rendering in "stripes" at different
    77                         * horizontal scanlines (lines equidistant from
    78                         * camera eye)) */
    79                         for (Layer l : frame.mapView.getAllLayers())
    80                                 if (l.isBackgroundLayer()) {
    81                                         groundLayer = l;
    82                                         setEnabled(true);
    83                                         return;
    84                                 }
     68            /* TODO: should only iterate through visible layers?
     69            * or only wms layers? or perhaps we should allow
     70            * driving on data/gpx layers too, or the full layer
     71            * stack (by calling mapView.paint() instead of
     72            * layer.paint()?  Nah.
     73            * (Note that for GPX or Data layers we could do
     74            * some clever rendering directly on our perspectivic
     75            * pseudo-3d surface by defining a strange projection
     76            * like that or rendering in "stripes" at different
     77            * horizontal scanlines (lines equidistant from
     78            * camera eye)) */
     79            for (Layer l : frame.mapView.getAllLayers())
     80                if (l.isBackgroundLayer()) {
     81                    groundLayer = l;
     82                    setEnabled(true);
     83                    return;
     84                }
    8585
    86                         groundLayer = null;
    87                         setEnabled(false);
    88                 }
    89         }
     86            groundLayer = null;
     87            setEnabled(false);
     88        }
     89    }
    9090
    91         protected DriveAction driveAction = new DriveAction();
     91    protected DriveAction driveAction = new DriveAction();
    9292
    93         public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
    94                 if (oldFrame != null)
    95                         oldFrame.mapView.removeLayerChangeListener(this);
     93    public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
     94        if (oldFrame != null)
     95            oldFrame.mapView.removeLayerChangeListener(this);
    9696
    97                 driveAction.frame = newFrame;
    98                 driveAction.updateEnabledState();
     97        driveAction.frame = newFrame;
     98        driveAction.updateEnabledState();
    9999
    100                 if (newFrame != null)
    101                         newFrame.mapView.addLayerChangeListener(this);
    102         }
     100        if (newFrame != null)
     101            newFrame.mapView.addLayerChangeListener(this);
     102    }
    103103
    104         /* LayerChangeListener methods */
    105         public void activeLayerChange(Layer oldLayer, Layer newLayer) {
    106                 driveAction.currentLayer = newLayer;
    107                 driveAction.updateEnabledState();
    108         }
     104    /* LayerChangeListener methods */
     105    public void activeLayerChange(Layer oldLayer, Layer newLayer) {
     106        driveAction.currentLayer = newLayer;
     107        driveAction.updateEnabledState();
     108    }
    109109
    110         public void layerAdded(Layer newLayer) {
    111                 driveAction.updateEnabledState();
    112         }
     110    public void layerAdded(Layer newLayer) {
     111        driveAction.updateEnabledState();
     112    }
    113113
    114         public void layerRemoved(Layer oldLayer) {
    115                 driveAction.updateEnabledState();
    116         }
     114    public void layerRemoved(Layer oldLayer) {
     115        driveAction.updateEnabledState();
     116    }
    117117}
Note: See TracChangeset for help on using the changeset viewer.