Statistics
| Revision:

gvsig-geoprocess / org.gvsig.geoprocess / branches / refactor-2018 / org.gvsig.geoprocess / org.gvsig.geoprocess.lib / org.gvsig.geoprocess.lib.sextante / src / main / java / org / gvsig / geoprocess / lib / sextante / SextanteGeoProcessManager.java @ 1059

History | View | Annotate | Download (20.5 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.InputStream;
27
import java.net.URL;
28
import java.util.ArrayList;
29
import java.util.HashMap;
30
import java.util.Iterator;
31
import java.util.List;
32
import java.util.Locale;
33
import java.util.Map;
34
import java.util.Set;
35
import java.util.Map.Entry;
36

    
37
import javax.swing.ImageIcon;
38

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

    
49
import es.unex.sextante.additionalInfo.AdditionalInfoVectorLayer;
50
import es.unex.sextante.core.GeoAlgorithm;
51
import es.unex.sextante.core.OutputObjectsSet;
52
import es.unex.sextante.core.ParametersSet;
53
import es.unex.sextante.core.Sextante;
54
import es.unex.sextante.docEngines.html.HTMLDoc;
55
import es.unex.sextante.exceptions.NullParameterAdditionalInfoException;
56
import es.unex.sextante.gui.algorithm.DefaultParametersPanel;
57
import es.unex.sextante.gui.algorithm.GeoAlgorithmParametersPanel;
58
import es.unex.sextante.gui.core.IAlgorithmProvider;
59
import es.unex.sextante.gui.core.IToolboxRightButtonAction;
60
import es.unex.sextante.gui.core.NameAndIcon;
61
import es.unex.sextante.gui.core.ToolboxAction;
62
import es.unex.sextante.gui.help.HelpElement;
63
import es.unex.sextante.gui.help.ImageAndDescription;
64
import es.unex.sextante.gui.modeler.DefaultModelerParametersPanel;
65
import es.unex.sextante.gui.settings.Setting;
66
import es.unex.sextante.outputs.Output;
67
import es.unex.sextante.outputs.Output3DRasterLayer;
68
import es.unex.sextante.outputs.OutputChart;
69
import es.unex.sextante.outputs.OutputNumericalValue;
70
import es.unex.sextante.outputs.OutputRasterLayer;
71
import es.unex.sextante.outputs.OutputTable;
72
import es.unex.sextante.outputs.OutputText;
73
import es.unex.sextante.outputs.OutputVectorLayer;
74
import es.unex.sextante.parameters.Parameter;
75
import es.unex.sextante.parameters.ParameterVectorLayer;
76
import org.gvsig.geoprocess.lib.api.GeoProcessBuiler;
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
    @Override
102
    public String getTranslation(String label) {
103
        // Just in case an algorithm is using a sextante label
104
        String text = i18nManager.getTranslation(label);
105
        return text == null ? Sextante.getText(label) : text;
106
    }
107

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

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

    
137
    @Override
138
    public void initialize() {
139
        // Nothing to do
140
    }
141

    
142
    @Override
143
    public String getName() {
144
        return Messages.getText("gv_algorithms");
145
    }
146

    
147
    @Override
148
    public HashMap<String, GeoAlgorithm> getAlgorithms() {
149
        return new HashMap<String, GeoAlgorithm>(geoprocesses);
150
    }
151

    
152
    @Override
153
    public HashMap<String, Class> getCustomModelerParameterPanels() {
154
        final HashMap<String, Class> map = new HashMap<String, Class>();
155
        final Set<String> set = getAlgorithms().keySet();
156
        final Iterator<String> iter = set.iterator();
157
        while (iter.hasNext()) {
158
            map.put(iter.next(), DefaultModelerParametersPanel.class);
159
        }
160

    
161
        return map;
162
    }
163

    
164
    @Override
165
    public HashMap<String, Class> getCustomParameterPanels() {
166
        final HashMap<String, Class> map = new HashMap<String, Class>();
167
        final Set<Entry<String, GeoAlgorithm>> set = getAlgorithms().entrySet();
168
        final Iterator<Entry<String, GeoAlgorithm>> iter = set.iterator();
169
        while (iter.hasNext()) {
170
            Entry<String, GeoAlgorithm> entry = iter.next();
171
            GeoAlgorithm algorithm = entry.getValue();
172
            Class<? extends GeoAlgorithmParametersPanel> panelClazz = null;
173
            if (algorithm instanceof AbstractSextanteGeoProcess) {
174
                panelClazz =
175
                    ((AbstractSextanteGeoProcess) algorithm)
176
                        .getCustomParametersPanelClass();
177
            }
178
            map.put(entry.getKey(), (panelClazz == null
179
                ? DefaultParametersPanel.class : panelClazz));
180
        }
181

    
182
        return map;
183
    }
184

    
185
    @Override
186
    public ImageIcon getIcon() {
187
        return IconThemeHelper.getImageIcon("gvsig-icon16x16");
188
    }
189

    
190
    @Override
191
    public Setting getSettings() {
192
        return new GeoprocessSetting();
193
    }
194

    
195
    @Override
196
    public void update() {
197
        // Nothing to do
198
    }
199

    
200
    @Override
201
    public Object getAlgorithmHelp(GeoAlgorithm alg) {
202
        String algName = alg.getClass().getSimpleName();
203
        String helpFileName =
204
            algName + "_" + Locale.getDefault().getLanguage() + ".xml";
205
        String currentLocaleHelp = "help" + "/" + helpFileName;
206
        InputStream is =
207
            alg.getClass().getClassLoader()
208
                .getResourceAsStream(currentLocaleHelp);
209
        if (is == null) {
210
            helpFileName = algName + ".xml";
211
            currentLocaleHelp = "help" + "/" + helpFileName;
212
            is =
213
                alg.getClass().getClassLoader()
214
                    .getResourceAsStream(currentLocaleHelp);
215
        }
216

    
217
        if (is == null) {
218
            return null;
219
        }
220

    
221
        // The following code has been extracted from the
222
        // es.unex.sextante.gui.help.HelpIO getHelpAsHTMLCode method, as it
223
        // works with a string file path, and we need a stream from a classpath
224
        // resource.
225

    
226
        URL helpURL =
227
            alg.getClass().getClassLoader().getResource(currentLocaleHelp);
228
        String helpBaseURL = helpURL.toString();
229
        int lastIndex = helpBaseURL.length() - helpFileName.length();
230
        helpBaseURL = helpBaseURL.substring(0, lastIndex);
231
        HelpElement element;
232
        Map<String, HelpElement> elements = readHelpElements(is);
233

    
234
        HTMLDoc doc = new HTMLDoc();
235

    
236
        doc.open(alg.getName());
237
        doc.addHeader(Sextante.getText(alg.getName()), 1);
238
        doc.addHeader(Sextante.getText("Description"), 2);
239

    
240
        element = (HelpElement) elements.get("DESCRIPTION");
241
        if (element != null) {
242
            doc.addParagraph(element.getTextAsFormattedHTML());
243
            for (int j = 0; j < element.getImages().size(); j++) {
244
                ImageAndDescription iad =
245
                    (ImageAndDescription) element.getImages().get(j);
246
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
247
                    iad.getDescription());
248
            }
249
        }
250

    
251
        doc.addHeader(Sextante.getText("Parameters"), 2);
252

    
253
        ParametersSet params = alg.getParameters();
254

    
255
        doc.startUnorderedList();
256
        for (int i = 0; i < params.getNumberOfParameters(); i++) {
257
            Parameter param = params.getParameter(i);
258
            String sParam = param.getParameterDescription();
259
            sParam =
260
                "<b>" + sParam + "[" + getParameterTypeName(param) + "]: </b>";
261
            element = (HelpElement) elements.get(param.getParameterName());
262
            if (element != null) {
263
                sParam = sParam + element.getTextAsFormattedHTML();
264
            }
265
            doc.addListElement(sParam);
266
            if (element != null) {
267
                for (int j = 0; j < element.getImages().size(); j++) {
268
                    final ImageAndDescription iad =
269
                        (ImageAndDescription) element.getImages().get(j);
270
                    doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
271
                        iad.getDescription());
272
                }
273
            }
274

    
275
        }
276

    
277
        doc.closeUnorderedList();
278

    
279
        doc.addHeader(Sextante.getText("Outputs"), 2);
280

    
281
        element = (HelpElement) elements.get("OUTPUT_DESCRIPTION");
282
        if (element != null) {
283
            doc.addParagraph(element.getTextAsFormattedHTML());
284
            for (int j = 0; j < element.getImages().size(); j++) {
285
                final ImageAndDescription iad =
286
                    (ImageAndDescription) element.getImages().get(j);
287
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
288
                    iad.getDescription());
289
            }
290
        }
291

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

    
348
        }
349
        doc.closeUnorderedList();
350

    
351
        doc.addHeader(Sextante.getText("Additional_information"), 2);
352

    
353
        element = (HelpElement) elements.get("ADDITIONAL_INFO");
354
        if (element != null) {
355
            doc.addParagraph(element.getTextAsFormattedHTML());
356
            for (int j = 0; j < element.getImages().size(); j++) {
357
                ImageAndDescription iad =
358
                    (ImageAndDescription) element.getImages().get(j);
359
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
360
                    iad.getDescription());
361
            }
362
        }
363

    
364
        doc.addHeader(Sextante.getText("Command_line"), 2);
365

    
366
        String sText = alg.getCommandLineHelp();
367
        sText = sText.replaceAll("\n", "<br>");
368
        sText = sText.replace("   ", " &nbsp ");
369
        doc.addCourierText(sText);
370

    
371
        doc.addParagraph("");
372

    
373
        element = (HelpElement) elements.get("EXTENSION_AUTHOR");
374
        if (element != null) {
375
            doc.addParagraph("<i>" + Sextante.getText("Algorithm_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
        element = (HelpElement) elements.get("HELP_AUTHOR");
386
        if (element != null) {
387
            doc.addParagraph("<i>" + Sextante.getText("Help_file_created_by")
388
                + " " + element.getText() + "</i>");
389
            for (int j = 0; j < element.getImages().size(); j++) {
390
                ImageAndDescription iad =
391
                    (ImageAndDescription) element.getImages().get(j);
392
                doc.addImageAndDescription(helpBaseURL + iad.getFilename(),
393
                    iad.getDescription());
394
            }
395
        }
396

    
397
        doc.close();
398

    
399
        return doc.getHTMLCode();
400
    }
401

    
402
    @Override
403
    public String getAlgorithmHelpFilename(GeoAlgorithm alg,
404
        boolean bForceCurrentLocale) {
405
        // TODO Auto-generated method stub
406
        return null;
407
    }
408

    
409
    @Override
410
    public boolean canEditHelp() {
411
        return false;
412
    }
413

    
414
    private Map<String, HelpElement> readHelpElements(InputStream is) {
415
        List<ImageAndDescription> images = null;
416
        Map<String, HelpElement> elements = new HashMap<String, HelpElement>();
417
        HelpElement element = null;
418
        KXmlParser parser = new KXmlParser();
419
        try {
420
            parser.setInput(is, XML_PARSER_ENCODING);
421
            int tag = parser.nextTag();
422
            boolean bOut = false;
423
            String name;
424

    
425
            if (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
426
                while ((tag != XmlPullParser.END_DOCUMENT) && !bOut) {
427
                    switch (tag) {
428
                    case XmlPullParser.START_TAG:
429
                        name = parser.getName();
430
                        if (HELP.equals(name)) {
431
                        } else if (HelpElement.ELEMENT.equals(name)) {
432
                            images = new ArrayList<ImageAndDescription>();
433
                            String sText =
434
                                parser.getAttributeValue("", HelpElement.TEXT);
435
                            String sName =
436
                                parser.getAttributeValue("", HelpElement.NAME);
437
                            String sDescription =
438
                                parser.getAttributeValue("",
439
                                    HelpElement.DESCRIPTION);
440
                            int iType =
441
                                Integer.parseInt(parser.getAttributeValue("",
442
                                    HelpElement.TYPE));
443
                            element = new HelpElement();
444
                            element.setText(sText);
445
                            element.setName(sName);
446
                            element.setType(iType);
447
                            element.setDescription(sDescription);
448
                        } else if (ImageAndDescription.IMAGE.equals(name)) {
449
                            final ImageAndDescription iad =
450
                                new ImageAndDescription();
451
                            final String sImageFilename =
452
                                parser.getAttributeValue("",
453
                                    ImageAndDescription.FILE);
454
                            final String sDesc =
455
                                parser.getAttributeValue("",
456
                                    ImageAndDescription.DESCRIPTION);
457
                            iad.setDescription(sDesc);
458
                            iad.setFilename(sImageFilename);
459
                            images.add(iad);
460
                        }
461
                        break;
462
                    case XmlPullParser.END_TAG:
463
                        name = parser.getName();
464
                        if (HELP.equals(name)) {
465
                            bOut = true;
466
                        } else if (HelpElement.ELEMENT.equals(name)) {
467
                            element.setImages((ArrayList) images);
468
                            elements.put(element.getName(), element);
469
                        }
470
                        break;
471
                    case XmlPullParser.TEXT:
472
                        break;
473
                    }
474
                    if (!bOut) {
475
                        tag = parser.next();
476
                    }
477
                }
478
            }
479

    
480
        } catch (final Exception e) {
481
            return null;
482
        }
483
        return elements;
484
    }
485

    
486
    private String getParameterTypeName(Parameter param) {
487

    
488
        String s =
489
            Sextante.getText(param.getParameterTypeName().replace(' ', '_'));
490

    
491
        if (param instanceof ParameterVectorLayer) {
492
            try {
493
                final AdditionalInfoVectorLayer ai =
494
                    (AdditionalInfoVectorLayer) param
495
                        .getParameterAdditionalInfo();
496
                switch (ai.getShapeType()) {
497
                case AdditionalInfoVectorLayer.SHAPE_TYPE_ANY:
498
                default:
499
                    s = s + " - " + Sextante.getText("Any_type");
500
                    break;
501
                case AdditionalInfoVectorLayer.SHAPE_TYPE_LINE:
502
                    s = s + " - " + Sextante.getText("Line");
503
                    break;
504
                case AdditionalInfoVectorLayer.SHAPE_TYPE_POLYGON:
505
                    s = s + " - " + Sextante.getText("Polygon");
506
                    break;
507
                case AdditionalInfoVectorLayer.SHAPE_TYPE_POINT:
508
                    s = s + " - " + Sextante.getText("Point");
509
                    break;
510
                }
511
            } catch (final NullParameterAdditionalInfoException e) {
512
                // Nothing to do
513
            }
514
        }
515

    
516
        return s;
517

    
518
    }
519

    
520
    @Override
521
    public HashMap<NameAndIcon, ArrayList<ToolboxAction>> getToolboxActions() {
522
        return new HashMap<NameAndIcon, ArrayList<ToolboxAction>>();
523
     }
524

    
525

    
526
    @Override
527
     public IToolboxRightButtonAction[] getToolboxRightButtonActions() {
528
        return new IToolboxRightButtonAction[0];
529
     }
530

    
531
    @Override
532
    public GeoProcessBuiler createGeoProcessBuilder() {
533
        return new GeoProcessBuilerBase();
534
    }
535
     
536
     
537
}