Statistics
| Revision:

gvsig-geoprocess / org.gvsig.geoprocess / trunk / org.gvsig.geoprocess / org.gvsig.geoprocess.lib / org.gvsig.geoprocess.lib.sextante / src / main / java / org / gvsig / geoprocess / lib / sextante / SextanteGeoProcessManager.java @ 723

History | View | Annotate | Download (20.1 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.lib.sextante;
25

    
26
import java.io.File;
27
import java.io.InputStream;
28
import java.net.URL;
29
import java.util.ArrayList;
30
import java.util.HashMap;
31
import java.util.Iterator;
32
import java.util.List;
33
import java.util.Locale;
34
import java.util.Map;
35
import java.util.Set;
36
import java.util.Map.Entry;
37

    
38
import javax.swing.ImageIcon;
39

    
40
import org.gvsig.andami.IconThemeHelper;
41
import org.gvsig.geoprocess.lib.api.GeoProcess;
42
import org.gvsig.geoprocess.lib.api.GeoProcessManager;
43
import org.gvsig.geoprocess.lib.sextante.gui.settings.GeoprocessSetting;
44
import org.gvsig.i18n.Messages;
45
import org.gvsig.tools.ToolsLocator;
46
import org.gvsig.tools.i18n.I18nManager;
47
import org.kxml2.io.KXmlParser;
48
import org.xmlpull.v1.XmlPullParser;
49

    
50
import es.unex.sextante.additionalInfo.AdditionalInfoVectorLayer;
51
import es.unex.sextante.core.GeoAlgorithm;
52
import es.unex.sextante.core.OutputObjectsSet;
53
import es.unex.sextante.core.ParametersSet;
54
import es.unex.sextante.core.Sextante;
55
import es.unex.sextante.docEngines.html.HTMLDoc;
56
import es.unex.sextante.exceptions.NullParameterAdditionalInfoException;
57
import es.unex.sextante.gui.algorithm.DefaultParametersPanel;
58
import es.unex.sextante.gui.algorithm.GeoAlgorithmParametersPanel;
59
import es.unex.sextante.gui.core.IAlgorithmProvider;
60
import es.unex.sextante.gui.core.IToolboxRightButtonAction;
61
import es.unex.sextante.gui.core.NameAndIcon;
62
import es.unex.sextante.gui.core.ToolboxAction;
63
import es.unex.sextante.gui.help.HelpElement;
64
import es.unex.sextante.gui.help.ImageAndDescription;
65
import es.unex.sextante.gui.modeler.DefaultModelerParametersPanel;
66
import es.unex.sextante.gui.settings.Setting;
67
import es.unex.sextante.outputs.Output;
68
import es.unex.sextante.outputs.Output3DRasterLayer;
69
import es.unex.sextante.outputs.OutputChart;
70
import es.unex.sextante.outputs.OutputNumericalValue;
71
import es.unex.sextante.outputs.OutputRasterLayer;
72
import es.unex.sextante.outputs.OutputTable;
73
import es.unex.sextante.outputs.OutputText;
74
import es.unex.sextante.outputs.OutputVectorLayer;
75
import es.unex.sextante.parameters.Parameter;
76
import es.unex.sextante.parameters.ParameterVectorLayer;
77

    
78
/**
79
 * Implementation for the {@link GeoProcessManager} interface based on the
80
 * sextante library.
81
 *
82
 * @author gvSIG Team
83
 * @version $Id$
84
 */
85
public class SextanteGeoProcessManager implements GeoProcessManager,
86
    IAlgorithmProvider {
87

    
88
    private static final String XML_PARSER_ENCODING = "ISO-8859-1";
89
    private static String HELP = "help";
90
    private Map<String, GeoAlgorithm> geoprocesses;
91
    private I18nManager i18nManager;
92

    
93
    /**
94
     * Manager constructor.
95
     */
96
    public SextanteGeoProcessManager() {
97
        i18nManager = ToolsLocator.getI18nManager();
98
        geoprocesses = new HashMap<String, GeoAlgorithm>();
99
    }
100

    
101
    public String getTranslation(String label) {
102
        // Just in case an algorithm is using a sextante label
103
        String text = i18nManager.getTranslation(label);
104
        return text == null ? Sextante.getText(label) : text;
105
    }
106

    
107
    public void registerGeoProcess(GeoProcess geoProcess) {
108
        if (geoProcess instanceof GeoAlgorithm) {
109
            GeoAlgorithm geoAlgorithm = (GeoAlgorithm) geoProcess;
110
            geoprocesses.put(geoAlgorithm.getCommandLineName(), geoAlgorithm);
111
        } else {
112
            throw new IllegalArgumentException("The geoprocess " + geoProcess
113
                + " is not an implementation of a sextante GeoAlgorithm, "
114
                + "so it is not supported as of now");
115
        }
116
    }
117

    
118
    public void registerGeoProcess(Class<? extends GeoProcess> geoProcessClazz,
119
        Map<String, String> localeStrings) {
120
        try {
121
            GeoProcess geoAlgorithm = geoProcessClazz.newInstance();
122
            registerGeoProcess(geoAlgorithm);
123
        } catch (InstantiationException e) {
124
            throw new RuntimeException(
125
                "Error creating a geoprocess instance from the class "
126
                    + geoProcessClazz, e);
127
        } catch (IllegalAccessException e) {
128
            throw new RuntimeException(
129
                "Error creating a geoprocess instance from the class "
130
                    + geoProcessClazz, e);
131
        }
132
    }
133

    
134
    public void initialize() {
135
        // Nothing to do
136
    }
137

    
138
    public String getName() {
139
        return Messages.getText("gv_algorithms");
140
    }
141

    
142
    public HashMap<String, GeoAlgorithm> getAlgorithms() {
143
        return new HashMap<String, GeoAlgorithm>(geoprocesses);
144
    }
145

    
146
    public HashMap<String, Class> getCustomModelerParameterPanels() {
147
        final HashMap<String, Class> map = new HashMap<String, Class>();
148
        final Set<String> set = getAlgorithms().keySet();
149
        final Iterator<String> iter = set.iterator();
150
        while (iter.hasNext()) {
151
            map.put(iter.next(), DefaultModelerParametersPanel.class);
152
        }
153

    
154
        return map;
155
    }
156

    
157
    public HashMap<String, Class> getCustomParameterPanels() {
158
        final HashMap<String, Class> map = new HashMap<String, Class>();
159
        final Set<Entry<String, GeoAlgorithm>> set = getAlgorithms().entrySet();
160
        final Iterator<Entry<String, GeoAlgorithm>> iter = set.iterator();
161
        while (iter.hasNext()) {
162
            Entry<String, GeoAlgorithm> entry = iter.next();
163
            GeoAlgorithm algorithm = entry.getValue();
164
            Class<? extends GeoAlgorithmParametersPanel> panelClazz = null;
165
            if (algorithm instanceof AbstractSextanteGeoProcess) {
166
                panelClazz =
167
                    ((AbstractSextanteGeoProcess) algorithm)
168
                        .getCustomParametersPanelClass();
169
            }
170
            map.put(entry.getKey(), (panelClazz == null
171
                ? DefaultParametersPanel.class : panelClazz));
172
        }
173

    
174
        return map;
175
    }
176

    
177
    public ImageIcon getIcon() {
178
        return IconThemeHelper.getImageIcon("gvsig-icon16x16");
179
    }
180

    
181
    public Setting getSettings() {
182
        return new GeoprocessSetting();
183
    }
184

    
185
    public void update() {
186
        // Nothing to do
187
    }
188

    
189
    public Object getAlgorithmHelp(GeoAlgorithm alg) {
190
        String algName = alg.getClass().getSimpleName();
191
        String helpFileName =
192
            algName + "_" + Locale.getDefault().getLanguage() + ".xml";
193
        String currentLocaleHelp = "help" + "/" + helpFileName;
194
        InputStream is =
195
            alg.getClass().getClassLoader()
196
                .getResourceAsStream(currentLocaleHelp);
197
        if (is == null) {
198
            helpFileName = algName + ".xml";
199
            currentLocaleHelp = "help" + "/" + helpFileName;
200
            is =
201
                alg.getClass().getClassLoader()
202
                    .getResourceAsStream(currentLocaleHelp);
203
        }
204

    
205
        if (is == null) {
206
            return null;
207
        }
208

    
209
        // The following code has been extracted from the
210
        // es.unex.sextante.gui.help.HelpIO getHelpAsHTMLCode method, as it
211
        // works with a string file path, and we need a stream from a classpath
212
        // resource.
213

    
214
        URL helpURL =
215
            alg.getClass().getClassLoader().getResource(currentLocaleHelp);
216
        String helpBaseURL = helpURL.toString();
217
        int lastIndex = helpBaseURL.length() - helpFileName.length();
218
        helpBaseURL = helpBaseURL.substring(0, lastIndex);
219
        HelpElement element;
220
        Map<String, HelpElement> elements = readHelpElements(is);
221

    
222
        HTMLDoc doc = new HTMLDoc();
223

    
224
        doc.open(alg.getName());
225
        doc.addHeader(Sextante.getText(alg.getName()), 1);
226
        doc.addHeader(Sextante.getText("Description"), 2);
227

    
228
        element = (HelpElement) elements.get("DESCRIPTION");
229
        if (element != null) {
230
            doc.addParagraph(element.getTextAsFormattedHTML());
231
            for (int j = 0; j < element.getImages().size(); j++) {
232
                ImageAndDescription iad =
233
                    (ImageAndDescription) element.getImages().get(j);
234
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
235
                    iad.getDescription());
236
            }
237
        }
238

    
239
        doc.addHeader(Sextante.getText("Parameters"), 2);
240

    
241
        ParametersSet params = alg.getParameters();
242

    
243
        doc.startUnorderedList();
244
        for (int i = 0; i < params.getNumberOfParameters(); i++) {
245
            Parameter param = params.getParameter(i);
246
            String sParam = param.getParameterDescription();
247
            sParam =
248
                "<b>" + sParam + "[" + getParameterTypeName(param) + "]: </b>";
249
            element = (HelpElement) elements.get(param.getParameterName());
250
            if (element != null) {
251
                sParam = sParam + element.getTextAsFormattedHTML();
252
            }
253
            doc.addListElement(sParam);
254
            if (element != null) {
255
                for (int j = 0; j < element.getImages().size(); j++) {
256
                    final ImageAndDescription iad =
257
                        (ImageAndDescription) element.getImages().get(j);
258
                    doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
259
                        iad.getDescription());
260
                }
261
            }
262

    
263
        }
264

    
265
        doc.closeUnorderedList();
266

    
267
        doc.addHeader(Sextante.getText("Outputs"), 2);
268

    
269
        element = (HelpElement) elements.get("OUTPUT_DESCRIPTION");
270
        if (element != null) {
271
            doc.addParagraph(element.getTextAsFormattedHTML());
272
            for (int j = 0; j < element.getImages().size(); j++) {
273
                final ImageAndDescription iad =
274
                    (ImageAndDescription) element.getImages().get(j);
275
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
276
                    iad.getDescription());
277
            }
278
        }
279

    
280
        doc.startUnorderedList();
281
        final OutputObjectsSet oo = alg.getOutputObjects();
282
        String sOutputType = "";
283
        for (int i = 0; i < oo.getOutputObjectsCount(); i++) {
284
            final Output out = oo.getOutput(i);
285
            String sOutput = out.getDescription();
286
            if (out instanceof OutputRasterLayer) {
287
                sOutputType = Sextante.getText("Raster_Layer");
288
            } else if (out instanceof Output3DRasterLayer) {
289
                sOutputType = Sextante.getText("3D_Raster_layer");
290
            } else if (out instanceof OutputVectorLayer) {
291
                sOutputType = Sextante.getText("Vector_Layer");
292
                final OutputVectorLayer ovl = (OutputVectorLayer) out;
293
                switch (ovl.getShapeType()) {
294
                case OutputVectorLayer.SHAPE_TYPE_UNDEFINED:
295
                default:
296
                    sOutputType =
297
                        sOutputType + " - " + Sextante.getText("Any_type");
298
                    break;
299
                case OutputVectorLayer.SHAPE_TYPE_LINE:
300
                    sOutputType =
301
                        sOutputType + " - " + Sextante.getText("Line");
302
                    break;
303
                case OutputVectorLayer.SHAPE_TYPE_POLYGON:
304
                    sOutputType =
305
                        sOutputType + " - " + Sextante.getText("Polygon");
306
                    break;
307
                case OutputVectorLayer.SHAPE_TYPE_POINT:
308
                    sOutputType =
309
                        sOutputType + " - " + Sextante.getText("Point");
310
                    break;
311
                }
312
            } else if (out instanceof OutputTable) {
313
                sOutputType = Sextante.getText("Table");
314
            } else if (out instanceof OutputChart) {
315
                sOutputType = Sextante.getText("graph-chart");
316
            } else if (out instanceof OutputText) {
317
                sOutputType = Sextante.getText("Text");
318
            } else if (out instanceof OutputNumericalValue) {
319
                sOutputType = Sextante.getText("Numerical_value");
320
            }
321
            sOutput = "<b>" + sOutput + "[" + sOutputType + "]: </b>";
322
            element = (HelpElement) elements.get(out.getName());
323
            if (element != null) {
324
                sOutput = sOutput + element.getTextAsFormattedHTML();
325
            }
326
            doc.addListElement(sOutput);
327
            if (element != null) {
328
                for (int j = 0; j < element.getImages().size(); j++) {
329
                    ImageAndDescription iad =
330
                        (ImageAndDescription) element.getImages().get(j);
331
                    doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
332
                        iad.getDescription());
333
                }
334
            }
335

    
336
        }
337
        doc.closeUnorderedList();
338

    
339
        doc.addHeader(Sextante.getText("Additional_information"), 2);
340

    
341
        element = (HelpElement) elements.get("ADDITIONAL_INFO");
342
        if (element != null) {
343
            doc.addParagraph(element.getTextAsFormattedHTML());
344
            for (int j = 0; j < element.getImages().size(); j++) {
345
                ImageAndDescription iad =
346
                    (ImageAndDescription) element.getImages().get(j);
347
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
348
                    iad.getDescription());
349
            }
350
        }
351

    
352
        doc.addHeader(Sextante.getText("Command_line"), 2);
353

    
354
        String sText = alg.getCommandLineHelp();
355
        sText = sText.replaceAll("\n", "<br>");
356
        sText = sText.replace("   ", " &nbsp ");
357
        doc.addCourierText(sText);
358

    
359
        doc.addParagraph("");
360

    
361
        element = (HelpElement) elements.get("EXTENSION_AUTHOR");
362
        if (element != null) {
363
            doc.addParagraph("<i>" + Sextante.getText("Algorithm_created_by")
364
                + " " + element.getText() + "</i>");
365
            for (int j = 0; j < element.getImages().size(); j++) {
366
                ImageAndDescription iad =
367
                    (ImageAndDescription) element.getImages().get(j);
368
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
369
                    iad.getDescription());
370
            }
371
        }
372

    
373
        element = (HelpElement) elements.get("HELP_AUTHOR");
374
        if (element != null) {
375
            doc.addParagraph("<i>" + Sextante.getText("Help_file_created_by")
376
                + " " + element.getText() + "</i>");
377
            for (int j = 0; j < element.getImages().size(); j++) {
378
                ImageAndDescription iad =
379
                    (ImageAndDescription) element.getImages().get(j);
380
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
381
                    iad.getDescription());
382
            }
383
        }
384

    
385
        doc.close();
386

    
387
        return doc.getHTMLCode();
388
    }
389

    
390
    public String getAlgorithmHelpFilename(GeoAlgorithm alg,
391
        boolean bForceCurrentLocale) {
392
        // TODO Auto-generated method stub
393
        return null;
394
    }
395

    
396
    public boolean canEditHelp() {
397
        return false;
398
    }
399

    
400
    private Map<String, HelpElement> readHelpElements(InputStream is) {
401
        List<ImageAndDescription> images = null;
402
        Map<String, HelpElement> elements = new HashMap<String, HelpElement>();
403
        HelpElement element = null;
404
        KXmlParser parser = new KXmlParser();
405
        try {
406
            parser.setInput(is, XML_PARSER_ENCODING);
407
            int tag = parser.nextTag();
408
            boolean bOut = false;
409
            String name;
410

    
411
            if (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
412
                while ((tag != XmlPullParser.END_DOCUMENT) && !bOut) {
413
                    switch (tag) {
414
                    case XmlPullParser.START_TAG:
415
                        name = parser.getName();
416
                        if (HELP.equals(name)) {
417
                        } else if (HelpElement.ELEMENT.equals(name)) {
418
                            images = new ArrayList<ImageAndDescription>();
419
                            String sText =
420
                                parser.getAttributeValue("", HelpElement.TEXT);
421
                            String sName =
422
                                parser.getAttributeValue("", HelpElement.NAME);
423
                            String sDescription =
424
                                parser.getAttributeValue("",
425
                                    HelpElement.DESCRIPTION);
426
                            int iType =
427
                                Integer.parseInt(parser.getAttributeValue("",
428
                                    HelpElement.TYPE));
429
                            element = new HelpElement();
430
                            element.setText(sText);
431
                            element.setName(sName);
432
                            element.setType(iType);
433
                            element.setDescription(sDescription);
434
                        } else if (ImageAndDescription.IMAGE.equals(name)) {
435
                            final ImageAndDescription iad =
436
                                new ImageAndDescription();
437
                            final String sImageFilename =
438
                                parser.getAttributeValue("",
439
                                    ImageAndDescription.FILE);
440
                            final String sDesc =
441
                                parser.getAttributeValue("",
442
                                    ImageAndDescription.DESCRIPTION);
443
                            iad.setDescription(sDesc);
444
                            iad.setFilename(sImageFilename);
445
                            images.add(iad);
446
                        }
447
                        break;
448
                    case XmlPullParser.END_TAG:
449
                        name = parser.getName();
450
                        if (HELP.equals(name)) {
451
                            bOut = true;
452
                        } else if (HelpElement.ELEMENT.equals(name)) {
453
                            element.setImages((ArrayList) images);
454
                            elements.put(element.getName(), element);
455
                        }
456
                        break;
457
                    case XmlPullParser.TEXT:
458
                        break;
459
                    }
460
                    if (!bOut) {
461
                        tag = parser.next();
462
                    }
463
                }
464
            }
465

    
466
        } catch (final Exception e) {
467
            return null;
468
        }
469
        return elements;
470
    }
471

    
472
    private String getParameterTypeName(Parameter param) {
473

    
474
        String s =
475
            Sextante.getText(param.getParameterTypeName().replace(' ', '_'));
476

    
477
        if (param instanceof ParameterVectorLayer) {
478
            try {
479
                final AdditionalInfoVectorLayer ai =
480
                    (AdditionalInfoVectorLayer) param
481
                        .getParameterAdditionalInfo();
482
                switch (ai.getShapeType()) {
483
                case AdditionalInfoVectorLayer.SHAPE_TYPE_ANY:
484
                default:
485
                    s = s + " - " + Sextante.getText("Any_type");
486
                    break;
487
                case AdditionalInfoVectorLayer.SHAPE_TYPE_LINE:
488
                    s = s + " - " + Sextante.getText("Line");
489
                    break;
490
                case AdditionalInfoVectorLayer.SHAPE_TYPE_POLYGON:
491
                    s = s + " - " + Sextante.getText("Polygon");
492
                    break;
493
                case AdditionalInfoVectorLayer.SHAPE_TYPE_POINT:
494
                    s = s + " - " + Sextante.getText("Point");
495
                    break;
496
                }
497
            } catch (final NullParameterAdditionalInfoException e) {
498
                // Nothing to do
499
            }
500
        }
501

    
502
        return s;
503

    
504
    }
505

    
506
    public HashMap<NameAndIcon, ArrayList<ToolboxAction>> getToolboxActions() {
507
        return new HashMap<NameAndIcon, ArrayList<ToolboxAction>>();
508
     }
509

    
510

    
511
     public IToolboxRightButtonAction[] getToolboxRightButtonActions() {
512
        return new IToolboxRightButtonAction[0];
513
     }
514
}