Changeset 17089 in osm for applications/editors


Ignore:
Timestamp:
2009-08-16T23:36:16+02:00 (15 years ago)
Author:
pieren
Message:

raster image feature implementation

Location:
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr
Files:
5 added
1 deleted
15 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java

    r15961 r17089  
    1616import java.util.concurrent.locks.ReentrantLock;
    1717
     18import javax.swing.JDialog;
    1819import javax.swing.JOptionPane;
    1920import org.openstreetmap.josm.Main;
     
    7879    public boolean loadCacheIfExist() {
    7980        try {
    80             File file = new File(CadastrePlugin.cacheDir + wmsLayer.name + "." + String.valueOf(wmsLayer.lambertZone+1));
     81            File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + String.valueOf(wmsLayer.lambertZone+1));
    8182            if (file.exists()) {
    82                 int reply = JOptionPane.showConfirmDialog(null,
    83                         "Location \""+wmsLayer.name+"\" found in cache.\n"+
     83                JOptionPane pane = new JOptionPane(
     84                        tr("Location \"{0}\" found in cache.\n"+
    8485                        "Load cache first ?\n"+
    85                         "(No = new cache)",
    86                         "Location in cache",
    87                         JOptionPane.YES_NO_OPTION);
     86                        "(No = new cache)", wmsLayer.getName()),
     87                        JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null);
     88                // this below is a temporary workaround to fix the "always on top" issue
     89                JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
     90                CadastrePlugin.prepareDialog(dialog);
     91                dialog.setVisible(true);
     92                int reply = (Integer)pane.getValue();
     93                // till here
     94
    8895                if (reply == JOptionPane.OK_OPTION) {
    8996                    return loadCache(file, wmsLayer.lambertZone);
     
    99106    public void deleteCacheFile() {
    100107        try {
    101             File file = new File(CadastrePlugin.cacheDir + wmsLayer.name + "." + String.valueOf(wmsLayer.lambertZone+1));
     108            File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + String.valueOf(wmsLayer.lambertZone+1));
    102109            if (file.exists())
    103110                file.delete();
     
    142149            imagesLock.unlock();
    143150            if (images != null && !images.isEmpty()) {
    144                 File file = new File(CadastrePlugin.cacheDir + wmsLayer.name + "." + String.valueOf((wmsLayer.lambertZone + 1)));
     151                File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + String.valueOf((wmsLayer.lambertZone + 1)));
    145152                try {
    146153                    if (file.exists()) {
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreGrabber.java

    r16581 r17089  
    1919public class CadastreGrabber {
    2020
    21     public static final double epsilon = 1e-11;
     21    public final static double epsilon = 1e-11;
    2222
    23     private CadastreInterface wmsInterface = new CadastreInterface(this);
    24     private String lastWMSLayerName = null;
    25 
    26     CadastreGrabber() {
    27         getWmsInterface().downloadCancelled = false;
    28     }
     23    private CadastreInterface wmsInterface = new CadastreInterface();
    2924
    3025    public GeorefImage grab(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax) throws IOException, OsmTransferException {
     
    3631            else
    3732                url = getURLVector(lambertMin, lambertMax);
    38             System.out.println("grab:"+url);
    3933            BufferedImage img = grab(url);
    40             ImageModifier imageModified = new ImageModifier(img);
     34            ImageModifier imageModified;
     35            if (wmsLayer.isRaster())
     36                imageModified = new RasterImageModifier(img);
     37            else
     38                imageModified = new VectorImageModifier(img);
    4139            return new GeorefImage(imageModified.bufferedImage, lambertMin, lambertMax);
    4240        } catch (MalformedURLException e) {
     
    4644
    4745    private URL getURLRaster(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
     46        // 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
     47        final int cRasterX = 1000; // keep width constant and adjust width to original image proportions
    4848        String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
    4949        str += "&layers=CDIF:PMC@";
     
    5252        str += "&bbox=";
    5353        str += wmsLayer.eastNorth2raster(lambertMin, lambertMax);
    54         str += "&width=600&height=600"; // maximum allowed by wms server
     54        //str += "&width=800&height=800"; // maximum allowed by wms server
     55        str += "&width="+cRasterX+"&height="; // maximum allowed by wms server (576/345, 800/378, 1000/634)
     56        str += (int)(cRasterX*(wmsLayer.communeBBox.max.getY() - wmsLayer.communeBBox.min.getY())/(wmsLayer.communeBBox.max.getX() - wmsLayer.communeBBox.min.getX()));
    5557        str += "&exception=application/vnd.ogc.se_inimage&styles=";
    5658        return new URL(str.replace(" ", "%20"));
     
    9496    }
    9597
    96     public String getLastWMSLayerName() {
    97         return lastWMSLayerName;
    98     }
    99 
    100     public void setLastWMSLayerName(String lastWMSLayerName) {
    101         this.lastWMSLayerName = lastWMSLayerName;
    102     }
    103 
    10498}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreInterface.java

    r16791 r17089  
    1414
    1515import javax.swing.JComboBox;
     16import javax.swing.JDialog;
    1617import javax.swing.JOptionPane;
    1718import javax.swing.JPanel;
     
    2627    public HttpURLConnection urlConn = null;
    2728
    28     private CadastreGrabber cadastreGrabber;
    2929    private String cookie;
    3030    private String interfaceRef = null;
     31    private String lastWMSLayerName = null;
    3132    private URL searchFormURL;
    3233    private Vector<String> listOfCommunes = new Vector<String>();
    3334    private Vector<String> listOfTA = new Vector<String>();
     35    class PlanImage {
     36        String name;
     37        String ref;
     38        PlanImage(String name, String ref) {
     39            this.name = name;
     40            this.ref = ref;
     41        }
     42    }
     43    private Vector<PlanImage> listOfFeuilles = new Vector<PlanImage>();
    3444
    3545    final String baseURL = "http://www.cadastre.gouv.fr";
     
    4353
    4454    final String cInterfaceVector = "afficherCarteCommune.do";
    45     final String cInterfaceRaster = "afficherCarteTa.do";
    46 
    47     CadastreInterface(CadastreGrabber cadastreGrabber) {
    48         this.cadastreGrabber = cadastreGrabber;
    49     }
     55    final String cInterfaceRasterTA = "afficherCarteTa.do";
     56    final String cInterfaceRasterFeuille = "afficherCarteFeuille.do";
     57    final String cImageLinkStart = "title=\"image\"><a href=\"#\" onClick=\"popup('afficherCarteFeuille.do?f=";
     58    final String cImageNameStart = ">Feuille ";
    5059
    5160    public boolean retrieveInterface(WMSLayer wmsLayer) throws DuplicateLayerException {
     
    5564        downloadCancelled = false;
    5665        try {
    57             if (cookie == null || !wmsLayer.getName().equals(cadastreGrabber.getLastWMSLayerName())) {
     66            if (cookie == null || !wmsLayer.getName().equals(lastWMSLayerName)) {
    5867                getCookie();
    5968                getInterface(wmsLayer);
    60                 cadastreGrabber.setLastWMSLayerName(wmsLayer.getName());
     69                this.lastWMSLayerName = wmsLayer.getName();
    6170            }
    6271            openInterface();
    6372        } catch (IOException e) {
    64             JOptionPane.showMessageDialog(Main.parent,
     73            /*JOptionPane.showMessageDialog(Main.parent,
    6574                    tr("Town/city {0} not found or not available in WMS.\n" +
    66                             "Please check its availibility on www.cadastre.gouv.fr", wmsLayer.getLocation()));
     75                            "Please check its availibility on www.cadastre.gouv.fr", wmsLayer.getLocation()));*/
     76            JOptionPane pane = new JOptionPane(
     77                    tr("Town/city {0} not found or not available in WMS.\n" +
     78                            "Please check its availibility on www.cadastre.gouv.fr", wmsLayer.getLocation()),
     79                            JOptionPane.INFORMATION_MESSAGE);
     80            // this below is a temporary workaround to fix the "always on top" issue
     81            JDialog dialog = pane.createDialog(Main.parent, tr("Select commune"));
     82            CadastrePlugin.prepareDialog(dialog);
     83            dialog.setVisible(true);
     84            // till here
    6785            return false;
    6886        }
     
    8098                throw new IOException("Cannot get Cadastre cookie.");
    8199            }
     100            System.out.println("GET "+searchFormURL);
    82101            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    83102            while(in.readLine() != null) {}  // read the buffer otherwise we sent POST too early
     
    97116
    98117    public void resetCookie() {
    99         cadastreGrabber.setLastWMSLayerName(null);
     118        lastWMSLayerName = null;
    100119    }
    101120
    102121    public void resetCookieIfNewLayer(String newWMSLayerName) {
    103         if (!newWMSLayerName.equals(cadastreGrabber.getLastWMSLayerName())) {
     122        if (!newWMSLayerName.equals(lastWMSLayerName)) {
    104123            resetCookie();
    105124        }
     
    107126
    108127    public void setCookie() {
    109         urlConn.setRequestProperty("Cookie", cookie);
    110     }
    111 
     128        this.urlConn.setRequestProperty("Cookie", this.cookie);
     129    }
     130
     131    public void setCookie(HttpURLConnection urlConn) {
     132        urlConn.setRequestProperty("Cookie", this.cookie);
     133    }
     134   
    112135    private void getInterface(WMSLayer wmsLayer) throws IOException, DuplicateLayerException {
    113136        // first attempt : search for given name without codeCommune
     
    126149                    interfaceRef = postForm(wmsLayer, wmsLayer.getCodeCommune());
    127150                }
    128                 if (wmsLayer.isRaster() && listOfTA.size() > 1) {
    129                     // commune known but raster format. Select "tableau d'assemblage" from list.
    130                     wmsLayer.setCodeCommune(selectTADialog());
    131                     checkLayerDuplicates(wmsLayer);
    132                     interfaceRef = buildRasterInterfaceRef(wmsLayer.getCodeCommune());
     151                if (listOfCommunes.size() == 1 && wmsLayer.isRaster()) {
     152                    // commune known but raster format. Select "Feuille" (non-georeferenced image) from list.
     153                    int res = selectFeuilleDialog();
     154                    if (res != -1) {
     155                        // TODO
     156                        wmsLayer.setCodeCommune(listOfFeuilles.elementAt(res).name);
     157                        checkLayerDuplicates(wmsLayer);
     158                        interfaceRef = buildRasterFeuilleInterfaceRef(wmsLayer.getCodeCommune());
     159                    }
    133160                }
    134161            }
     
    142169        try {
    143170            // finally, open the interface on server side giving access to the wms server
     171            String lines = null;
     172            String ln = null;
    144173            URL interfaceURL = new URL(baseURL + "/scpc/"+interfaceRef);
    145174            urlConn = (HttpURLConnection)interfaceURL.openConnection();
     
    150179                throw new IOException("Cannot open Cadastre interface. GET response:"+urlConn.getResponseCode());
    151180            }
     181            System.out.println("GET "+interfaceURL);
    152182            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    153             while(in.readLine() != null) {}  // read the buffer otherwise we sent POST too early
    154             System.out.println("GET to open interface sent");
     183            //while(in.readLine() != null) {}  // read the buffer otherwise we sent POST too early
     184            while ((ln = in.readLine()) != null) {
     185                lines += ln;
     186            }
    155187        } catch (MalformedURLException e) {
    156188            throw (IOException) new IOException(
     
    171203     *   <option value="QK066" >COLMAR - 68000</option>
    172204     *   </select>
     205     * The returned string is the interface name used in further requests, e.g. "afficherCarteCommune.do?c=QP224"
     206     * where QP224 is the code commune known by the WMS (or "afficherCarteTa.do?c=..." for raster images).
    173207     *
    174208     * @param location
    175209     * @param codeCommune
    176      * @return retURL url to available cadastre vectorised master piece; "" if not found
     210     * @return retURL url to available code commune in the cadastre; "" if not found
    177211     * @throws IOException
    178212     */
     
    180214        try {
    181215            String ln = null;
    182             String line = null;
     216            String lines = null;
    183217            listOfCommunes.clear();
    184218            listOfTA.clear();
     
    203237            OutputStream wr = urlConn.getOutputStream();
    204238            wr.write(content.getBytes());
     239            System.out.println("POST "+content);
    205240            wr.flush();
    206241            wr.close();
    207242            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    208243            while ((ln = rd.readLine()) != null) {
    209                 line += ln;
     244                lines += ln;
    210245            }
    211246            rd.close();
    212247            urlConn.disconnect();
    213             System.out.println("POST="+line);
    214             if (line.indexOf(cImageFormat) != -1) {
    215                 int i = line.indexOf(cImageFormat);
    216                 int j = line.indexOf(".", i);
    217                 wmsLayer.setRaster(line.substring(i+cImageFormat.length(), j).equals("image"));
    218             }
    219             if (!wmsLayer.isRaster() && line.indexOf(cInterfaceVector) != -1) {  // "afficherCarteCommune.do"
     248            if (lines.indexOf(cImageFormat) != -1) {
     249                int i = lines.indexOf(cImageFormat);
     250                int j = lines.indexOf(".", i);
     251                wmsLayer.setRaster(lines.substring(i+cImageFormat.length(), j).equals("image"));
     252            }
     253            if (!wmsLayer.isRaster() && lines.indexOf(cInterfaceVector) != -1) {  // "afficherCarteCommune.do"
    220254                // shall be something like: interfaceRef = "afficherCarteCommune.do?c=X2269";
    221                 line = line.substring(line.indexOf(cInterfaceVector),line.length());
    222                 line = line.substring(0, line.indexOf("'"));
    223                 System.out.println("interface ref.:"+line);
    224                 return line;
    225             } else if (wmsLayer.isRaster() && line.indexOf(cInterfaceRaster) != -1) { // "afficherCarteTa.do"
    226                 // list of values parsed in listOfTA (Tableau d'assemblage)
    227                 parseTAList(line.substring(line.indexOf(cInterfaceRaster)));
    228                 if (listOfTA.size() == 1) {
    229                     wmsLayer.setCodeCommune(listOfTA.firstElement());
    230                     return buildRasterInterfaceRef(listOfTA.firstElement());
     255                lines = lines.substring(lines.indexOf(cInterfaceVector),lines.length());
     256                lines = lines.substring(0, lines.indexOf("'"));
     257                System.out.println("interface ref.:"+lines);
     258                return lines;
     259            } else if (wmsLayer.isRaster() && lines.indexOf(cInterfaceRasterTA) != -1) { // "afficherCarteTa.do"
     260                // list of values parsed in listOfFeuilles (list all non-georeferenced images)
     261                lines = getFeuillesList();
     262                parseFeuillesList(lines);
     263                if (listOfFeuilles.size() > 0) {
     264                    int res = selectFeuilleDialog();
     265                    if (res != -1) {
     266                        wmsLayer.setCodeCommune(listOfFeuilles.elementAt(res).name);
     267                        checkLayerDuplicates(wmsLayer);
     268                        interfaceRef = buildRasterFeuilleInterfaceRef(wmsLayer.getCodeCommune());
     269                        wmsLayer.setCodeCommune(listOfFeuilles.elementAt(res).ref);
     270                        lines = buildRasterFeuilleInterfaceRef(listOfFeuilles.elementAt(res).ref);
     271                        System.out.println("interface ref.:"+lines);
     272                        return lines;
     273                    }
    231274                }
    232275                return null;
    233             } else if (line.indexOf(cCommuneListStart) != -1 && line.indexOf(cCommuneListEnd) != -1) {
     276            } else if (lines.indexOf(cCommuneListStart) != -1 && lines.indexOf(cCommuneListEnd) != -1) {
    234277                // list of values parsed in listOfCommunes
    235                 int i = line.indexOf(cCommuneListStart);
    236                 int j = line.indexOf(cCommuneListEnd, i);
    237                 parseCommuneList(line.substring(i, j));
     278                int i = lines.indexOf(cCommuneListStart);
     279                int j = lines.indexOf(cCommuneListEnd, i);
     280                parseCommuneList(lines.substring(i, j));
    238281            }
    239282        } catch (MalformedURLException e) {
     
    265308    }
    266309
    267     private void parseTAList(String input) {
    268         while (input.indexOf(cInterfaceRaster) != -1) {
    269             input = input.substring(input.indexOf(cInterfaceRaster));
    270             String codeTA = input.substring(0, input.indexOf("'"));
    271             codeTA = codeTA.substring(codeTA.indexOf("=")+1);
    272             if (!listOfTA.contains(codeTA)) {
    273                 System.out.println("parse "+codeTA);
    274                 listOfTA.add(codeTA);
    275             }
    276             input = input.substring(cInterfaceRaster.length());
    277         }
    278     }
    279 
     310    private String getFeuillesList() {
     311        // get all images in one html page
     312        String ln = null;
     313        String lines = null;
     314        HttpURLConnection urlConn2 = null;
     315        try {
     316            URL getAllImagesURL = new URL(baseURL + "/scpc/listerFeuillesParcommune.do?keepVolatileSession=&offset=2000");
     317            urlConn2 = (HttpURLConnection)getAllImagesURL.openConnection();
     318            setCookie(urlConn2);
     319            urlConn2.connect();
     320            System.out.println("GET "+getAllImagesURL);
     321            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn2.getInputStream()));
     322            while ((ln = rd.readLine()) != null) {
     323                lines += ln;
     324            }
     325            rd.close();
     326            urlConn2.disconnect();
     327            //System.out.println("GET="+lines);
     328        } catch (IOException e) {
     329            listOfFeuilles.clear();
     330            e.printStackTrace();
     331        }
     332        return lines;
     333    }
     334   
     335    private void parseFeuillesList(String input) {
     336        listOfFeuilles.clear();
     337        while (input.indexOf(cImageLinkStart) != -1) {
     338            input = input.substring(input.indexOf(cImageLinkStart)+cImageLinkStart.length());
     339            String refFeuille = input.substring(0, input.indexOf("'"));
     340            String nameFeuille = input.substring(
     341                    input.indexOf(cImageNameStart)+cImageNameStart.length(),
     342                    input.indexOf(" -"));
     343            listOfFeuilles.add(new PlanImage(nameFeuille, refFeuille));
     344        }
     345    }
     346   
    280347    private String selectCommuneDialog() {
    281348        JPanel p = new JPanel(new GridBagLayout());
     
    290357            private static final long serialVersionUID = 1L;
    291358        };
    292         pane.createDialog(Main.parent, tr("Select commune")).setVisible(true);
     359        //pane.createDialog(Main.parent, tr("Select commune")).setVisible(true);
     360        // this below is a temporary workaround to fix the "always on top" issue
     361        JDialog dialog = pane.createDialog(Main.parent, tr("Select commune"));
     362        CadastrePlugin.prepareDialog(dialog);
     363        dialog.setVisible(true);
     364        // till here
    293365        if (!Integer.valueOf(JOptionPane.OK_OPTION).equals(pane.getValue()))
    294366            return null;
     
    297369    }
    298370
    299     private String selectTADialog() {
     371    private int selectFeuilleDialog() {
    300372        JPanel p = new JPanel(new GridBagLayout());
    301         JComboBox inputTAList = new JComboBox(listOfTA);
    302         p.add(inputTAList, GBC.eol().fill(GBC.HORIZONTAL).insets(10, 0, 0, 0));
    303         JOptionPane pane = new JOptionPane(p, JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null) {
    304             private static final long serialVersionUID = 1L;
    305         };
    306         pane.createDialog(Main.parent, tr("Select Tableau d'Assemblage")).setVisible(true);
     373        Vector<String> ImageNames = new Vector<String>();
     374        for (PlanImage src : listOfFeuilles) {
     375            ImageNames.add(src.name);
     376        }
     377        JComboBox inputFeuilleList = new JComboBox(ImageNames);
     378        p.add(inputFeuilleList, GBC.eol().fill(GBC.HORIZONTAL).insets(10, 0, 0, 0));
     379        JOptionPane pane = new JOptionPane(p, JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null);
     380        //pane.createDialog(Main.parent, tr("Select Feuille")).setVisible(true);
     381        // this below is a temporary workaround to fix the "always on top" issue
     382        JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
     383        CadastrePlugin.prepareDialog(dialog);
     384        dialog.setVisible(true);
     385        // till here
    307386        if (!Integer.valueOf(JOptionPane.OK_OPTION).equals(pane.getValue()))
    308             return null;
    309         String result = listOfTA.elementAt(inputTAList.getSelectedIndex());
     387            return -1;
     388        int result = inputFeuilleList.getSelectedIndex();
    310389        return result;
    311390    }
    312391
    313     private String buildRasterInterfaceRef(String codeCommune) {
    314         return cInterfaceRaster + "?f=" + codeCommune;
     392    private String buildRasterFeuilleInterfaceRef(String codeCommune) {
     393        return cInterfaceRasterFeuille + "?f=" + codeCommune;
    315394    }
    316395
     
    324403        content += "&dontSaveLastForward&keepVolatileSession=";
    325404        searchFormURL = new URL(content);
    326         System.out.println("HEAD:"+content);
    327405        urlConn = (HttpURLConnection)searchFormURL.openConnection();
    328406        urlConn.setRequestMethod("GET");
     
    332410            throw new IOException("Cannot get Cadastre response.");
    333411        }
     412        System.out.println("GET "+searchFormURL);
    334413        BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    335414        while ((ln = in.readLine()) != null) {
     
    377456        }
    378457        downloadCancelled = true;
    379         cadastreGrabber.setLastWMSLayerName(null);
     458        lastWMSLayerName = null;
    380459    }
    381460
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastrePlugin.java

    r16929 r17089  
    1010
    1111import javax.swing.JCheckBoxMenuItem;
     12import javax.swing.JDialog;
    1213import javax.swing.JMenu;
    1314import javax.swing.JMenuItem;
     
    135136                menuGrab.setAccelerator(ks);
    136137            }
     138            JMenuItem menuActionGrabPlanImage = new JMenuItem(new MenuActionGrabPlanImage());
    137139            JMenuItem menuSettings = new JMenuItem(new MenuActionNewLocation());
    138140            final JCheckBoxMenuItem menuSource = new JCheckBoxMenuItem(tr("Auto sourcing"));
     
    152154
    153155            cadastreJMenu.add(menuGrab);
     156            cadastreJMenu.add(menuActionGrabPlanImage);
    154157            cadastreJMenu.add(menuSettings);
    155158            cadastreJMenu.add(menuSource);
     
    214217            JMenuItem item = cadastreJMenu.getItem(i);
    215218            if (item != null)
    216                 if (item.getText().equals(MenuActionGrab.name) /* ||
     219                if (item.getText().equals(MenuActionGrab.name) ||
     220                    item.getText().equals(MenuActionGrabPlanImage.name) /* ||
    217221                    item.getText().equals(MenuActionBoundaries.name) ||
    218222                    item.getText().equals(MenuActionBuildings.name)*/) {
     
    229233            if (oldFrame == null && newFrame != null) {
    230234                setEnabledAll(true);
    231                 Main.map.addMapMode(new IconToggleButton
    232                         (new WMSAdjustAction(Main.map)));
     235                /*Main.map.addMapMode(new IconToggleButton
     236                        (new WMSAdjustAction(Main.map)));*/
    233237            } else if (oldFrame != null && newFrame == null) {
    234238                setEnabledAll(false);
     
    246250    }
    247251
     252    public static void safeSleep(long milliseconds) {
     253        try {
     254            Thread.sleep(milliseconds);
     255        } catch (InterruptedException e) {}
     256    }
     257
     258    // See OptionPaneUtil
     259    // FIXME: this is a temporary solution.
     260    public static void prepareDialog(JDialog dialog) {
     261        if (Main.pref.getBoolean("window-handling.option-pane-always-on-top", true)) {
     262            try {
     263                dialog.setAlwaysOnTop(true);
     264            } catch(SecurityException e) {
     265                System.out.println(tr("Warning: failed to put option pane dialog always on top. Exception was: {0}", e.toString()));
     266            }
     267        }
     268        dialog.setModal(true);
     269        dialog.toFront();
     270        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
     271    }
    248272}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastrePreferenceSetting.java

    r16007 r17089  
    5050    JLabel jLabelCacheSize = new JLabel(tr("Max. cache size (in MB)"));
    5151    private JTextField cacheSize = new JTextField(20);
     52   
     53    static final String DEFAULT_RASTER_DIVIDER = "5";
     54    private JTextField rasterDivider = new JTextField(10);
    5255
    5356    public void addGui(final PreferenceDialog gui) {
     
    103106        cadastrewms.add(drawBoundaries, GBC.eop().insets(0, 0, 0, 5));
    104107
    105         // the downloaded images multiplier
    106         JLabel jLabelScale = new JLabel(tr("Image grab multiplier:"));
     108        // the vectorized images multiplier
     109        JLabel jLabelScale = new JLabel(tr("Vector images grab multiplier:"));
    107110        cadastrewms.add(jLabelScale, GBC.std().insets(0, 5, 10, 0));
    108111        ButtonGroup bg = new ButtonGroup();
     
    151154        cadastrewms.add(grabMultiplier4Size, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 0, 5));
    152155
     156        // for raster images (not vectorized), image grab divider (from 1 to 10)
     157        String savedRasterDivider = Main.pref.get("cadastrewms.rasterDivider", DEFAULT_RASTER_DIVIDER);
     158        JLabel jLabelRasterDivider = new JLabel(tr("Raster images grab multiplier:"));
     159        rasterDivider.setText(savedRasterDivider);
     160        rasterDivider.setToolTipText("Raster image grab division, from 1 to 10; 10 is very high definition");
     161        cadastrewms.add(jLabelRasterDivider, GBC.std().insets(0, 5, 10, 0));
     162        cadastrewms.add(rasterDivider, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 200, 5));
     163
    153164        // option to enable automatic caching
    154165        enableCache.addActionListener(new ActionListener() {
     
    167178        cacheSize.setToolTipText(tr("Oldest files are automatically deleted when this size is exceeded"));
    168179        cadastrewms.add(jLabelCacheSize, GBC.std().insets(20, 0, 0, 0));
    169         cadastrewms.add(cacheSize, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 0, 5));
    170 
     180        cadastrewms.add(cacheSize, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 200, 5));
     181       
    171182        cadastrewms.add(Box.createVerticalGlue(), GBC.eol().fill(GBC.VERTICAL));
    172183
     
    196207            }
    197208        }
     209        try {
     210            int i = Integer.parseInt(rasterDivider.getText());
     211            if (i > 0 && i < 11)
     212                Main.pref.put("cadastrewms.rasterDivider", String.valueOf(i));
     213        } catch (NumberFormatException e) { // ignore the last input
     214        }
    198215        Main.pref.put("cadastrewms.enableCaching", enableCache.isSelected());
    199216
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java

    r16619 r17089  
    205205            URL url = null;
    206206            url = getURLsvg(bbox);
    207             System.out.println("grab:"+url);
    208207            return grabSVG(url);
    209208        } catch (MalformedURLException e) {
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGTask.java

    r16619 r17089  
    4747
    4848    public DownloadSVGTask(WMSLayer wmsLayer) {
    49         super(tr("Downloading {0}", wmsLayer.name));
     49        super(tr("Downloading {0}", wmsLayer.getName()));
    5050
    5151        this.wmsLayer = wmsLayer;
     
    161161            URL url = null;
    162162            url = getURLsvg(bbox);
    163             System.out.println("grab:"+url);
    164163            return grabSVG(url);
    165164        } catch (MalformedURLException e) {
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadWMSVectorImage.java

    r17085 r17089  
    1010import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    1111
    12 public class DownloadWMSTask extends PleaseWaitRunnable {
     12public class DownloadWMSVectorImage extends PleaseWaitRunnable {
    1313
    1414    private WMSLayer wmsLayer;
     
    1818    private CadastreGrabber grabber = CadastrePlugin.cadastreGrabber;
    1919
    20     public DownloadWMSTask(WMSLayer wmsLayer, Bounds bounds) {
    21         super(tr("Downloading {0}", wmsLayer.name));
     20    public DownloadWMSVectorImage(WMSLayer wmsLayer, Bounds bounds) {
     21        super(tr("Downloading {0}", wmsLayer.getName()));
    2222
    2323        this.wmsLayer = wmsLayer;
     
    6767        Bounds bounds = new Bounds(mv.getLatLon(0, mv.getHeight()), mv.getLatLon(mv.getWidth(), 0));
    6868
    69         Main.worker.execute(new DownloadWMSTask(wmsLayer, bounds));
     69        Main.worker.execute(new DownloadWMSVectorImage(wmsLayer, bounds));
    7070
    7171    }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/GeorefImage.java

    r15961 r17089  
    1515import java.io.ObjectOutputStream;
    1616import java.io.Serializable;
     17
    1718import javax.imageio.ImageIO;
    1819
     
    2324    private static final long serialVersionUID = 1L;
    2425
    25     public EastNorth min, max;
    26 
    27     public EastNorth org_min, org_max;
    28 
     26    public EastNorth min;
     27    public EastNorth max;
    2928    public BufferedImage image;
    3029
    31     private double angle = 0; // in radian
    32 
    33     private BufferedImage rotated_image; // only if angle <> 0
    34 
    35     double pixelPerEast;
    36     double pixelPerNorth;
     30    private double pixelPerEast;
     31    private double pixelPerNorth;
    3732
    3833    public GeorefImage(BufferedImage img, EastNorth min, EastNorth max) {
     
    4338    }
    4439
    45     public void displace(double dx, double dy) {
    46         min = new EastNorth(min.east() + dx, min.north() + dy);
    47         max = new EastNorth(max.east() + dx, max.north() + dy);
    48     }
    49 
    50     public void resize(EastNorth rasterCenter, double proportion) {
    51         min = min.interpolate(rasterCenter, proportion);
    52         max = max.interpolate(rasterCenter, proportion);
    53         updatePixelPer();
    54     }
    55 
    56     public void rotate(EastNorth pivot, double delta) {
    57         if (angle == 0) {
    58             org_min = min;
    59             org_max = max;
    60         }
    61         this.angle += delta;
    62 
    63         EastNorth imageCenter = org_min.interpolate(org_max, 0.5);
    64         EastNorth newimageCenter = imageCenter.rotate(pivot, angle);
    65         min.setLocation(org_min.east() + newimageCenter.east()-imageCenter.east(),
    66                 org_min.north() + newimageCenter.north()-imageCenter.north());
    67         max.setLocation(org_max.east() + newimageCenter.east()-imageCenter.east(),
    68                 org_max.north() + newimageCenter.north()-imageCenter.north());
    69         EastNorth min2 = new EastNorth(min.east(), max.north());
    70         EastNorth max2 = new EastNorth(max.east(), min.north());
    71         min = org_min.rotate(newimageCenter, angle);
    72         max = org_max.rotate(newimageCenter, angle);
    73         min2 = min2.rotate(newimageCenter, angle);
    74         max2 = max2.rotate(newimageCenter, angle);
    75         getNewBounding(min, max, min2, max2);
    76 
    77         rotated_image = tilt(image, angle);
    78     }
    79 
    80     public static BufferedImage tilt(BufferedImage image, double angle) {
    81         double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    82         int w = image.getWidth(), h = image.getHeight();
    83         int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);
    84         GraphicsConfiguration gc = getDefaultConfiguration();
    85         BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
    86         Graphics2D g = result.createGraphics();
    87         g.translate((neww-w)/2, (newh-h)/2);
    88         g.rotate(angle, w/2, h/2);
    89         g.drawRenderedImage(image, null);
    90         g.dispose();
    91         return result;
    92     }
    9340    public static GraphicsConfiguration getDefaultConfiguration() {
    9441        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
     
    12774            return;
    12875
    129         BufferedImage toDisplay;
    130         if (angle != 0)
    131             toDisplay = rotated_image;
    132         else
    133             toDisplay = image;
    134 
    13576        Point minPt = nc.getPoint(min), maxPt = nc.getPoint(max);
    13677
     
    14485            g.drawRect(minPt.x, maxPt.y, maxPt.x - minPt.x, minPt.y - maxPt.y);
    14586        }
    146         g.drawImage(toDisplay, minPt.x, maxPt.y, maxPt.x, minPt.y, // dest
    147                 0, 0, toDisplay.getWidth(), toDisplay.getHeight(), // src
     87        g.drawImage(image, minPt.x, maxPt.y, maxPt.x, minPt.y, // dest
     88                0, 0, image.getWidth(), image.getHeight(), // src
    14889                null);
    14990        if (backgroundTransparent && transparency < 1.0f)
     
    183124            for (int x = minXMaskPixel; x < minXMaskPixel + widthXMaskPixel; x++)
    184125                for (int y = minYMaskPixel; y < minYMaskPixel + heightYMaskPixel; y++)
    185                     image.setRGB(x, y, ImageModifier.cadastreBackgroundTransp);
     126                    image.setRGB(x, y, VectorImageModifier.cadastreBackgroundTransp);
    186127            g.dispose();
    187128        }
    188129    }
    189130
     131    /*
     132     * Method required by BufferedImage serialization
     133     */
    190134    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    191135        max = (EastNorth) in.readObject();
     
    195139    }
    196140
    197 
    198     private void updatePixelPer() {
    199         pixelPerEast = image.getWidth()/(max.east()-min.east());
    200         pixelPerNorth = image.getHeight()/(max.north()-min.north());
    201     }
    202 
     141    /*
     142     * Method required by BufferedImage serialization
     143     */
    203144    private void writeObject(ObjectOutputStream out) throws IOException {
    204145        out.writeObject(max);
     
    207148    }
    208149
     150    private void updatePixelPer() {
     151        pixelPerEast = image.getWidth()/(max.east()-min.east());
     152        pixelPerNorth = image.getHeight()/(max.north()-min.north());
     153    }
     154
     155    public double getPixelPerEast() {
     156        return pixelPerEast;
     157    }
     158
     159    public double getPixelPerNorth() {
     160        return pixelPerNorth;
     161    }
     162
    209163    @Override
    210164    public String toString() {
     
    212166    }
    213167
     168    /*
     169     * Following methods are used for affine transformation of two points p1 and p2
     170     */
     171    /**
     172     * Add a translation (dx, dy) to this image min,max coordinates
     173     * @param dx delta added to X image coordinate
     174     * @param dy delta added to Y image coordinate
     175     */
     176    public void shear(double dx, double dy) {
     177        min = new EastNorth(min.east() + dx, min.north() + dy);
     178        max = new EastNorth(max.east() + dx, max.north() + dy);
     179    }
     180   
     181    /**
     182     * Change this image scale by moving the min,max coordinates around an anchor
     183     * @param anchor
     184     * @param proportion
     185     */
     186    public void scale(EastNorth anchor, double proportion) {
     187        min = anchor.interpolate(min, proportion);
     188        max = anchor.interpolate(max, proportion);
     189        updatePixelPer();
     190    }
     191
     192    /**
     193     * Rotate this image and its min/max coordinates around anchor point
     194     * @param anchor anchor of rotation
     195     * @param angle angle of rotation (in radians)
     196     */
     197    public void rotate(EastNorth anchor, double angle) {
     198        EastNorth min2 = new EastNorth(min.east(), max.north());
     199        EastNorth max2 = new EastNorth(max.east(), min.north());
     200        min = min.rotate(anchor, angle);
     201        max = max.rotate(anchor, angle);
     202        min2 = min2.rotate(anchor, angle);
     203        max2 = max2.rotate(anchor, angle);
     204        getNewBounding(min, max, min2, max2);
     205        image = tilt(image, angle);
     206    }
     207
     208    /**
     209     * Rotate by copying original buffered image into a new one with new dimensions
     210     * @param image
     211     * @param angle
     212     * @return
     213     */
     214    public static BufferedImage tilt(BufferedImage image, double angle) {
     215        double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
     216        int w = image.getWidth(), h = image.getHeight();
     217        int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);
     218        GraphicsConfiguration gc = getDefaultConfiguration();
     219        BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
     220        Graphics2D g = result.createGraphics();
     221        g.translate((neww-w)/2, (newh-h)/2);
     222        g.rotate(angle, w/2, h/2);
     223        g.drawRenderedImage(image, null);
     224        g.dispose();
     225        return result;
     226    }
     227
    214228}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/ImageModifier.java

    r15961 r17089  
    11package cadastre_fr;
    22
    3 import java.awt.Color;
    43import java.awt.image.BufferedImage;
    5 import java.awt.image.ColorModel;
    6 import java.awt.image.IndexColorModel;
    7 import java.awt.image.WritableRaster;
    8 import org.openstreetmap.josm.Main;
    9 import org.openstreetmap.josm.tools.ColorHelper;
    104
    11 public class ImageModifier {
    12 
     5public abstract class ImageModifier {
    136    /**
    147     * Current background color used by cadastre.gouv.fr
    158     */
     9    //public static int cadastreBackgroundTransp = 1; // original white but transparent
     10
    1611    private static final long serialVersionUID = 1L;
    17 
    18     public static final int cadastreBackground = -1; // white
    19 
    20     public static final int cadastreBackgroundTransp = 1; // original white but transparent
    2112
    2213    public BufferedImage bufferedImage;
    2314
    24     private boolean withBackground = false;
    25 
    26     private int backgroundPixel = 0;
    27 
    28     private int backgroundSampleX, backgroundSampleY;
    29 
    30     public ImageModifier(BufferedImage bi) {
    31         bufferedImage = bi;
    32         if (Main.pref.getBoolean("cadastrewms.backgroundTransparent"))
    33             makeTransparent();
    34         else if (Main.pref.getBoolean("cadastrewms.alterColors"))
    35             replaceBackground();
    36 
    37         if (Main.pref.getBoolean("cadastrewms.invertGrey"))
    38             invertGrey();
    39     }
    40 
    41     /**
    42      * Replace the background color by the josm color.background color.
    43      */
    44     private void replaceBackground() {
    45         int w = bufferedImage.getWidth();
    46         int h = bufferedImage.getHeight();
    47         int josmBackgroundColor = ColorHelper.html2color(Main.pref.get("color.background", "#000000")).getRGB();
    48         for (int x = 0; x < w; x++) {
    49             for (int y = 0; y < h; y++) {
    50                 int pixel = bufferedImage.getRGB(x, y);
    51                 if (pixel == cadastreBackground) {
    52                     bufferedImage.setRGB(x, y, josmBackgroundColor);
    53                     if (!withBackground)
    54                         withBackground = true;
    55                     backgroundSampleX = x;
    56                     backgroundSampleY = y;
    57                 }
    58             }
    59         }
    60     }
    61 
    62     /**
    63      * Invert black/white/grey pixels (to change original black characters to white).
    64      */
    65     private void invertGrey() {
    66         int w = bufferedImage.getWidth();
    67         int h = bufferedImage.getHeight();
    68         for (int x = 0; x < w; x++) {
    69             for (int y = 0; y < h; y++) {
    70                 int pixel = bufferedImage.getRGB(x, y);
    71                 if (pixel != cadastreBackground) {
    72                     bufferedImage.setRGB(x, y, reverseIfGrey(pixel));
    73                 }
    74             }
    75         }
    76     }
    77 
    78     /**
    79      * Reverse the grey value if the pixel is grey (light grey becomes dark grey)
    80      * Used for texts.
    81      * @param pixel
    82      * @return
    83      */
    84     private int reverseIfGrey(int pixel) {
    85         Color col = new Color(pixel);
    86         int r = col.getRed();
    87         int g = col.getGreen();
    88         int b = col.getBlue();
    89         if ((b == r) && (b == g)) {
    90             pixel = (0x00 << 32) + ((byte) (255 - r) << 16) + ((byte) (255 - r) << 8) + ((byte) (255 - r));
    91         }
    92         return pixel;
    93     }
    94 
    95     private void makeTransparent() {
    96         ColorModel colorModel = bufferedImage.getColorModel();
    97         if (bufferedImage.getColorModel() instanceof IndexColorModel) {
    98             // vector image (IndexColorModel)
    99             IndexColorModel icm = (IndexColorModel) colorModel;
    100             WritableRaster raster = bufferedImage.getRaster();
    101             // pixel is offset in ICM's palette
    102             if (withBackground)
    103                 backgroundPixel = raster.getSample(backgroundSampleX, backgroundSampleY, 0);
    104             else
    105                 backgroundPixel = 1; // default Cadastre background sample
    106             int size = icm.getMapSize();
    107             byte[] reds = new byte[size];
    108             byte[] greens = new byte[size];
    109             byte[] blues = new byte[size];
    110             icm.getReds(reds);
    111             icm.getGreens(greens);
    112             icm.getBlues(blues);
    113             IndexColorModel icm2 = new IndexColorModel(colorModel.getPixelSize(), size, reds, greens, blues,
    114                     backgroundPixel);
    115             bufferedImage = new BufferedImage(icm2, raster, bufferedImage.isAlphaPremultiplied(), null);
    116         } else {
    117             int width = bufferedImage.getWidth();
    118             int height = bufferedImage.getHeight();
    119             BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    120             for (int y = 0; y < height; y++) {
    121                 for (int x = 0; x < width; x++) {
    122                     Color c = new Color(bufferedImage.getRGB(x, y));
    123                     int r = c.getRed();
    124                     int g = c.getGreen();
    125                     int b = c.getBlue();
    126                     Color maskedColor;
    127                     if (r==0 && g==0 && b==0) {
    128                         maskedColor = new Color(r, g, b, 0x00);
    129                     } else {
    130                         maskedColor = new Color(r, g, b, 0xFF);
    131                     }
    132                     bi.setRGB(x, y, maskedColor.getRGB());
    133                 }
    134             }
    135             bufferedImage = bi;
    136         }
    137         return;
    138     }
    13915}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/MenuActionGrab.java

    r16929 r17089  
    3232                WMSLayer wmsLayer = WMSDownloadAction.getLayer();
    3333                if (wmsLayer != null)
    34                     DownloadWMSTask.download(wmsLayer);
     34                    DownloadWMSVectorImage.download(wmsLayer);
    3535            } else {
    3636                JOptionPane.showMessageDialog(Main.parent,
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/MenuActionLoadFromCache.java

    r15961 r17089  
    5252            if (Main.map != null) {
    5353                for (Layer l : Main.map.mapView.getAllLayers()) {
    54                     if (l instanceof WMSLayer && l.name.equals(location)) {
     54                    if (l instanceof WMSLayer && l.getName().equals(location)) {
    5555                        System.out.println("The location " + filename + " is already on screen. Cache not loaded.");
    5656                        continue nextFile;
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/MenuActionNewLocation.java

    r15961 r17089  
    3030        WMSLayer wmsLayer = addNewLayer(new ArrayList<WMSLayer>());
    3131        if (wmsLayer != null)
    32             DownloadWMSTask.download(wmsLayer);
     32            DownloadWMSVectorImage.download(wmsLayer);
    3333    }
    3434
     
    7979                Main.pref.put("cadastrewms.codeCommune", codeCommune);
    8080                for (Layer l : Main.map.mapView.getAllLayers()) {
    81                     if (l instanceof WMSLayer && l.name.equalsIgnoreCase(location + codeDepartement)) {
     81                    if (l instanceof WMSLayer && l.getName().equalsIgnoreCase(location + codeDepartement)) {
    8282                        return null;
    8383                    }
     
    9393
    9494            if (resetCookie)
    95                 CadastrePlugin.cadastreGrabber.getWmsInterface().resetCookieIfNewLayer(wmsLayer.name);
     95                CadastrePlugin.cadastreGrabber.getWmsInterface().resetCookieIfNewLayer(wmsLayer.getName());
    9696            return wmsLayer;
    9797        }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSDownloadAction.java

    r15961 r17089  
    2121
    2222    public void actionPerformed(ActionEvent e) {
    23         DownloadWMSTask.download(getLayer());
     23        DownloadWMSVectorImage.download(getLayer());
    2424    }
    2525
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java

    r16791 r17089  
    66import java.awt.Graphics;
    77import java.awt.Graphics2D;
     8import java.awt.Image;
    89import java.awt.Toolkit;
    910import java.awt.image.BufferedImage;
     11import java.awt.image.ImageObserver;
    1012import java.io.EOFException;
    1113import java.io.IOException;
     
    1315import java.io.ObjectOutputStream;
    1416import java.util.ArrayList;
     17import java.util.Vector;
    1518
    1619import javax.swing.Icon;
     
    3538 * server load.
    3639 */
    37 public class WMSLayer extends Layer {
     40public class WMSLayer extends Layer implements ImageObserver {
    3841
    3942    Component[] component = null;
     
    4447            CadastrePlugin.class.getResource("/images/cadastre_small.png")));
    4548
    46     protected ArrayList<GeorefImage> images = new ArrayList<GeorefImage>();
     49    protected Vector<GeorefImage> images = new Vector<GeorefImage>();
    4750
    4851    protected final int serializeFormatVersion = 2;
     
    5659    private String codeCommune = "";
    5760
    58     private EastNorthBound communeBBox = new EastNorthBound(new EastNorth(0,0), new EastNorth(0,0));
     61    public EastNorthBound communeBBox = new EastNorthBound(new EastNorth(0,0), new EastNorth(0,0));
    5962
    6063    private boolean isRaster = false;
    6164
    6265    private EastNorth rasterMin;
    63 
    64     private EastNorth rasterCenter;
    65 
     66    private EastNorth rasterMax;
    6667    private double rasterRatio;
    67 
    68     double cRasterMaxSizeX = 12286;
    69     double cRasterMaxSizeY = 8730;
     68   
     69    private JMenuItem saveAsPng;
    7070
    7171    public WMSLayer() {
     
    9494
    9595    public void grab(CadastreGrabber grabber, Bounds b) throws IOException {
    96         divideBbox(b, Integer.parseInt(Main.pref.get("cadastrewms.scale", Scale.X1.toString())));
     96        if (isRaster) {
     97            b = new Bounds(Main.proj.eastNorth2latlon(rasterMin), Main.proj.eastNorth2latlon(rasterMax));
     98            divideBbox(b, Integer.parseInt(Main.pref.get("cadastrewms.rasterDivider",
     99                    CadastrePreferenceSetting.DEFAULT_RASTER_DIVIDER)));
     100        } else
     101            divideBbox(b, Integer.parseInt(Main.pref.get("cadastrewms.scale", Scale.X1.toString())));
    97102
    98103        for (EastNorthBound n : dividedBbox) {
     
    148153        double dNorth = (lambertMax.north() - minNorth) / factor;
    149154        dividedBbox.clear();
    150         if (factor < 4) {
     155        if (factor < 4 || isRaster) {
    151156            for (int xEast = 0; xEast < factor; xEast++)
    152157                for (int xNorth = 0; xNorth < factor; xNorth++) {
     
    177182        if (isRaster) {
    178183            str += "\n"+tr("Is not vectorized.");
    179             str += "\n"+tr("Raster center: {0}", rasterCenter);
     184            str += "\n"+tr("Raster size: {0}", communeBBox);
    180185        } else
    181186            str += "\n"+tr("Is vectorized.");
     
    195200    @Override
    196201    public void paint(Graphics g, final MapView mv) {
    197         for (GeorefImage img : images)
    198             img.paint((Graphics2D) g, mv, CadastrePlugin.backgroundTransparent,
    199                     CadastrePlugin.transparency, CadastrePlugin.drawBoundaries);
     202        synchronized(this){
     203            for (GeorefImage img : images)
     204                img.paint((Graphics2D) g, mv, CadastrePlugin.backgroundTransparent,
     205                        CadastrePlugin.transparency, CadastrePlugin.drawBoundaries);
     206        }
    200207    }
    201208
     
    215222    @Override
    216223    public Component[] getMenuEntries() {
     224        saveAsPng = new JMenuItem(new MenuActionSaveRasterAs(this));
     225        saveAsPng.setEnabled(isRaster);
    217226        component = new Component[] { new JMenuItem(LayerListDialog.getInstance().createShowHideLayerAction(this)),
    218                 new JMenuItem(LayerListDialog.getInstance().createDeleteLayerAction(this)), new JMenuItem(new MenuActionLoadFromCache()),
    219                 new JMenuItem(new LayerListPopup.InfoAction(this)) };
     227                new JMenuItem(LayerListDialog.getInstance().createDeleteLayerAction(this)),
     228                new JMenuItem(new MenuActionLoadFromCache()),
     229                saveAsPng,
     230                new JMenuItem(new LayerListPopup.InfoAction(this)),
     231               
     232        };
    220233        return component;
    221234    }
     
    245258
    246259    public void saveToCache(GeorefImage image) {
    247         if (CacheControl.cacheEnabled) {
     260        if (CacheControl.cacheEnabled && !isRaster()) {
    248261            getCacheControl().saveCache(image);
    249262        }
     
    303316    public void setRaster(boolean isRaster) {
    304317        this.isRaster = isRaster;
    305     }
    306 
    307     /**
    308      * Set the eastNorth position in rasterMin which is the 0,0 coordinate (bottom left corner).
    309      * The bounds width is the raster width and height is calculate on a fixed image ratio.
    310      * @param bounds
     318        if (saveAsPng != null)
     319            saveAsPng.setEnabled(isRaster);
     320    }
     321
     322    /**
     323     * Set raster positions used for grabbing and georeferencing.
     324     * rasterMin is the Eaast North of bottom left corner raster image on the screen when image is grabbed.
     325     * The bounds width and height are the raster width and height. The image width matches the current view
     326     * and the image height is adapted.
     327     * Required: the communeBBox must be set (normally it is catched by CadastreInterface and saved by DownloadWMSPlanImage)   
     328     * @param bounds the current main map view boundaries
    311329     */
    312330    public void setRasterBounds(Bounds bounds) {
    313         rasterMin = new EastNorth(Main.proj.latlon2eastNorth(bounds.min).east(), Main.proj.latlon2eastNorth(bounds.min).north());
    314         EastNorth rasterMax = new EastNorth(Main.proj.latlon2eastNorth(bounds.max).east(), Main.proj.latlon2eastNorth(bounds.max).north());
    315         // now, resize on same proportion as wms server raster images (bounds center)
    316         double rasterHalfHeight = (rasterMax.east() - rasterMin.east())/cRasterMaxSizeX*cRasterMaxSizeY/2;
    317         double rasterMid = rasterMin.north() + (rasterMax.north()-rasterMin.north())/2;
    318         rasterMin.setLocation(rasterMin.east(), rasterMid - rasterHalfHeight);
    319         rasterMax.setLocation(rasterMax.east(), rasterMid + rasterHalfHeight);
    320         rasterCenter = new EastNorth(rasterMin.east()+(rasterMax.east()-rasterMin.east())/2,
    321                 rasterMin.north()+(rasterMax.north()-rasterMin.north())/2);
    322         rasterRatio = (rasterMax.east() - rasterMin.east()) / cRasterMaxSizeX;
    323     }
    324 
    325     public EastNorth getRasterMin() {
    326         return rasterMin;
    327     }
    328 
    329     public void setRasterMin(EastNorth rasterMin) {
    330         this.rasterMin = rasterMin;
    331     }
    332 
    333     public void displace(double dx, double dy) {
    334         this.rasterMin = new EastNorth(rasterMin.east() + dx, rasterMin.north() + dy);
    335         this.rasterCenter = new EastNorth(rasterCenter.east() + dx, rasterCenter.north() + dy);
    336         for (GeorefImage img : images)
    337             img.displace(dx, dy);
    338     }
    339 
    340     public void resize(double proportion) {
    341         this.rasterMin = rasterMin.interpolate(rasterCenter, proportion);
    342         for (GeorefImage img : images)
    343             img.resize(rasterCenter, proportion);
    344     }
    345 
    346     public void rotate(double angle) {
    347         this.rasterMin = rasterMin.rotate(rasterCenter, angle);
    348         for (GeorefImage img : images)
    349             img.rotate(rasterCenter, angle);
     331        EastNorth rasterCenter = Main.proj.latlon2eastNorth(bounds.getCenter());
     332        EastNorth eaMin = Main.proj.latlon2eastNorth(bounds.min);
     333        EastNorth eaMax = Main.proj.latlon2eastNorth(bounds.max);
     334        double rasterSizeX = communeBBox.max.getX() - communeBBox.min.getX();
     335        double rasterSizeY = communeBBox.max.getY() - communeBBox.min.getY();
     336        double ratio = rasterSizeY/rasterSizeX;
     337        // keep same ratio on screen as WMS bbox (stored in communeBBox)
     338        rasterMin = new EastNorth(eaMin.getX(), rasterCenter.getY()-(eaMax.getX()-eaMin.getX())*ratio/2);
     339        rasterMax = new EastNorth(eaMax.getX(), rasterCenter.getY()+(eaMax.getX()-eaMin.getX())*ratio/2);
     340        rasterRatio = (rasterMax.getX()-rasterMin.getX())/rasterSizeX;
    350341    }
    351342
     
    363354        if (this.isRaster) {
    364355            oos.writeObject(this.rasterMin);
    365             oos.writeObject(this.rasterCenter);
     356            oos.writeObject(this.rasterMax);
    366357            oos.writeDouble(this.rasterRatio);
    367         } else {
    368             oos.writeObject(this.communeBBox);
    369         }
    370         for (GeorefImage img : imgs) {
    371             oos.writeObject(img);
     358        }
     359        oos.writeObject(this.communeBBox);
     360        synchronized(this){
     361            for (GeorefImage img : imgs) {
     362                oos.writeObject(img);
     363            }
    372364        }
    373365    }
     
    389381        this.setCodeCommune((String) ois.readObject());
    390382        this.lambertZone = ois.readInt();
    391         this.isRaster = ois.readBoolean();
     383        this.setRaster(ois.readBoolean());
    392384        if (this.isRaster) {
    393385            this.rasterMin = (EastNorth) ois.readObject();
    394             this.rasterCenter = (EastNorth) ois.readObject();
     386            this.rasterMax = (EastNorth) ois.readObject();
    395387            this.rasterRatio = ois.readDouble();
    396         } else {
    397             this.communeBBox = (EastNorthBound) ois.readObject();
    398         }
     388        }
     389        this.communeBBox = (EastNorthBound) ois.readObject();
    399390        if (this.lambertZone != currentLambertZone) {
    400391            JOptionPane.showMessageDialog(Main.parent, tr("Lambert zone {0} in cache "+
     
    403394            return false;
    404395        }
    405         boolean EOF = false;
    406         try {
    407             while (!EOF) {
    408                 GeorefImage newImage = (GeorefImage) ois.readObject();
    409                 for (GeorefImage img : this.images) {
    410                     if (CadastrePlugin.backgroundTransparent) {
    411                         if (img.overlap(newImage))
    412                             // mask overlapping zone in already grabbed image
    413                             img.withdraw(newImage);
    414                         else
    415                             // mask overlapping zone in new image only when
    416                             // new image covers completely the existing image
    417                             newImage.withdraw(img);
     396        synchronized(this){
     397            boolean EOF = false;
     398            try {
     399                while (!EOF) {
     400                    GeorefImage newImage = (GeorefImage) ois.readObject();
     401                    for (GeorefImage img : this.images) {
     402                        if (CadastrePlugin.backgroundTransparent) {
     403                            if (img.overlap(newImage))
     404                                // mask overlapping zone in already grabbed image
     405                                img.withdraw(newImage);
     406                            else
     407                                // mask overlapping zone in new image only when
     408                                // new image covers completely the existing image
     409                                newImage.withdraw(img);
     410                        }
    418411                    }
     412                    this.images.add(newImage);
    419413                }
    420                 this.images.add(newImage);
    421             }
    422         } catch (EOFException ex) {
    423             // expected exception when all images are read
     414            } catch (EOFException ex) {
     415                // expected exception when all images are read
     416            }
    424417        }
    425418        return true;
    426419    }
    427 
    428     public double getRasterRatio() {
    429         return rasterRatio;
    430     }
    431 
    432     public void setRasterRatio(double rasterRatio) {
    433         this.rasterRatio = rasterRatio;
    434     }
    435 
    436     public EastNorth getRasterCenter() {
    437         return rasterCenter;
    438     }
    439 
    440     public void setRasterCenter(EastNorth rasterCenter) {
    441         this.rasterCenter = rasterCenter;
     420   
     421    /**
     422     * Join the grabbed images into one single.
     423     * Works only for images grabbed from non-georeferenced images (Feuilles cadastrales)(same amount of
     424     * images in x and y)
     425     */
     426    public void joinRasterImages() {
     427        if (images.size() > 1) {
     428            EastNorth min = images.get(0).min;
     429            EastNorth max = images.get(images.size()-1).max;
     430            int oldImgWidth = images.get(0).image.getWidth();
     431            int oldImgHeight = images.get(0).image.getHeight();
     432            int newWidth = oldImgWidth*(int)Math.sqrt(images.size());
     433            int newHeight = oldImgHeight*(int)Math.sqrt(images.size());
     434            BufferedImage new_img = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
     435            Graphics g = new_img.getGraphics();
     436            // Coordinate (0,0) is on top,left corner where images are grabbed from bottom left
     437            int rasterDivider = (int)Math.sqrt(images.size());
     438            for (int h = 0; h < rasterDivider; h++) {
     439                for (int v = 0; v < rasterDivider; v++) {
     440                    int newx = h*oldImgWidth;
     441                    int newy = newHeight - oldImgHeight - (v*oldImgHeight);
     442                    int j = h*rasterDivider + v;
     443                    g.drawImage(images.get(j).image, newx, newy, this);
     444                }
     445            }
     446            synchronized(this) {
     447                images.clear();
     448                images.add(new GeorefImage(new_img, min, max));
     449            }
     450        }
     451    }
     452   
     453    /**
     454     * Image cropping based on two EN coordinates pointing to two corners in diagonal
     455     * Because it's coming from user mouse clics, we have to sort de positions first.
     456     * Works only for raster image layer (only one image in collection).
     457     * Updates layer georeferences.
     458     * @param en1
     459     * @param en2
     460     */
     461    public void cropImage(EastNorth en1, EastNorth en2){
     462        // adj1 is corner bottom, left
     463        EastNorth adj1 = new EastNorth(en1.east() <= en2.east() ? en1.east() : en2.east(),
     464                en1.north() <= en2.north() ? en1.north() : en2.north());
     465        // adj2 is corner top, right
     466        EastNorth adj2 = new EastNorth(en1.east() > en2.east() ? en1.east() : en2.east(),
     467                en1.north() > en2.north() ? en1.north() : en2.north());
     468        // s1 and s2 have 0,0 at top, left where all EastNorth coord. have 0,0 at bottom, left
     469        int sx1 = (int)((adj1.getX() - images.get(0).min.getX())*images.get(0).getPixelPerEast());
     470        int sy1 = (int)((images.get(0).max.getY() - adj2.getY())*images.get(0).getPixelPerNorth());
     471        int sx2 = (int)((adj2.getX() - images.get(0).min.getX())*images.get(0).getPixelPerEast());
     472        int sy2 = (int)((images.get(0).max.getY() - adj1.getY())*images.get(0).getPixelPerNorth());
     473        int newWidth = Math.abs(sx2 - sx1);
     474        int newHeight = Math.abs(sy2 - sy1);
     475        BufferedImage new_img = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
     476        Graphics g = new_img.getGraphics();
     477        g.drawImage(images.get(0).image, 0, 0, newWidth-1, newHeight-1,
     478                (int)sx1, (int)sy1, (int)sx2, (int)sy2,
     479                this);
     480        images.set(0, new GeorefImage(new_img, adj1, adj2));
     481        // important: update the layer georefs !
     482        rasterMin = adj1;
     483        rasterMax = adj2;
     484        rasterRatio = (rasterMax.getX()-rasterMin.getX())/(communeBBox.max.getX() - communeBBox.min.getX());
     485        setCommuneBBox(new EastNorthBound(new EastNorth(0,0), new EastNorth(newWidth-1,newHeight-1)));
    442486    }
    443487
     
    450494    }
    451495
     496    /**
     497     * Method required by ImageObserver when drawing an image
     498     */
     499    public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
     500        return false;
     501    }
     502
    452503}
Note: See TracChangeset for help on using the changeset viewer.