Changeset 18761 in osm


Ignore:
Timestamp:
2009-11-23T17:00:00+01:00 (15 years ago)
Author:
stoecker
Message:

fixed code indentation

Location:
applications/editors/josm/plugins/wmsplugin/src/wmsplugin
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/wmsplugin/src/wmsplugin/GeorefImage.java

    r17561 r18761  
    137137        boolean hasImage = in.readBoolean();
    138138        if (hasImage)
    139                 image = (BufferedImage) ImageIO.read(ImageIO.createImageInputStream(in));
     139            image = (BufferedImage) ImageIO.read(ImageIO.createImageInputStream(in));
    140140        else {
    141                 in.readObject(); // read null from input stream
    142                 image = null;
     141            in.readObject(); // read null from input stream
     142            image = null;
    143143        }
    144144    }
     
    148148        out.writeObject(min);
    149149        if(image == null) {
    150                 out.writeBoolean(false);
     150            out.writeBoolean(false);
    151151            out.writeObject(null);
    152152        } else {
    153                 out.writeBoolean(true);
     153            out.writeBoolean(true);
    154154            ImageIO.write(image, "png", ImageIO.createImageOutputStream(out));
    155155        }
  • applications/editors/josm/plugins/wmsplugin/src/wmsplugin/Map_Rectifier_WMSmenuAction.java

    r17552 r18761  
    155155        // The loop is break;-ed if the users cancels
    156156        outer: while(true) {
    157                 diag.showDialog();
     157            diag.showDialog();
    158158            int answer = diag.getValue();
    159159            // Break loop when the user cancels
  • applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSAdjustAction.java

    r18670 r18761  
    3232
    3333public class WMSAdjustAction extends MapMode implements MouseListener, MouseMotionListener{
    34         static private final Logger logger = Logger.getLogger(WMSAdjustAction.class.getName());
    35        
     34    static private final Logger logger = Logger.getLogger(WMSAdjustAction.class.getName());
     35   
    3636    GeorefImage selectedImage;
    3737    boolean mouseDown;
     
    5050        super.enterMode();       
    5151        if (!hasWMSLayersToAdjust()) {
    52                 warnNoWMSLayers();
    53                 return;
     52            warnNoWMSLayers();
     53            return;
    5454        }
    5555        List<WMSLayer> wmsLayers = Main.map.mapView.getLayersOfType(WMSLayer.class);
    5656        if (wmsLayers.size() == 1) {
    57                 adjustingLayer = wmsLayers.get(0);
     57            adjustingLayer = wmsLayers.get(0);
    5858        } else {
    59                 adjustingLayer = (WMSLayer)askAdjustLayer(Main.map.mapView.getLayersOfType(WMSLayer.class));
     59            adjustingLayer = (WMSLayer)askAdjustLayer(Main.map.mapView.getLayersOfType(WMSLayer.class));
    6060        }
    6161        if (adjustingLayer == null)
    62                 return;
     62            return;
    6363        if (!adjustingLayer.isVisible()) {
    64                 adjustingLayer.setVisible(true);
     64            adjustingLayer.setVisible(true);
    6565        }
    6666        Main.map.mapView.addMouseListener(this);
     
    175175   
    176176       ExtendedDialog diag = new ExtendedDialog(
    177                    Main.parent,
    178                    tr("Select WMS layer"),
    179                    new String[] { tr("Start adjusting"),tr("Cancel") }
    180                    );
     177               Main.parent,
     178               tr("Select WMS layer"),
     179               new String[] { tr("Start adjusting"),tr("Cancel") }
     180               );
    181181       diag.setContent(pnl);
    182182       diag.setButtonIcons(new String[] { "mapmode/adjustwms", "cancel" });
     
    195195   protected void warnNoWMSLayers() {
    196196       JOptionPane.showMessageDialog(
    197                    Main.parent,
     197               Main.parent,
    198198               tr("There are currently no WMS layer to adjust."),
    199199               tr("No layers to adjust"),
     
    208208    */
    209209   protected boolean hasWMSLayersToAdjust() {
    210            if (Main.map == null) return false;
    211            if (Main.map.mapView == null) return false;
    212            return ! Main.map.mapView.getLayersOfType(WMSLayer.class).isEmpty();
    213    }
    214 
    215         @Override
    216         protected void updateEnabledState() {
    217                 setEnabled(hasWMSLayersToAdjust());
    218         }   
     210       if (Main.map == null) return false;
     211       if (Main.map.mapView == null) return false;
     212       return ! Main.map.mapView.getLayersOfType(WMSLayer.class).isEmpty();
     213   }
     214
     215    @Override
     216    protected void updateEnabledState() {
     217        setEnabled(hasWMSLayersToAdjust());
     218    }   
    219219}
  • applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSGrabber.java

    r18712 r18761  
    3737        return url != null && url.contains("{") && url.contains("}");
    3838    }
    39        
     39   
    4040    protected String baseURL;
    4141    private final boolean urlWithPatterns;
     
    7171            image.downloadingStarted = false;
    7272        } catch(Exception e) {
    73                 e.printStackTrace();
     73            e.printStackTrace();
    7474            throw new Exception(e.getMessage() + "\nImage couldn't be fetched: " + (url != null ? url.toString() : ""));
    7575        }
     
    112112                + getProjection(baseURL, false)
    113113                + "&width=" + wi + "&height=" + ht;
    114                 if (!(baseURL.endsWith("&") || baseURL.endsWith("?"))) {
    115                         System.out.println(tr("Warning: The base URL ''{0}'' for a WMS service doesn't have a trailing '&' or a trailing '?'.", baseURL));
    116                         System.out.println(tr("Warning: Fetching WMS tiles is likely to fail. Please check you preference settings."));
    117                         System.out.println(tr("Warning: The complete URL is ''{0}''.", str));
    118                 }
     114            if (!(baseURL.endsWith("&") || baseURL.endsWith("?"))) {
     115                System.out.println(tr("Warning: The base URL ''{0}'' for a WMS service doesn't have a trailing '&' or a trailing '?'.", baseURL));
     116                System.out.println(tr("Warning: Fetching WMS tiles is likely to fail. Please check you preference settings."));
     117                System.out.println(tr("Warning: The complete URL is ''{0}''.", str));
     118            }
    119119        }
    120120        return new URL(str.replace(" ", "%20"));
  • applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSLayer.java

    r18670 r18761  
    4141/**
    4242 * This is a layer that grabs the current screen from an WMS server. The data
    43  * fetched this way is tiled and managerd to the disc to reduce server load.
     43 * fetched this way is tiled and managed to the disc to reduce server load.
    4444 */
    4545public class WMSLayer extends Layer {
    46         protected static final Icon icon =
    47                 new ImageIcon(Toolkit.getDefaultToolkit().createImage(WMSPlugin.class.getResource("/images/wms_small.png")));
    48 
    49         public int messageNum = 5; //limit for messages per layer
    50         protected MapView mv;
    51         protected String resolution;
    52         protected boolean stopAfterPaint = false;
    53         protected int ImageSize = 500;
    54         protected int dax = 10;
    55         protected int day = 10;
    56         protected int minZoom = 3;
    57         protected double dx = 0.0;
    58         protected double dy = 0.0;
    59         protected double pixelPerDegree;
    60         protected GeorefImage[][] images = new GeorefImage[dax][day];
    61         JCheckBoxMenuItem startstop = new JCheckBoxMenuItem(tr("Automatic downloading"), true);
    62         protected JCheckBoxMenuItem alphaChannel = new JCheckBoxMenuItem(new ToggleAlphaAction());
    63         protected String baseURL;
    64         protected String cookies;
    65         protected final int serializeFormatVersion = 5;
    66 
    67         private ExecutorService executor = null;
    68 
    69         /** set to true if this layer uses an invalid base url */
    70         private boolean usesInvalidUrl = false;
    71         /** set to true if the user confirmed to use an potentially invalid WMS base url */
    72         private boolean isInvalidUrlConfirmed = false;
    73 
    74         public WMSLayer() {
    75                 this(tr("Blank Layer"), null, null);
    76                 initializeImages();
    77                 mv = Main.map.mapView;
    78         }
    79 
    80         public WMSLayer(String name, String baseURL, String cookies) {
    81                 super(name);
    82                 alphaChannel.setSelected(Main.pref.getBoolean("wmsplugin.alpha_channel"));
    83                 setBackgroundLayer(true); /* set global background variable */
    84                 initializeImages();
    85                 this.baseURL = baseURL;
    86                 this.cookies = cookies;
    87                 WMSGrabber.getProjection(baseURL, true);
    88                 mv = Main.map.mapView;
    89                 resolution = mv.getDist100PixelText();
    90                 pixelPerDegree = getPPD();
    91 
    92                 executor = Executors.newFixedThreadPool(3);
    93                 if (baseURL != null && !baseURL.startsWith("html:") && !WMSGrabber.isUrlWithPatterns(baseURL)) {
    94                         if (!(baseURL.endsWith("&") || baseURL.endsWith("?"))) {
    95                                 if (!confirmMalformedUrl(baseURL)) {
    96                                         System.out.println(tr("Warning: WMS layer deactivated because of malformed base url ''{0}''", baseURL));
    97                                         usesInvalidUrl = true;
    98                                         setName(getName() + tr("(deactivated)"));
    99                                         return;
    100                                 } else {
    101                                         isInvalidUrlConfirmed = true;
    102                                 }
    103                         }
    104                 }
    105         }
    106 
    107         public double getDx(){
    108                 return dx;
    109         }
    110 
    111         public double getDy(){
    112                 return dy;
    113         }
    114 
    115         @Override
    116         public void destroy() {
    117                 try {
    118                         executor.shutdownNow();
    119                         // Might not be initalized, so catch NullPointer as well
    120                 } catch(Exception x) {
    121                         x.printStackTrace();
    122                 }
    123         }
    124 
    125         public double getPPD(){
    126                 ProjectionBounds bounds = mv.getProjectionBounds();
    127                 return mv.getWidth() / (bounds.max.east() - bounds.min.east());
    128         }
    129 
    130         public void initializeImages() {
    131                 images = new GeorefImage[dax][day];
    132                 for(int x = 0; x<dax; ++x) {
    133                         for(int y = 0; y<day; ++y) {
    134                                 images[x][y]= new GeorefImage(false);
    135                         }
    136                 }
    137         }
    138 
    139         @Override public Icon getIcon() {
    140                 return icon;
    141         }
    142 
    143         @Override public String getToolTipText() {
    144                 if(startstop.isSelected())
    145                         return tr("WMS layer ({0}), automatically downloading in zoom {1}", getName(), resolution);
    146                 else
    147                         return tr("WMS layer ({0}), downloading in zoom {1}", getName(), resolution);
    148         }
    149 
    150         @Override public boolean isMergable(Layer other) {
    151                 return false;
    152         }
    153 
    154         @Override public void mergeFrom(Layer from) {
    155         }
    156 
    157         private ProjectionBounds XYtoBounds (int x, int y) {
    158                 return new ProjectionBounds(
    159                                 new EastNorth(      x * ImageSize / pixelPerDegree,       y * ImageSize / pixelPerDegree),
    160                                 new EastNorth((x + 1) * ImageSize / pixelPerDegree, (y + 1) * ImageSize / pixelPerDegree));
    161         }
    162 
    163         private int modulo (int a, int b) {
    164                 return a % b >= 0 ? a%b : a%b+b;
    165         }
    166 
    167         @Override public void paint(Graphics2D g, final MapView mv, Bounds bounds) {
    168                 if(baseURL == null) return;
    169                 if (usesInvalidUrl && !isInvalidUrlConfirmed) return;
    170 
    171                 if( !startstop.isSelected() || (pixelPerDegree / getPPD() > minZoom) ){ //don't download when it's too outzoomed
    172                         for(int x = 0; x<dax; ++x) {
    173                                 for(int y = 0; y<day; ++y) {
    174                                         images[modulo(x,dax)][modulo(y,day)].paint(g, mv, dx, dy);
    175                                 }
    176                         }
    177                 } else {
    178                         downloadAndPaintVisible(g, mv);
    179                 }
    180         }
    181 
    182         public void displace(double dx, double dy) {
    183                 this.dx += dx;
    184                 this.dy += dy;
    185         }
    186 
    187         protected boolean confirmMalformedUrl(String url) {
    188                 if (isInvalidUrlConfirmed)
    189                         return true;
    190                 String msg  = tr("<html>The base URL<br>"
    191                                         + "''{0}''<br>"
    192                                         + "for this WMS layer does neither end with a ''&'' nor with a ''?''.<br>"
    193                                         + "This is likely to lead to invalid WMS request. You should check your<br>"
    194                                         + "preference settings.<br>"
    195                                         + "Do you want to fetch WMS tiles anyway?",
    196                                         url);
    197                 String [] options = new String[] {
    198                         tr("Yes, fetch images"),
    199                         tr("No, abort")
    200                 };
    201                 int ret = JOptionPane.showOptionDialog(
    202                                 Main.parent,
    203                                 msg,
    204                                 tr("Invalid URL?"),
    205                                 JOptionPane.YES_NO_OPTION,
    206                                 JOptionPane.WARNING_MESSAGE,
    207                                 null,
    208                                 options, options[1]
    209                 );
    210                 switch(ret) {
    211                 case JOptionPane.YES_OPTION: return true;
    212                 default: return false;
    213                 }
    214         }
    215         protected void downloadAndPaintVisible(Graphics g, final MapView mv){
    216                 if (usesInvalidUrl)
    217                         return;
    218                 ProjectionBounds bounds = mv.getProjectionBounds();
    219                 int bminx= (int)Math.floor (((bounds.min.east() - dx) * pixelPerDegree) / ImageSize );
    220                 int bminy= (int)Math.floor (((bounds.min.north() - dy) * pixelPerDegree) / ImageSize );
    221                 int bmaxx= (int)Math.ceil  (((bounds.max.east() - dx) * pixelPerDegree) / ImageSize );
    222                 int bmaxy= (int)Math.ceil  (((bounds.max.north() - dy) * pixelPerDegree) / ImageSize );
    223 
    224                 if((bmaxx - bminx > dax) || (bmaxy - bminy > day)){
    225                         JOptionPane.showMessageDialog(
    226                                         Main.parent,
    227                                         tr("The requested area is too big. Please zoom in a little, or change resolution"),
    228                                         tr("Error"),
    229                                         JOptionPane.ERROR_MESSAGE
    230                         );
    231                         return;
    232                 }
    233 
    234                 for(int x = bminx; x<bmaxx; ++x) {
    235                         for(int y = bminy; y<bmaxy; ++y){
    236                                 GeorefImage img = images[modulo(x,dax)][modulo(y,day)];
    237                                 g.drawRect(x, y, dax, bminy);
    238                                 if(!img.paint(g, mv, dx, dy) && !img.downloadingStarted){
    239                                         img.downloadingStarted = true;
    240                                         img.image = null;
    241                                         img.flushedResizedCachedInstance();
    242                                         Grabber gr = WMSPlugin.getGrabber(XYtoBounds(x,y), img, mv, this);
    243                                         gr.setPriority(1);
    244                                         executor.submit(gr);
    245                                 }
    246                         }
    247                 }
    248         }
    249 
    250         @Override public void visitBoundingBox(BoundingXYVisitor v) {
    251                 for(int x = 0; x<dax; ++x) {
    252                         for(int y = 0; y<day; ++y)
    253                                 if(images[x][y].image!=null){
    254                                         v.visit(images[x][y].min);
    255                                         v.visit(images[x][y].max);
    256                                 }
    257                 }
    258         }
    259 
    260         @Override public Object getInfoComponent() {
    261                 return getToolTipText();
    262         }
    263 
    264         @Override public Component[] getMenuEntries() {
    265                 return new Component[]{
    266                                 new JMenuItem(LayerListDialog.getInstance().createShowHideLayerAction(this)),
    267                                 new JMenuItem(LayerListDialog.getInstance().createDeleteLayerAction(this)),
    268                                 new JSeparator(),
    269                                 new JMenuItem(new LoadWmsAction()),
    270                                 new JMenuItem(new SaveWmsAction()),
    271                                 new JSeparator(),
    272                                 startstop,
    273                                 alphaChannel,
    274                                 new JMenuItem(new ChangeResolutionAction()),
    275                                 new JMenuItem(new ReloadErrorTilesAction()),
    276                                 new JMenuItem(new DownloadAction()),
    277                                 new JSeparator(),
    278                                 new JMenuItem(new LayerListPopup.InfoAction(this))
    279                 };
    280         }
    281 
    282         public GeorefImage findImage(EastNorth eastNorth) {
    283                 for(int x = 0; x<dax; ++x) {
    284                         for(int y = 0; y<day; ++y)
    285                                 if(images[x][y].image!=null && images[x][y].min!=null && images[x][y].max!=null)
    286                                         if(images[x][y].contains(eastNorth, dx, dy))
    287                                                 return images[x][y];
    288                 }
    289                 return null;
    290         }
    291 
    292         public class DownloadAction extends AbstractAction {
    293                 public DownloadAction() {
    294                         super(tr("Download visible tiles"));
    295                 }
    296                 public void actionPerformed(ActionEvent ev) {
    297                         downloadAndPaintVisible(mv.getGraphics(), mv);
    298                 }
    299         }
    300 
    301         public class ChangeResolutionAction extends AbstractAction {
    302                 public ChangeResolutionAction() {
    303                         super(tr("Change resolution"));
    304                 }
    305                 public void actionPerformed(ActionEvent ev) {
    306                         initializeImages();
    307                         resolution = mv.getDist100PixelText();
    308                         pixelPerDegree = getPPD();
    309                         mv.repaint();
    310                 }
    311         }
    312 
    313         public class ReloadErrorTilesAction extends AbstractAction {
    314                 public ReloadErrorTilesAction() {
    315                         super(tr("Reload erroneous tiles"));
    316                 }
    317                 public void actionPerformed(ActionEvent ev) {
    318                         // Delete small files, because they're probably blank tiles.
    319                         // See https://josm.openstreetmap.de/ticket/2307
    320                         WMSPlugin.cache.customCleanUp(CacheFiles.CLEAN_SMALL_FILES, 2048);
    321 
    322                         for (int x = 0; x < dax; ++x) {
    323                                 for (int y = 0; y < day; ++y) {
    324                                         GeorefImage img = images[modulo(x,dax)][modulo(y,day)];
    325                                         if(img.failed){
    326                                                 img.image = null;
    327                                                 img.flushedResizedCachedInstance();
    328                                                 img.downloadingStarted = false;
    329                                                 img.failed = false;
    330                                                 mv.repaint();
    331                                         }
    332                                 }
    333                         }
    334                 }
    335         }
    336 
    337         public class ToggleAlphaAction extends AbstractAction {
    338                 public ToggleAlphaAction() {
    339                         super(tr("Alpha channel"));
    340                 }
    341                 public void actionPerformed(ActionEvent ev) {
    342                         JCheckBoxMenuItem checkbox = (JCheckBoxMenuItem) ev.getSource();
    343                         boolean alphaChannel = checkbox.isSelected();
    344                         Main.pref.put("wmsplugin.alpha_channel", alphaChannel);
    345 
    346                         // clear all resized cached instances and repaint the layer
    347                         for (int x = 0; x < dax; ++x) {
    348                                 for (int y = 0; y < day; ++y) {
    349                                         GeorefImage img = images[modulo(x, dax)][modulo(y, day)];
    350                                         img.flushedResizedCachedInstance();
    351                                 }
    352                         }
    353                         mv.repaint();
    354                 }
    355         }
    356 
    357         public class SaveWmsAction extends AbstractAction {
    358                 public SaveWmsAction() {
    359                         super(tr("Save WMS layer to file"), ImageProvider.get("save"));
    360                 }
    361                 public void actionPerformed(ActionEvent ev) {
    362                         File f = SaveActionBase.createAndOpenSaveFileChooser(
    363                                         tr("Save WMS layer"), ".wms");
    364                         try {
    365                                 if (f != null) {
    366                                         ObjectOutputStream oos = new ObjectOutputStream(
    367                                                         new FileOutputStream(f)
    368                                         );
    369                                         oos.writeInt(serializeFormatVersion);
    370                                         oos.writeInt(dax);
    371                                         oos.writeInt(day);
    372                                         oos.writeInt(ImageSize);
    373                                         oos.writeDouble(pixelPerDegree);
    374                                         oos.writeObject(getName());
    375                                         oos.writeObject(baseURL);
    376                                         oos.writeObject(images);
    377                                         oos.close();
    378                                 }
    379                         } catch (Exception ex) {
    380                                 ex.printStackTrace(System.out);
    381                         }
    382                 }
    383         }
    384 
    385         public class LoadWmsAction extends AbstractAction {
    386                 public LoadWmsAction() {
    387                         super(tr("Load WMS layer from file"), ImageProvider.get("load"));
    388                 }
    389                 public void actionPerformed(ActionEvent ev) {
    390                         JFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true,
    391                                         false, tr("Load WMS layer"), "wms");
    392                         if(fc == null) return;
    393                         File f = fc.getSelectedFile();
    394                         if (f == null) return;
    395                         try
    396                         {
    397                                 FileInputStream fis = new FileInputStream(f);
    398                                 ObjectInputStream ois = new ObjectInputStream(fis);
    399                                 int sfv = ois.readInt();
    400                                 if (sfv != serializeFormatVersion) {
    401                                         JOptionPane.showMessageDialog(Main.parent,
    402                                                         tr("Unsupported WMS file version; found {0}, expected {1}", sfv, serializeFormatVersion),
    403                                                         tr("File Format Error"),
    404                                                         JOptionPane.ERROR_MESSAGE);
    405                                         return;
    406                                 }
    407                                 startstop.setSelected(false);
    408                                 dax = ois.readInt();
    409                                 day = ois.readInt();
    410                                 ImageSize = ois.readInt();
    411                                 pixelPerDegree = ois.readDouble();
    412                                 setName((String)ois.readObject());
    413                                 baseURL = (String) ois.readObject();
    414                                 images = (GeorefImage[][])ois.readObject();
    415                                 ois.close();
    416                                 fis.close();
    417                                 mv.repaint();
    418                         }
    419                         catch (Exception ex) {
    420                                 // FIXME be more specific
    421                                 ex.printStackTrace(System.out);
    422                                 JOptionPane.showMessageDialog(Main.parent,
    423                                                 tr("Error loading file"),
    424                                                 tr("Error"),
    425                                                 JOptionPane.ERROR_MESSAGE);
    426                                 return;
    427                         }
    428                 }
    429         }
     46    protected static final Icon icon =
     47        new ImageIcon(Toolkit.getDefaultToolkit().createImage(WMSPlugin.class.getResource("/images/wms_small.png")));
     48
     49    public int messageNum = 5; //limit for messages per layer
     50    protected MapView mv;
     51    protected String resolution;
     52    protected boolean stopAfterPaint = false;
     53    protected int ImageSize = 500;
     54    protected int dax = 10;
     55    protected int day = 10;
     56    protected int minZoom = 3;
     57    protected double dx = 0.0;
     58    protected double dy = 0.0;
     59    protected double pixelPerDegree;
     60    protected GeorefImage[][] images = new GeorefImage[dax][day];
     61    JCheckBoxMenuItem startstop = new JCheckBoxMenuItem(tr("Automatic downloading"), true);
     62    protected JCheckBoxMenuItem alphaChannel = new JCheckBoxMenuItem(new ToggleAlphaAction());
     63    protected String baseURL;
     64    protected String cookies;
     65    protected final int serializeFormatVersion = 5;
     66
     67    private ExecutorService executor = null;
     68
     69    /** set to true if this layer uses an invalid base url */
     70    private boolean usesInvalidUrl = false;
     71    /** set to true if the user confirmed to use an potentially invalid WMS base url */
     72    private boolean isInvalidUrlConfirmed = false;
     73
     74    public WMSLayer() {
     75        this(tr("Blank Layer"), null, null);
     76        initializeImages();
     77        mv = Main.map.mapView;
     78    }
     79
     80    public WMSLayer(String name, String baseURL, String cookies) {
     81        super(name);
     82        alphaChannel.setSelected(Main.pref.getBoolean("wmsplugin.alpha_channel"));
     83        setBackgroundLayer(true); /* set global background variable */
     84        initializeImages();
     85        this.baseURL = baseURL;
     86        this.cookies = cookies;
     87        WMSGrabber.getProjection(baseURL, true);
     88        mv = Main.map.mapView;
     89        resolution = mv.getDist100PixelText();
     90        pixelPerDegree = getPPD();
     91
     92        executor = Executors.newFixedThreadPool(3);
     93        if (baseURL != null && !baseURL.startsWith("html:") && !WMSGrabber.isUrlWithPatterns(baseURL)) {
     94            if (!(baseURL.endsWith("&") || baseURL.endsWith("?"))) {
     95                if (!confirmMalformedUrl(baseURL)) {
     96                    System.out.println(tr("Warning: WMS layer deactivated because of malformed base url ''{0}''", baseURL));
     97                    usesInvalidUrl = true;
     98                    setName(getName() + tr("(deactivated)"));
     99                    return;
     100                } else {
     101                    isInvalidUrlConfirmed = true;
     102                }
     103            }
     104        }
     105    }
     106
     107    public double getDx(){
     108        return dx;
     109    }
     110
     111    public double getDy(){
     112        return dy;
     113    }
     114
     115    @Override
     116    public void destroy() {
     117        try {
     118            executor.shutdownNow();
     119            // Might not be initalized, so catch NullPointer as well
     120        } catch(Exception x) {
     121            x.printStackTrace();
     122        }
     123    }
     124
     125    public double getPPD(){
     126        ProjectionBounds bounds = mv.getProjectionBounds();
     127        return mv.getWidth() / (bounds.max.east() - bounds.min.east());
     128    }
     129
     130    public void initializeImages() {
     131        images = new GeorefImage[dax][day];
     132        for(int x = 0; x<dax; ++x) {
     133            for(int y = 0; y<day; ++y) {
     134                images[x][y]= new GeorefImage(false);
     135            }
     136        }
     137    }
     138
     139    @Override public Icon getIcon() {
     140        return icon;
     141    }
     142
     143    @Override public String getToolTipText() {
     144        if(startstop.isSelected())
     145            return tr("WMS layer ({0}), automatically downloading in zoom {1}", getName(), resolution);
     146        else
     147            return tr("WMS layer ({0}), downloading in zoom {1}", getName(), resolution);
     148    }
     149
     150    @Override public boolean isMergable(Layer other) {
     151        return false;
     152    }
     153
     154    @Override public void mergeFrom(Layer from) {
     155    }
     156
     157    private ProjectionBounds XYtoBounds (int x, int y) {
     158        return new ProjectionBounds(
     159                new EastNorth(      x * ImageSize / pixelPerDegree,       y * ImageSize / pixelPerDegree),
     160                new EastNorth((x + 1) * ImageSize / pixelPerDegree, (y + 1) * ImageSize / pixelPerDegree));
     161    }
     162
     163    private int modulo (int a, int b) {
     164        return a % b >= 0 ? a%b : a%b+b;
     165    }
     166
     167    @Override public void paint(Graphics2D g, final MapView mv, Bounds bounds) {
     168        if(baseURL == null) return;
     169        if (usesInvalidUrl && !isInvalidUrlConfirmed) return;
     170
     171        if( !startstop.isSelected() || (pixelPerDegree / getPPD() > minZoom) ){ //don't download when it's too outzoomed
     172            for(int x = 0; x<dax; ++x) {
     173                for(int y = 0; y<day; ++y) {
     174                    images[modulo(x,dax)][modulo(y,day)].paint(g, mv, dx, dy);
     175                }
     176            }
     177        } else {
     178            downloadAndPaintVisible(g, mv);
     179        }
     180    }
     181
     182    public void displace(double dx, double dy) {
     183        this.dx += dx;
     184        this.dy += dy;
     185    }
     186
     187    protected boolean confirmMalformedUrl(String url) {
     188        if (isInvalidUrlConfirmed)
     189            return true;
     190        String msg  = tr("<html>The base URL<br>"
     191                        + "''{0}''<br>"
     192                        + "for this WMS layer does neither end with a ''&'' nor with a ''?''.<br>"
     193                        + "This is likely to lead to invalid WMS request. You should check your<br>"
     194                        + "preference settings.<br>"
     195                        + "Do you want to fetch WMS tiles anyway?",
     196                        url);
     197        String [] options = new String[] {
     198            tr("Yes, fetch images"),
     199            tr("No, abort")
     200        };
     201        int ret = JOptionPane.showOptionDialog(
     202                Main.parent,
     203                msg,
     204                tr("Invalid URL?"),
     205                JOptionPane.YES_NO_OPTION,
     206                JOptionPane.WARNING_MESSAGE,
     207                null,
     208                options, options[1]
     209        );
     210        switch(ret) {
     211        case JOptionPane.YES_OPTION: return true;
     212        default: return false;
     213        }
     214    }
     215    protected void downloadAndPaintVisible(Graphics g, final MapView mv){
     216        if (usesInvalidUrl)
     217            return;
     218        ProjectionBounds bounds = mv.getProjectionBounds();
     219        int bminx= (int)Math.floor (((bounds.min.east() - dx) * pixelPerDegree) / ImageSize );
     220        int bminy= (int)Math.floor (((bounds.min.north() - dy) * pixelPerDegree) / ImageSize );
     221        int bmaxx= (int)Math.ceil  (((bounds.max.east() - dx) * pixelPerDegree) / ImageSize );
     222        int bmaxy= (int)Math.ceil  (((bounds.max.north() - dy) * pixelPerDegree) / ImageSize );
     223
     224        if((bmaxx - bminx > dax) || (bmaxy - bminy > day)){
     225            JOptionPane.showMessageDialog(
     226                    Main.parent,
     227                    tr("The requested area is too big. Please zoom in a little, or change resolution"),
     228                    tr("Error"),
     229                    JOptionPane.ERROR_MESSAGE
     230            );
     231            return;
     232        }
     233
     234        for(int x = bminx; x<bmaxx; ++x) {
     235            for(int y = bminy; y<bmaxy; ++y){
     236                GeorefImage img = images[modulo(x,dax)][modulo(y,day)];
     237                g.drawRect(x, y, dax, bminy);
     238                if(!img.paint(g, mv, dx, dy) && !img.downloadingStarted){
     239                    img.downloadingStarted = true;
     240                    img.image = null;
     241                    img.flushedResizedCachedInstance();
     242                    Grabber gr = WMSPlugin.getGrabber(XYtoBounds(x,y), img, mv, this);
     243                    gr.setPriority(1);
     244                    executor.submit(gr);
     245                }
     246            }
     247        }
     248    }
     249
     250    @Override public void visitBoundingBox(BoundingXYVisitor v) {
     251        for(int x = 0; x<dax; ++x) {
     252            for(int y = 0; y<day; ++y)
     253                if(images[x][y].image!=null){
     254                    v.visit(images[x][y].min);
     255                    v.visit(images[x][y].max);
     256                }
     257        }
     258    }
     259
     260    @Override public Object getInfoComponent() {
     261        return getToolTipText();
     262    }
     263
     264    @Override public Component[] getMenuEntries() {
     265        return new Component[]{
     266                new JMenuItem(LayerListDialog.getInstance().createShowHideLayerAction(this)),
     267                new JMenuItem(LayerListDialog.getInstance().createDeleteLayerAction(this)),
     268                new JSeparator(),
     269                new JMenuItem(new LoadWmsAction()),
     270                new JMenuItem(new SaveWmsAction()),
     271                new JSeparator(),
     272                startstop,
     273                alphaChannel,
     274                new JMenuItem(new ChangeResolutionAction()),
     275                new JMenuItem(new ReloadErrorTilesAction()),
     276                new JMenuItem(new DownloadAction()),
     277                new JSeparator(),
     278                new JMenuItem(new LayerListPopup.InfoAction(this))
     279        };
     280    }
     281
     282    public GeorefImage findImage(EastNorth eastNorth) {
     283        for(int x = 0; x<dax; ++x) {
     284            for(int y = 0; y<day; ++y)
     285                if(images[x][y].image!=null && images[x][y].min!=null && images[x][y].max!=null)
     286                    if(images[x][y].contains(eastNorth, dx, dy))
     287                        return images[x][y];
     288        }
     289        return null;
     290    }
     291
     292    public class DownloadAction extends AbstractAction {
     293        public DownloadAction() {
     294            super(tr("Download visible tiles"));
     295        }
     296        public void actionPerformed(ActionEvent ev) {
     297            downloadAndPaintVisible(mv.getGraphics(), mv);
     298        }
     299    }
     300
     301    public class ChangeResolutionAction extends AbstractAction {
     302        public ChangeResolutionAction() {
     303            super(tr("Change resolution"));
     304        }
     305        public void actionPerformed(ActionEvent ev) {
     306            initializeImages();
     307            resolution = mv.getDist100PixelText();
     308            pixelPerDegree = getPPD();
     309            mv.repaint();
     310        }
     311    }
     312
     313    public class ReloadErrorTilesAction extends AbstractAction {
     314        public ReloadErrorTilesAction() {
     315            super(tr("Reload erroneous tiles"));
     316        }
     317        public void actionPerformed(ActionEvent ev) {
     318            // Delete small files, because they're probably blank tiles.
     319            // See https://josm.openstreetmap.de/ticket/2307
     320            WMSPlugin.cache.customCleanUp(CacheFiles.CLEAN_SMALL_FILES, 2048);
     321
     322            for (int x = 0; x < dax; ++x) {
     323                for (int y = 0; y < day; ++y) {
     324                    GeorefImage img = images[modulo(x,dax)][modulo(y,day)];
     325                    if(img.failed){
     326                        img.image = null;
     327                        img.flushedResizedCachedInstance();
     328                        img.downloadingStarted = false;
     329                        img.failed = false;
     330                        mv.repaint();
     331                    }
     332                }
     333            }
     334        }
     335    }
     336
     337    public class ToggleAlphaAction extends AbstractAction {
     338        public ToggleAlphaAction() {
     339            super(tr("Alpha channel"));
     340        }
     341        public void actionPerformed(ActionEvent ev) {
     342            JCheckBoxMenuItem checkbox = (JCheckBoxMenuItem) ev.getSource();
     343            boolean alphaChannel = checkbox.isSelected();
     344            Main.pref.put("wmsplugin.alpha_channel", alphaChannel);
     345
     346            // clear all resized cached instances and repaint the layer
     347            for (int x = 0; x < dax; ++x) {
     348                for (int y = 0; y < day; ++y) {
     349                    GeorefImage img = images[modulo(x, dax)][modulo(y, day)];
     350                    img.flushedResizedCachedInstance();
     351                }
     352            }
     353            mv.repaint();
     354        }
     355    }
     356
     357    public class SaveWmsAction extends AbstractAction {
     358        public SaveWmsAction() {
     359            super(tr("Save WMS layer to file"), ImageProvider.get("save"));
     360        }
     361        public void actionPerformed(ActionEvent ev) {
     362            File f = SaveActionBase.createAndOpenSaveFileChooser(
     363                    tr("Save WMS layer"), ".wms");
     364            try {
     365                if (f != null) {
     366                    ObjectOutputStream oos = new ObjectOutputStream(
     367                            new FileOutputStream(f)
     368                    );
     369                    oos.writeInt(serializeFormatVersion);
     370                    oos.writeInt(dax);
     371                    oos.writeInt(day);
     372                    oos.writeInt(ImageSize);
     373                    oos.writeDouble(pixelPerDegree);
     374                    oos.writeObject(getName());
     375                    oos.writeObject(baseURL);
     376                    oos.writeObject(images);
     377                    oos.close();
     378                }
     379            } catch (Exception ex) {
     380                ex.printStackTrace(System.out);
     381            }
     382        }
     383    }
     384
     385    public class LoadWmsAction extends AbstractAction {
     386        public LoadWmsAction() {
     387            super(tr("Load WMS layer from file"), ImageProvider.get("load"));
     388        }
     389        public void actionPerformed(ActionEvent ev) {
     390            JFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true,
     391                    false, tr("Load WMS layer"), "wms");
     392            if(fc == null) return;
     393            File f = fc.getSelectedFile();
     394            if (f == null) return;
     395            try
     396            {
     397                FileInputStream fis = new FileInputStream(f);
     398                ObjectInputStream ois = new ObjectInputStream(fis);
     399                int sfv = ois.readInt();
     400                if (sfv != serializeFormatVersion) {
     401                    JOptionPane.showMessageDialog(Main.parent,
     402                            tr("Unsupported WMS file version; found {0}, expected {1}", sfv, serializeFormatVersion),
     403                            tr("File Format Error"),
     404                            JOptionPane.ERROR_MESSAGE);
     405                    return;
     406                }
     407                startstop.setSelected(false);
     408                dax = ois.readInt();
     409                day = ois.readInt();
     410                ImageSize = ois.readInt();
     411                pixelPerDegree = ois.readDouble();
     412                setName((String)ois.readObject());
     413                baseURL = (String) ois.readObject();
     414                images = (GeorefImage[][])ois.readObject();
     415                ois.close();
     416                fis.close();
     417                mv.repaint();
     418            }
     419            catch (Exception ex) {
     420                // FIXME be more specific
     421                ex.printStackTrace(System.out);
     422                JOptionPane.showMessageDialog(Main.parent,
     423                        tr("Error loading file"),
     424                        tr("Error"),
     425                        JOptionPane.ERROR_MESSAGE);
     426                return;
     427            }
     428        }
     429    }
    430430}
  • applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSPlugin.java

    r18625 r18761  
    5757
    5858    protected void initExporterAndImporter() {
    59         ExtensionFileFilter.exporters.add(new WMSLayerExporter());
    60         ExtensionFileFilter.importers.add(new WMSLayerImporter());
     59        ExtensionFileFilter.exporters.add(new WMSLayerExporter());
     60        ExtensionFileFilter.importers.add(new WMSLayerImporter());
    6161    }
    6262
  • applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSPreferenceEditor.java

    r17556 r18761  
    5959        new String[]{tr("Menu Name (Default)"), tr("WMS URL (Default)")}, 0);
    6060        final JTable listdef = new JTable(modeldef){
    61                 @Override
     61            @Override
    6262            public boolean isCellEditable(int row,int column){return false;}
    6363        };
     
    8585                p.add(value, GBC.eol().insets(5,0,0,0).fill(GBC.HORIZONTAL));
    8686                int answer = JOptionPane.showConfirmDialog(
    87                                 gui, p,
    88                                 tr("Enter a menu name and WMS URL"),
    89                                 JOptionPane.OK_CANCEL_OPTION,
    90                                 JOptionPane.QUESTION_MESSAGE);
     87                        gui, p,
     88                        tr("Enter a menu name and WMS URL"),
     89                        JOptionPane.OK_CANCEL_OPTION,
     90                        JOptionPane.QUESTION_MESSAGE);
    9191                if (answer == JOptionPane.OK_OPTION) {
    9292                    model.addRow(new String[]{key.getText(), value.getText()});
     
    117117                if (lines.length == 0) {
    118118                    JOptionPane.showMessageDialog(
    119                                 gui,
    120                                 tr("Please select at least one row to copy."),
    121                                 tr("Information"),
    122                                 JOptionPane.INFORMATION_MESSAGE
    123                                 );
     119                            gui,
     120                            tr("Please select at least one row to copy."),
     121                            tr("Information"),
     122                            JOptionPane.INFORMATION_MESSAGE
     123                            );
    124124                    return;
    125125                }
    126126               
    127127                outer: for(int i = 0; i < lines.length; i++) {
    128                         String c1 = modeldef.getValueAt(lines[i], 0).toString();
    129                         String c2 = modeldef.getValueAt(lines[i], 1).toString();
    130                        
    131                         // Check if an entry with exactly the same values already
    132                         // exists
    133                         for(int j = 0; j < model.getRowCount(); j++) {
    134                                 if(c1.equals(model.getValueAt(j, 0).toString())
    135                                                 && c2.equals(model.getValueAt(j, 1).toString())) {
    136                                         // Select the already existing row so the user has
    137                                         // some feedback in case an entry exists
    138                                         list.getSelectionModel().setSelectionInterval(j, j);
    139                                         list.scrollRectToVisible(list.getCellRect(j, 0, true));
    140                                         continue outer;
    141                                 }
    142                         }
    143                        
    144                         model.addRow(new String[] {c1, c2});
    145                         int lastLine = model.getRowCount() - 1;
    146                         list.getSelectionModel().setSelectionInterval(lastLine, lastLine);
    147                         list.scrollRectToVisible(list.getCellRect(lastLine, 0, true));
     128                    String c1 = modeldef.getValueAt(lines[i], 0).toString();
     129                    String c2 = modeldef.getValueAt(lines[i], 1).toString();
     130                   
     131                    // Check if an entry with exactly the same values already
     132                    // exists
     133                    for(int j = 0; j < model.getRowCount(); j++) {
     134                        if(c1.equals(model.getValueAt(j, 0).toString())
     135                                && c2.equals(model.getValueAt(j, 1).toString())) {
     136                            // Select the already existing row so the user has
     137                            // some feedback in case an entry exists
     138                            list.getSelectionModel().setSelectionInterval(j, j);
     139                            list.scrollRectToVisible(list.getCellRect(j, 0, true));
     140                            continue outer;
     141                        }
     142                    }
     143                   
     144                    model.addRow(new String[] {c1, c2});
     145                    int lastLine = model.getRowCount() - 1;
     146                    list.getSelectionModel().setSelectionInterval(lastLine, lastLine);
     147                    list.scrollRectToVisible(list.getCellRect(lastLine, 0, true));
    148148                }
    149149            }
     
    182182        overlapPanel.add(spinNorth);
    183183         
    184         p.add(overlapPanel);   
     184        p.add(overlapPanel);   
    185185    }
    186186
Note: See TracChangeset for help on using the changeset viewer.