source: osm/applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastrePlugin.java@ 26510

Last change on this file since 26510 was 26510, checked in by pieren, 13 years ago

Improve configuration checks to avoid complains like the one reported in JOSM ticket #6632

  • Property svn:eol-style set to native
File size: 21.8 KB
Line 
1// License: GPL. v2 and later. Copyright 2008-2009 by Pieren <pieren3@gmail.com> and others
2package cadastre_fr;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.marktr;
6import static org.openstreetmap.josm.tools.I18n.tr;
7
8import java.awt.event.ActionEvent;
9import java.awt.event.ActionListener;
10import java.awt.event.KeyEvent;
11import java.io.File;
12
13import javax.swing.JCheckBoxMenuItem;
14import javax.swing.JDialog;
15import javax.swing.JMenu;
16import javax.swing.JMenuItem;
17import javax.swing.JOptionPane;
18import javax.swing.KeyStroke;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.actions.JosmAction;
22import org.openstreetmap.josm.actions.UploadAction;
23import org.openstreetmap.josm.gui.MainMenu;
24import org.openstreetmap.josm.gui.MapFrame;
25import org.openstreetmap.josm.gui.IconToggleButton;
26import org.openstreetmap.josm.gui.layer.Layer;
27import org.openstreetmap.josm.gui.preferences.PreferenceSetting;
28import org.openstreetmap.josm.plugins.Plugin;
29import org.openstreetmap.josm.plugins.PluginInformation;
30import org.openstreetmap.josm.data.projection.*;
31
32/**
33 *
34 * Plugin to access the French Cadastre WMS server at www.cadastre.gouv.fr This
35 * WMS server requires some specific handling like retrieving a cookie for a
36 * limitation in case of no activity, or the request to the server shall provide
37 * a city/town/village code.
38 *
39 * @author Pieren <pieren3@gmail.com>,
40 * @author <matthieu.lochegnies@gmail.com> for the extension to codeCommune
41 * @version 0.8
42 * History:
43 * 0.1 17-Jun-2008 first prototype using a first Lambert projection impl. in core
44 * 0.2 22-Jun-2008 first stable version
45 * 0.3 24-Jun-2008 add code departement
46 * 0.4 06-Jul-2008 - add images scales, icons, menu items disabling
47 * - remove dependencies of wmsplugin
48 * - add option to force a Lambert zone (for median locations)
49 * - add auto-sourcing
50 * 0.5 16-Aug-2008 - add transparency in layer (allowing multiple wms layers displayed together)
51 * - no overlapping of grabbed images if transparency is enabled
52 * - set one layer per location
53 * - use utf-8 charset in POST request to server
54 * - improve the preferences setting dialog
55 * - cancel the current download is now possible
56 * - add automatic images caching and load on request (+ manage cache directory size)
57 * - enable auto-sourcing only if a WMS layer is used
58 * 0.6 18-Aug-2008 - suppress the null-exception message after the dialog 'open a layer first'
59 * - process the overlapping images when cache is loaded from disk
60 * - save the last 'new location request' text again in preferences
61 * - avoid duplicate layers with same name
62 * - set text input for new locations in upper case
63 * - the cache directory is configurable in "cadastrewms.cacheDir"
64 * - improve configuration change updates
65 * 0.7 24-Aug-2008 - mask images only if transparency enabled
66 * - validate projection name by Lambert.toString() method
67 * 0.8 25-Jan-2009 - display returned list of communes if direct name is not recognized by server
68 * - new possible grab factor of 100 square meters fixed size
69 * - minor fixes due to changes in JOSM core classes
70 * - first draft of raster image support
71 * 0.9 05-Feb-2009 - grab vectorized full commune bbox, save in file, convert to OSM way
72 * and simplify
73 * 1.0 18-Feb-2009 - fix various bugs in color management and preference dialog
74 * - increase PNG picture size requested to WMS (800x1000)
75 * - set 4th grab scale fixed size configurable (from 25 to 1000 meters)
76 * 1.1 11-Jun-2009 - fixed a null exception error when trying to displace a vectorized layer
77 * - propose to use shortcut F11 for grabbing
78 * 1.2 16-Aug-2009 - implementation of raster image grabbing, cropping and georeferencing (not the
79 * overview rasters (Tableau d'assemblage) but directly small units (Feuille)
80 * 1.3 23-Aug-2009 - improve georeferencing action cancellation
81 * - fixed bug of raster image loaded from cache not working on Java1.6
82 * - improve mouse click bounce detection during georeferencing process
83 * 1.4 25-Oct-2009 - add support for new Lambert CC 9 Zones projection
84 * - add optional crosspieces display on raster image layers
85 * - add automatic raster images georeferencing when WMS provides data
86 * - re-implement manual adjustment mode in raster image layer
87 * 1.5 21-Nov-2009 - major changes in projection in core : no magical zone prediction anymore for
88 * Lambert 4 and 9 zones; grid translation implemented for Lambert 4 zones;
89 * support of subprojections in preferences for zones setting and UTM20N
90 * - removed autosourcing of empty new nodes
91 * 1.6 28-Nov-2009 - Fix minor issues if Grab is called without layer (possible since projection rework)
92 * 1.7 12-Dec-2009 - Change URL's changes for cookie and downgrade imgs resolution due to WMS changes
93 * 1.8 11-Mar-2010 - filter the mouse button 1 during georeferencing
94 * - retry if getting a new cookie failed (10 times during 30 seconds)
95 * - cookie expiration automatically detected and renewed (after 30 minutes)
96 * - proper WMS layer cleanup at destruction (workaround for memory leak)
97 * - new cache format (v3) storing original image and cropped image bbox + angle
98 * - new cache format (v4) storing original image size for later rotation
99 * - cache files read compatible with previous formats
100 * - raster image rotation issues fixed, now using shift+ctrl key instead of ctrl
101 * - raster image adjustment using default system menu modifier (ctrl for windows) for Mac support
102 * - image resolution configurable (high, medium, low) like the online interface
103 * - layer selection configurable for vectorized images
104 * - improved download cancellation
105 * - from Erik Amzallag:
106 * - possibility to modify the auto-sourcing text just before upload
107 * - from Clément Ménier:
108 * - new option allowing an auto-selection of the first cadastre layer for grab
109 * - non-modal JDialog in MenuActionGrabPlanImage
110 * - new options in the image filter (bilinear, bicubic)
111 * 1.9 05-Apr-2010 - added a scroll bar in preferences
112 * - download cancellation improved
113 * - last deployment for Java1.5 compatibility
114 * 2.0 07-Jul-2010 - update projection for "La Reunion" departement to RGR92, UTM40S.
115 * - add 'departement' as option in the municipality selection
116 * - fixed bug in cache directory size control (and disabled by default)
117 * - add map mode for addressing
118 * - from Nicolas Dumoulin:
119 * - add "tableau d'assemblage" in raster images for georeferencing (as option)
120 * 2.1 14-Jan-2011 - add GrabThread moving the grab to a separate thread
121 * - the divided BBox mode starts from the central square and loads the next in a spiral
122 * - move the grabber from CadastrPlugin singleton to each wmsLayer instance to allow grabbing
123 * of multiple municipalities in parallel.
124 * 2.2 01-Jul-2011 - replace deprecated Main.proj by newest Main.getProjection()
125 * - fix list of raster images (Feuilles) parsing failing after a Cadastre server change/maintenance
126 */
127public class CadastrePlugin extends Plugin {
128 static String VERSION = "2.1";
129
130 static JMenu cadastreJMenu;
131
132 public static String source = "";
133
134 // true if the checkbox "auto-sourcing" is set in the plugin menu
135 public static boolean autoSourcing = false;
136
137 // true when the plugin is first used, e.g. grab from WMS or download cache file
138 public static boolean pluginUsed = false;
139
140 public static String cacheDir = null;
141
142 public static boolean alterColors = false;
143
144 public static boolean backgroundTransparent = false;
145
146 public static float transparency = 1.0f;
147
148 public static boolean drawBoundaries = false;
149
150 public static int imageWidth, imageHeight;
151
152 public static String grabLayers, grabStyles = null;
153
154 static private boolean menuEnabled = false;
155
156 private static String LAYER_BULDINGS = "CDIF:LS2";
157 private static String STYLE_BUILDING = "LS2_90";
158 private static String LAYER_WATER = "CDIF:LS3";
159 private static String STYLE_WATER = "LS3_90";
160 private static String LAYER_SYMBOL = "CDIF:LS1";
161 private static String STYLE_SYMBOL = "LS1_90";
162 private static String LAYER_PARCELS = "CDIF:PARCELLE";
163 private static String STYLE_PARCELS = "PARCELLE_90";
164 private static String LAYER_NUMERO = "CDIF:NUMERO";
165 private static String STYLE_NUMERO = "NUMERO_90";
166 private static String LAYER_LABEL = "CDIF:PT3,CDIF:PT2,CDIF:PT1";
167 private static String STYLE_LABEL = "PT3_90,PT2_90,PT1_90";
168 private static String LAYER_LIEUDIT = "CDIF:LIEUDIT";
169 private static String STYLE_LIEUDIT = "LIEUDIT_90";
170 private static String LAYER_SECTION = "CDIF:SUBSECTION,CDIF:SECTION";
171 private static String STYLE_SECTION = "SUBSECTION_90,SECTION_90";
172 private static String LAYER_COMMUNE = "CDIF:COMMUNE";
173 private static String STYLE_COMMUNE = "COMMUNE_90";
174
175 /**
176 * Creates the plugin and setup the default settings if necessary
177 *
178 * @throws Exception
179 */
180 public CadastrePlugin(PluginInformation info) throws Exception {
181 super(info);
182 System.out.println("Pluging cadastre-fr v"+VERSION+" started...");
183 if (Main.pref.get("cadastrewms.cacheDir").equals(""))
184 cacheDir = Main.pref.getPreferencesDir()+"plugins"+File.separatorChar+"cadastrewms"+File.separatorChar;
185 else {
186 cacheDir = Main.pref.get("cadastrewms.cacheDir");
187 if (cacheDir.charAt(cacheDir.length()-1) != File.separatorChar )
188 cacheDir += File.separatorChar;
189 }
190 System.out.println("current cache directory: "+cacheDir);
191
192 refreshConfiguration();
193
194 UploadAction.registerUploadHook(new CheckSourceUploadHook());
195
196 }
197
198 public static void refreshMenu() {
199 MainMenu menu = Main.main.menu;
200
201 if (cadastreJMenu == null) {
202 cadastreJMenu = menu.addMenu(marktr("Cadastre"), KeyEvent.VK_C, menu.defaultMenuPos, ht("/Plugin/CadastreFr"));
203 JosmAction grab = new MenuActionGrab();
204 JMenuItem menuGrab = new JMenuItem(grab);
205 KeyStroke ks = grab.getShortcut().getKeyStroke();
206 if (ks != null) {
207 menuGrab.setAccelerator(ks);
208 }
209 JMenuItem menuActionGrabPlanImage = new JMenuItem(new MenuActionGrabPlanImage());
210 JMenuItem menuSettings = new JMenuItem(new MenuActionNewLocation());
211 final JCheckBoxMenuItem menuSource = new JCheckBoxMenuItem(tr("Auto sourcing"));
212 menuSource.setSelected(autoSourcing);
213 menuSource.addActionListener(new ActionListener() {
214 public void actionPerformed(ActionEvent ev) {
215 Main.pref.put("cadastrewms.autosourcing", menuSource.isSelected());
216 autoSourcing = menuSource.isSelected();
217 }
218 });
219
220 //JMenuItem menuResetCookie = new JMenuItem(new MenuActionResetCookie());
221 //JMenuItem menuLambertZone = new JMenuItem(new MenuActionLambertZone());
222 JMenuItem menuLoadFromCache = new JMenuItem(new MenuActionLoadFromCache());
223 // temporary disabled:
224 //JMenuItem menuActionBoundaries = new JMenuItem(new MenuActionBoundaries());
225 //JMenuItem menuActionBuildings = new JMenuItem(new MenuActionBuildings());
226
227 cadastreJMenu.add(menuGrab);
228 cadastreJMenu.add(menuActionGrabPlanImage);
229 cadastreJMenu.add(menuSettings);
230 cadastreJMenu.add(menuSource);
231 //cadastreJMenu.add(menuResetCookie); not required any more
232 //cadastreJMenu.add(menuLambertZone);
233 //if (Main.pref.getBoolean("cadastrewms.buildingsMenu", false))
234 // cadastreJMenu.add(menuActionBuildings);
235 cadastreJMenu.add(menuLoadFromCache);
236 // all SVG features disabled until official WMS is released
237 //cadastreJMenu.add(menuActionBoundaries);
238 }
239 setEnabledAll(menuEnabled);
240 }
241
242 public static void refreshConfiguration() {
243 source = checkSourceMillesime();
244 autoSourcing = Main.pref.getBoolean("cadastrewms.autosourcing", true);
245 alterColors = Main.pref.getBoolean("cadastrewms.alterColors");
246 drawBoundaries = Main.pref.getBoolean("cadastrewms.drawBoundaries", false);
247 if (alterColors) {
248 backgroundTransparent = Main.pref.getBoolean("cadastrewms.backgroundTransparent");
249 transparency = Float.parseFloat(Main.pref.get("cadastrewms.brightness", "1.0f"));
250 } else {
251 backgroundTransparent = false;
252 transparency = 1.0f;
253 }
254 String currentResolution = Main.pref.get("cadastrewms.resolution", "high");
255 if (currentResolution.equals("high")) {
256 imageWidth = 1000; imageHeight = 800;
257 } else if (currentResolution.equals("medium")){
258 imageWidth = 800; imageHeight = 600;
259 } else {
260 imageWidth = 600; imageHeight = 400;
261 }
262 refreshLayersURL();
263
264 // overwrite F11 shortcut used from the beginning by this plugin and recently used
265 // for full-screen switch in JOSM core
266 int i = 0;
267 String p = Main.pref.get("shortcut.shortcut."+i, null);
268 boolean alreadyRedefined = false;
269 while (p != null) {
270 String[] s = p.split(";");
271 alreadyRedefined = alreadyRedefined || s[0].equals("menu:view:fullscreen");
272 i++;
273 p = Main.pref.get("shortcut.shortcut."+i, null);
274 }
275 if (!alreadyRedefined) {
276 int reply = JOptionPane.showConfirmDialog(null,
277 tr("Plugin cadastre-fr used traditionally the key shortcut F11 for grabbing,\n"+
278 "which is currently allocated for full-screen switch by default.\n"+
279 "Would you like to restore F11 for grab action?"),
280 tr("Restore grab shortcut F11"),
281 JOptionPane.YES_NO_OPTION);
282 if (reply == JOptionPane.OK_OPTION) {
283 System.out.println("redefine fullscreen shortcut F11 to shift+F11");
284 Main.pref.put("shortcut.shortcut."+i, "menu:view:fullscreen;Toggle Full Screen view;122;5;122;64;false;true");
285 JOptionPane.showMessageDialog(Main.parent,tr("JOSM is stopped for the change to take effect."));
286 System.exit(0);
287 }
288 } else
289 System.out.println("Shortcut F11 already redefined; do not change.");
290
291 refreshMenu();
292 }
293
294 private static void refreshLayersURL() {
295 grabLayers = "";
296 grabStyles = "";
297 int countLayers = 0;
298 if (Main.pref.getBoolean("cadastrewms.layerWater", true)) {
299 grabLayers += LAYER_WATER + ",";
300 grabStyles += STYLE_WATER + ",";
301 countLayers++;
302 }
303 if (Main.pref.getBoolean("cadastrewms.layerBuilding", true)) {
304 grabLayers += LAYER_BULDINGS + ",";
305 grabStyles += STYLE_BUILDING + ",";
306 countLayers++;
307 }
308 if (Main.pref.getBoolean("cadastrewms.layerSymbol", true)) {
309 grabLayers += LAYER_SYMBOL + ",";
310 grabStyles += STYLE_SYMBOL + ",";
311 countLayers++;
312 }
313 if (Main.pref.getBoolean("cadastrewms.layerParcel", true)) {
314 grabLayers += LAYER_PARCELS + ",";
315 grabStyles += STYLE_PARCELS + ",";
316 countLayers++;
317 }
318 if (Main.pref.getBoolean("cadastrewms.layerNumero", true)) {
319 grabLayers += LAYER_NUMERO + ",";
320 grabStyles += STYLE_NUMERO + ",";
321 countLayers++;
322 }
323 if (Main.pref.getBoolean("cadastrewms.layerLabel", true)) {
324 grabLayers += LAYER_LABEL + ",";
325 grabStyles += STYLE_LABEL + ",";
326 countLayers++;
327 }
328 if (Main.pref.getBoolean("cadastrewms.layerLieudit", true)) {
329 grabLayers += LAYER_LIEUDIT + ",";
330 grabStyles += STYLE_LIEUDIT + ",";
331 countLayers++;
332 }
333 if (Main.pref.getBoolean("cadastrewms.layerSection", true)) {
334 grabLayers += LAYER_SECTION + ",";
335 grabStyles += STYLE_SECTION + ",";
336 countLayers++;
337 }
338 if (Main.pref.getBoolean("cadastrewms.layerCommune", true)) {
339 grabLayers += LAYER_COMMUNE + ",";
340 grabStyles += STYLE_COMMUNE + ",";
341 countLayers++;
342 }
343 if (countLayers > 2) { // remove the last ','
344 grabLayers = grabLayers.substring(0, grabLayers.length()-1);
345 grabStyles = grabStyles.substring(0, grabStyles.length()-1);
346 } else {
347 JOptionPane.showMessageDialog(Main.parent,tr("Please enable at least two WMS layers in the cadastre-fr "
348 + "plugin configuration.\nLayers ''Building'' and ''Parcel'' added by default."));
349 Main.pref.put("cadastrewms.layerBuilding", true);
350 Main.pref.put("cadastrewms.layerParcel", true);
351 grabLayers += LAYER_BULDINGS + "," + LAYER_PARCELS;
352 grabStyles += STYLE_BUILDING + "," + STYLE_PARCELS;
353 }
354 }
355
356 @Override
357 public PreferenceSetting getPreferenceSetting() {
358 return new CadastrePreferenceSetting();
359 }
360
361 private static void setEnabledAll(boolean isEnabled) {
362 for (int i = 0; i < cadastreJMenu.getItemCount(); i++) {
363 JMenuItem item = cadastreJMenu.getItem(i);
364 if (item != null)
365 if (item.getText().equals(MenuActionGrabPlanImage.name) /*||
366 item.getText().equals(MenuActionGrab.name) ||
367 item.getText().equals(MenuActionBoundaries.name) ||
368 item.getText().equals(MenuActionBuildings.name)*/) {
369 item.setEnabled(isEnabled);
370 }
371 }
372 menuEnabled = isEnabled;
373 }
374
375 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
376 if (cadastreJMenu != null) {
377 if (oldFrame == null && newFrame != null) {
378 setEnabledAll(true);
379 Main.map.addMapMode(new IconToggleButton(new WMSAdjustAction(Main.map)));
380 Main.map.addMapMode(new IconToggleButton(new Address(Main.map)));
381 } else if (oldFrame != null && newFrame == null) {
382 setEnabledAll(false);
383 //Lambert.layoutZone = -1;
384 //LambertCC9Zones.layoutZone = -1;
385 }
386 }
387 }
388
389 public static boolean isCadastreProjection() {
390 return Main.getProjection().toString().equals(new Lambert().toString())
391 || Main.getProjection().toString().equals(new UTM_France_DOM().toString())
392 || Main.getProjection().toString().equals(new LambertCC9Zones().toString());
393 }
394
395 public static void safeSleep(long milliseconds) {
396 try {
397 Thread.sleep(milliseconds);
398 } catch (InterruptedException e) {}
399 }
400
401 // See OptionPaneUtil
402 // FIXME: this is a temporary solution.
403 public static void prepareDialog(JDialog dialog) {
404 if (Main.pref.getBoolean("window-handling.option-pane-always-on-top", true)) {
405 try {
406 dialog.setAlwaysOnTop(true);
407 } catch(SecurityException e) {
408 System.out.println(tr("Warning: failed to put option pane dialog always on top. Exception was: {0}", e.toString()));
409 }
410 }
411 dialog.setModal(true);
412 dialog.toFront();
413 dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
414 }
415
416 /**
417 * Adds the WMSLayer following this rule:<br/>
418 * - if a WMSLayer exists place this new layer just before this layer<br/>
419 * - Otherwise place it at the bottom
420 * @param wmsLayer the wmsLayer to add
421 */
422 public static void addWMSLayer(WMSLayer wmsLayer) {
423 if (Main.map != null && Main.map.mapView != null) {
424 int wmsNewLayerPos = Main.map.mapView.getAllLayers().size();
425 for(Layer l : Main.map.mapView.getLayersOfType(WMSLayer.class)) {
426 int wmsPos = Main.map.mapView.getLayerPos(l);
427 if (wmsPos < wmsNewLayerPos) wmsNewLayerPos = wmsPos;
428 }
429 Main.main.addLayer(wmsLayer);
430 // Move the layer to its new position
431 Main.map.mapView.moveLayer(wmsLayer, wmsNewLayerPos);
432 } else
433 Main.main.addLayer(wmsLayer);
434 }
435
436 private static String checkSourceMillesime() {
437 java.util.Calendar calendar = java.util.Calendar.getInstance();
438 int currentYear = calendar.get(java.util.Calendar.YEAR);
439 String src = Main.pref.get("cadastrewms.source",
440 "cadastre-dgi-fr source : Direction G\u00e9n\u00e9rale des Imp\u00f4ts - Cadastre. Mise \u00e0 jour : AAAA");
441 String srcYear = src.substring(src.lastIndexOf(" ")+1);
442 Integer year = null;
443 try {
444 year = Integer.decode(srcYear);
445 } catch (NumberFormatException e) {}
446 if (srcYear.equals("AAAA") || (year != null && year < currentYear)) {
447 System.out.println("Replace source year "+srcYear+" by current year "+currentYear);
448 src = src.substring(0, src.lastIndexOf(" ")+1)+currentYear;
449 Main.pref.put("cadastrewms.source", src);
450 }
451 return src;
452 }
453
454}
Note: See TracBrowser for help on using the repository browser.