Statistics
| Revision:

gvsig-osm / org.gvsig.raster.osm / trunk / org.gvsig.raster.osm / org.gvsig.raster.osm.app.osmclient / src / main / java / org / gvsig / raster / osm / app / osmclient / AddOSMLayerWizard.java @ 309

History | View | Annotate | Download (11.8 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.raster.osm.app.osmclient;
23

    
24
import java.awt.Component;
25
import java.awt.GridBagConstraints;
26
import java.awt.GridBagLayout;
27
import java.awt.Insets;
28
import java.awt.event.MouseEvent;
29
import java.awt.event.MouseListener;
30
import java.beans.PropertyVetoException;
31
import java.io.File;
32
import java.io.FileNotFoundException;
33
import java.io.IOException;
34
import java.net.MalformedURLException;
35
import java.net.URISyntaxException;
36
import java.net.URL;
37

    
38
import javax.swing.JOptionPane;
39
import javax.swing.JPanel;
40

    
41
import org.cresques.cts.IProjection;
42

    
43
import org.gvsig.andami.Launcher;
44
import org.gvsig.andami.PluginServices;
45
import org.gvsig.andami.PluginsLocator;
46
import org.gvsig.andami.ui.mdiManager.IWindow;
47
import org.gvsig.app.ApplicationLocator;
48
import org.gvsig.app.ApplicationManager;
49
import org.gvsig.app.gui.WizardPanel;
50
import org.gvsig.app.gui.wizards.WizardListener;
51
import org.gvsig.app.gui.wizards.WizardListenerSupport;
52
import org.gvsig.app.project.ProjectManager;
53
import org.gvsig.app.project.documents.view.ViewDocument;
54
import org.gvsig.app.project.documents.view.ViewManager;
55
import org.gvsig.app.project.documents.view.gui.AbstractViewPanel;
56
import org.gvsig.app.project.documents.view.gui.IView;
57
import org.gvsig.fmap.crs.CRSFactory;
58
import org.gvsig.fmap.dal.DALLocator;
59
import org.gvsig.fmap.dal.DataParameters;
60
import org.gvsig.fmap.dal.DataStoreParameters;
61
import org.gvsig.fmap.dal.coverage.RasterLocator;
62
import org.gvsig.fmap.dal.coverage.store.parameter.TileDataParameters;
63
import org.gvsig.fmap.dal.coverage.util.FileUtils;
64
import org.gvsig.fmap.dal.exception.InitializeException;
65
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
66
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
67
import org.gvsig.fmap.mapcontext.MapContext;
68
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
69
import org.gvsig.raster.osm.app.osmclient.layer.FLyrOSM;
70
import org.gvsig.raster.osm.io.OSMDataParameters;
71
import org.gvsig.raster.osm.io.OSMProvider;
72
import org.gvsig.raster.osm.swing.AddOSMLayerPanel;
73
import org.gvsig.raster.osm.swing.OSMSwingLocator;
74

    
75
import org.slf4j.Logger;
76
import org.slf4j.LoggerFactory;
77

    
78
/**
79
 * Wizard panel to add a new OSM raster layer
80
 * @author Nacho Brodin (nachobrodin@gmail.com)
81
 */
82
public class AddOSMLayerWizard extends WizardPanel implements MouseListener {
83
        private static final long           serialVersionUID      = 1L;
84
        private static final String         TAB_NAME              = "OSM";
85
        private static Logger               logger                = LoggerFactory.getLogger(AddOSMLayerWizard.class.getName());
86
        private AddOSMLayerPanel            apiUI                 = null;
87
        private WizardListenerSupport       listenerSupport       = null;
88

    
89
        public AddOSMLayerWizard() {
90
                super();
91
        }
92

    
93
        /**
94
         * This method initializes this
95
         *
96
         * @return void
97
         */
98
        private void initialize() {
99
                setTabName(PluginServices.getText(this, TAB_NAME));
100
                setLayout(new GridBagLayout());
101
                GridBagConstraints gridBagConstraints = new GridBagConstraints();
102
                gridBagConstraints.fill = GridBagConstraints.BOTH;
103
                gridBagConstraints.weightx = 1.0;
104
                gridBagConstraints.weighty = 1.0;
105
                gridBagConstraints.insets = new Insets(6, 6, 6, 6);
106

    
107
                boolean showCrsWarning = false;
108
                IProjection osmProjection = CRSFactory.getCRS("EPSG:3857");
109
        if(getMapCtrl()!=null && !(getMapCtrl().getProjection().equals(osmProjection))){
110
            showCrsWarning = true;
111
        }
112
                apiUI = OSMSwingLocator.getSwingManager().createAddOSMLayerPanel(new File(Launcher.getAppHomeDir()),showCrsWarning);
113

    
114
                //Copying osmservers.properties
115
                if(!new File(apiUI.getPropertiesFilePath()).exists()) {
116
                        File pluginFolder = PluginsLocator.getManager().getPluginsFolder();
117
                        File f = new File(pluginFolder.getAbsolutePath() +
118
                                                        File.separator +
119
                                                        "org.gvsig.raster.osm.app.osmclient" +
120
                                                        File.separator +
121
                                                        apiUI.getPropertiesFileName());
122
                        FileUtils utils = RasterLocator.getManager().getFileUtils();
123
                        try {
124
                                utils.copyFile(f.getAbsolutePath(), Launcher.getAppHomeDir() + File.separator);
125
                                apiUI = OSMSwingLocator.getSwingManager().createAddOSMLayerPanel(new File(Launcher.getAppHomeDir()),showCrsWarning);
126
                        } catch (FileNotFoundException e) {
127
                                logger.info("File not found copying osmservers.properties", e);
128
                        } catch (IOException e) {
129
                                logger.info("Error copying osmservers.properties", e);
130
                        }
131
                }
132

    
133
                apiUI.addMouseListener(this);
134

    
135
                JPanel mainPanel = (JPanel)apiUI.getComponent();
136
                add(mainPanel, gridBagConstraints);
137
        }
138

    
139
        private WizardListenerSupport getWizardListenerSupport() {
140
                if(listenerSupport == null)
141
                        listenerSupport = new WizardListenerSupport();
142
                return listenerSupport;
143
        }
144

    
145
        /**
146
         * This method checks for the options selected within the configuration
147
         * dialog are correct.
148
         *
149
         * @return true if you're done, false if not.
150
         */
151
        public boolean areSettingsValid() {
152
                return apiUI.areSettingsValid();
153
        }
154

    
155
        public void addWizardListener(WizardListener listener) {
156
                getWizardListenerSupport().addWizardListener(listener);
157
                getWizardListenerSupport().callStateChanged(false);
158
        }
159

    
160
        public void removeWizardListener(WizardListener listener) {
161
                getWizardListenerSupport().removeWizardListener(listener);
162
        }
163

    
164
        @Override
165
        public void close() {
166

    
167
        }
168

    
169
        @Override
170
        public void execute() {
171
                if(!apiUI.areSettingsValid()) {
172
                        messageBoxInfo("server_not_selected", PluginServices.getMDIManager().getActiveWindow(), null);
173
                        return;
174
                }
175

    
176
                try {
177
                        TileDataParameters tileParams = createDataParameters();
178

    
179
                        //Getting the MapContext
180
                        MapContext mapContext = getMapContext();
181

    
182
                        if(mapContext == null) {
183
                                mapContext = createViewWindow();
184
                        }
185

    
186
                        //Adding the layer
187
                        FLyrOSM layer = buildLayer(tileParams);
188
                        addLayerToMapContext(mapContext, layer);
189
                } catch (InitializeException e) {
190
                        messageBoxInfo("error_creating_parameters", PluginServices.getMDIManager().getActiveWindow(), e);
191
                } catch (ProviderNotRegisteredException e) {
192
                        messageBoxInfo("error_creating_parameters", PluginServices.getMDIManager().getActiveWindow(), e);
193
                } catch (LoadLayerException e) {
194
                        messageBoxInfo("error_creating_the_view", PluginServices.getMDIManager().getActiveWindow(), e);
195
                }
196
        }
197

    
198
        /**
199
         * Create the parameters to the provider
200
         * @return
201
         * @throws InitializeException
202
         * @throws ProviderNotRegisteredException
203
         */
204
        private TileDataParameters createDataParameters() throws InitializeException, ProviderNotRegisteredException {
205
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
206
                OSMDataParameters parameters = (OSMDataParameters)dataman.createStoreParameters(OSMProvider.NAME);
207
                URL selectedURL = null;
208
                try {
209
                    selectedURL = apiUI.getSelectedURL();
210
                } catch (MalformedURLException e) {
211
                    throw new InitializeException(e);
212
                }
213
                try {
214
                    parameters.setURI(selectedURL.toURI());
215
        } catch (URISyntaxException e1) {
216
            logger.warn("Can't convert URI from "+selectedURL.toString(), e1);
217
            throw new InitializeException(e1);
218
        }
219
                parameters.setTileSuffix(apiUI.getSelectedFormat());
220
                parameters.setOSMLayerName(apiUI.getSelectedName());
221
                try {
222
                        parameters.setNumberOfLevels(new Integer(apiUI.getSelectedLevel()));
223
                } catch (NumberFormatException e) {
224

    
225
                }
226

    
227
                TileDataParameters tileParams = (TileDataParameters) dataman.createStoreParameters("Tile Store");
228
                tileParams.setDataParameters((DataParameters)parameters);
229
                return tileParams;
230
        }
231

    
232
        /**
233
         * Adds the layer to the MapContext selected
234
         * @param mapContext
235
         * @param layer
236
         */
237
        private void addLayerToMapContext(MapContext mapContext, FLyrOSM layer) {
238
                mapContext.beginAtomicEvent();
239
                layer.setVisible(true);
240
                mapContext.getLayers().addLayer(layer);
241
                mapContext.callLegendChanged();
242
                mapContext.endAtomicEvent();
243
        }
244

    
245
        /**
246
         * Builds the OSM layer
247
         * @param tileParams
248
         * @return
249
         */
250
        private FLyrOSM buildLayer(TileDataParameters tileParams) {
251
                FLyrOSM layer = new FLyrOSM();
252
                layer.deleteCache(false);  //Esto es parametrizable
253
                try {
254
                        layer.setParameters(tileParams);
255
                        layer.setName(apiUI.getSelectedName());
256
                } catch (InitializeException e) {
257
                        messageBoxInfo("error_initializing_layer", PluginServices.getMDIManager().getActiveWindow(), e);
258
                }
259
                return layer;
260
        }
261

    
262
        /**
263
         * Gets the active view or the first view opened if there is not
264
         * any with the focus
265
         * @return
266
         */
267
        public MapContext getMapContext() {
268
                IWindow window = PluginServices.getMDIManager().getFocusWindow();
269
                if(window instanceof AbstractViewPanel) {
270
                        return ((AbstractViewPanel)window).getMapControl().getMapContext();
271
                }
272

    
273
                IWindow[] w = PluginServices.getMDIManager().getAllWindows();
274
                for (int i = 0; i < w.length; i++) {
275
                        if (w[i] instanceof org.gvsig.app.project.documents.view.gui.AbstractViewPanel) {
276
                                return ((AbstractViewPanel)w[i]).getMapControl().getMapContext();
277
                        }
278
                }
279
                return null;
280
        }
281

    
282
        private void messageBoxInfo(String msg, Object parentWindow, Exception exception) {
283
                LoggerFactory.getLogger(getClass()).debug(msg, exception);
284
                String string = PluginServices.getText(parentWindow, "accept");
285
                Object[] options = {string};
286
                JOptionPane.showOptionDialog((Component)/*PluginServices.getMainFrame()*/parentWindow,
287
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
288
                                        PluginServices.getText(parentWindow, "confirmacion"),
289
                                        JOptionPane.OK_OPTION,
290
                                        JOptionPane.INFORMATION_MESSAGE,
291
                                        null,
292
                                        options,
293
                                        string);
294
        }
295

    
296
        /**
297
     * Create the view in the project. Add the blocks layer
298
     * to the view, and register the tool for get info of the
299
     * blocks.
300
     */
301
    @SuppressWarnings("deprecation")
302
        private MapContext createViewWindow() throws LoadLayerException {
303
            ApplicationManager application = ApplicationLocator.getManager();
304

    
305
            ProjectManager projectManager = application.getProjectManager();
306

    
307
            // 1. Create a new view and set the name.
308
            ViewManager viewManager = (ViewManager) projectManager.getDocumentManagers(ViewManager.TYPENAME);
309
            ViewDocument view = (ViewDocument) viewManager.createDocument();
310
            view.setName("OpenStreetMap View");
311

    
312
            // 4. Add the view to the current project.
313
            projectManager.getCurrentProject().add(view);
314

    
315
            // 5. Force to show the view's window.
316
            IView viewWindow = (IView) viewManager.getMainWindow(view);
317

    
318
            application.getUIManager().addWindow(viewWindow, GridBagConstraints.CENTER);
319
            try {
320
                        application.getUIManager().setMaximum((IWindow) viewWindow, true);
321
                } catch (PropertyVetoException e) {
322
                }
323

    
324
                if(viewWindow != null) {
325
                        IProjection proj = CRSFactory.getCRS("EPSG:3857");
326
                        if(proj != null)
327
                                viewWindow.getMapControl().setProjection(proj);
328
                        return viewWindow.getMapControl().getMapContext();
329
                }
330
                return null;
331
    }
332

    
333
        @Override
334
        public DataStoreParameters[] getParameters() {
335
                return null;
336
        }
337

    
338
        @Override
339
        public void initWizard() {
340
            initialize();
341
        }
342

    
343
        public void mouseClicked(MouseEvent e) {
344

    
345
        }
346

    
347
        public void mouseEntered(MouseEvent e) {
348

    
349
        }
350

    
351
        public void mouseExited(MouseEvent e) {
352

    
353
        }
354

    
355
        public void mousePressed(MouseEvent e) {
356
                getWizardListenerSupport().callStateChanged(true);
357
        }
358

    
359
        public void mouseReleased(MouseEvent e) {
360

    
361
        }
362
}