Statistics
| Revision:

root / org.gvsig.toolbox / trunk / org.gvsig.toolbox / org.gvsig.toolbox.gui / src / main / java / es / unex / sextante / gui / core / SextanteGUI.java @ 239

History | View | Annotate | Download (35.9 KB)

1

    
2

    
3
package es.unex.sextante.gui.core;
4

    
5
import java.awt.Color;
6
import java.awt.Container;
7
import java.awt.Frame;
8
import java.io.BufferedReader;
9
import java.io.BufferedWriter;
10
import java.io.File;
11
import java.io.FileNotFoundException;
12
import java.io.FileReader;
13
import java.io.FileWriter;
14
import java.io.IOException;
15
import java.io.Writer;
16
import java.net.URL;
17
import java.util.ArrayList;
18
import java.util.HashMap;
19
import java.util.Iterator;
20
import java.util.Set;
21

    
22
import javax.swing.ImageIcon;
23
import javax.swing.JDialog;
24
import javax.swing.JOptionPane;
25

    
26
import es.unex.sextante.core.GeoAlgorithm;
27
import es.unex.sextante.core.IInputFactory;
28
import es.unex.sextante.core.OutputFactory;
29
import es.unex.sextante.core.Sextante;
30
import es.unex.sextante.gui.cmd.ScriptAlgorithmProvider;
31
import es.unex.sextante.gui.help.HelpIO;
32
import es.unex.sextante.gui.modeler.ModelerAlgorithmProvider;
33
import es.unex.sextante.gui.settings.Setting;
34
import es.unex.sextante.gui.settings.SextanteGeneralSettings;
35
import es.unex.sextante.gui.settings.SextanteGrassSettings;
36
import es.unex.sextante.gui.settings.SextanteModelerSettings;
37
import es.unex.sextante.gui.settings.SextanteRSettings;
38
import es.unex.sextante.gui.settings.SextanteSagaSettings;
39
import es.unex.sextante.gui.settings.SextanteScriptsSettings;
40

    
41

    
42
/**
43
 * This class centralizes most actions related to the SextanteGUI, containing methods to show dialogs and retrieve basic values
44
 * used by GUI elements
45
 */
46
public class SextanteGUI {
47
   public static String                               resourcePrefix              = "org.gvsig.toolbox";
48
   public static final int                            HISTORY                     = 0;
49
   public static final int                            COMMANDLINE                 = 1;
50

    
51
   private static IInputFactory                       m_InputFactory;
52
   private static OutputFactory                       m_OutputFactory;
53
   private static IGUIFactory                         m_GUIFactory                = new DefaultGUIFactory();
54

    
55
   private static IPostProcessTaskFactory             m_PostProcessTaskFactory;
56

    
57
   private static JDialog                             m_LastCommandOriginParentPanel;
58
   private static int                                 m_iLastCommandOrigin;
59
   private static Frame                               m_MainFrame;
60

    
61
   private static boolean                             m_bShowOnlyActiveAlgorithms = false;
62
   private static String                              m_sOutputFolder;
63
   private static HashMap<String, String>             m_Settings                  = new HashMap<String, String>();
64
   private static HashMap<String, String>             m_DefaultSettings           = new HashMap<String, String>();
65
   private static IDataRenderer                       m_Renderer;
66
   private static String m_sSextanteHomePath;
67
   private static String m_sSextanteInstallPath;
68

    
69
   private static ArrayList<String> foldersWithResources = new ArrayList<String>();
70
   private static boolean initialized = false;
71

    
72

    
73
   private final static HashMap<String, Class>        m_ParametersPanel           = new HashMap<String, Class>();
74
   private final static HashMap<String, Class>        m_ModelerParametersPanel    = new HashMap<String, Class>();
75

    
76
   private final static ArrayList<IAlgorithmProvider> m_AlgorithmProviders        = new ArrayList<IAlgorithmProvider>();
77

    
78
   public final static ImageIcon                      SEXTANTE_ICON               = new ImageIcon(
79
                                                                                           SextanteGUI.class.getClassLoader().getResource(
80
                                                                                                    "images/module2.png"));
81

    
82
   public final static Color COLOR_WHITE = new Color(255, 255, 255, 255);
83
   public final static Color COLOR_GREY = new Color(128, 128, 128, 255);
84
   public final static Color COLOR_BLACK = new Color(0, 0, 0, 255);
85
   public final static Color COLOR_RED = new Color (255, 51, 51, 255);
86
   public final static Color COLOR_ORANGE = new Color(255, 103, 51, 255);
87
   public final static Color COLOR_YELLOW = new Color(255, 255, 51, 255);
88
   public final static Color COLOR_GREEN_LIGHT = new Color(51, 255, 51, 255);
89
   public final static Color COLOR_GREEN_DARK = new Color(0, 184, 0, 255);
90
   public final static Color COLOR_BLUE_LIGHT = new Color (102, 179, 255, 255);
91
   public final static Color COLOR_BLUE_DARK = new Color (0, 102, 204, 255);
92
   public final static Color COLOR_PINK = new Color(255, 153, 255, 255);
93
   public final static Color COLOR_PURPLE = new Color(163, 71, 255, 255);
94
   public final static Color COLOR_BROWN_LIGHT = new Color(255, 168, 82, 255);
95
   public final static Color COLOR_BROWN_DARK = new Color(204, 102, 0, 255);
96

    
97

    
98
   static {
99

    
100
      m_AlgorithmProviders.add(new ScriptAlgorithmProvider());
101
      m_AlgorithmProviders.add(new ModelerAlgorithmProvider());
102

    
103
   }
104

    
105

    
106
   /**
107
    * Sets a new main frame. This will be used as the parent frame by SEXTANTE GUI elements
108
    *
109
    * @param frame
110
    *                The main frame
111
    */
112
   public static void setMainFrame(final Frame frame) {
113

    
114
      m_MainFrame = frame;
115

    
116
   }
117

    
118

    
119
   /**
120
    * Returns the current main frame
121
    *
122
    * @return the current main frame
123
    */
124
   public static Frame getMainFrame() {
125

    
126
      return m_MainFrame;
127

    
128
   }
129

    
130

    
131
   /** ************************************************************ */
132

    
133
   /**
134
    * Returns the current input factory
135
    *
136
    * @see IInputFactory.
137
    * @return the current input factory
138
    */
139
   public static IInputFactory getInputFactory() {
140

    
141
      return m_InputFactory;
142

    
143
   }
144

    
145

    
146
   /**
147
    * Sets a new input factory as the current one
148
    *
149
    * @param inputFactory
150
    *                the new input factory
151
    */
152
   public static void setInputFactory(final IInputFactory inputFactory) {
153

    
154
      m_InputFactory = inputFactory;
155

    
156
   }
157

    
158

    
159
   /**
160
    * Returns the current OutputFactory
161
    *
162
    * @return the current OutputFactory
163
    */
164
   public static OutputFactory getOutputFactory() {
165

    
166
      return m_OutputFactory;
167

    
168
   }
169

    
170

    
171
   /**
172
    * sets a new output factory
173
    *
174
    * @param outputFactory
175
    *                the new output factory
176
    */
177
   public static void setOutputFactory(final OutputFactory outputFactory) {
178

    
179
      m_OutputFactory = outputFactory;
180
      m_OutputFactory.setDefaultNoDataValue(getDefaultNoDataValue());
181

    
182
   }
183

    
184

    
185
   /**
186
    * Returns the current GUIFactory
187
    *
188
    * @return the current GUIFactory
189
    */
190
   public static IGUIFactory getGUIFactory() {
191

    
192
      return m_GUIFactory;
193

    
194
   }
195

    
196

    
197
   /**
198
    * sets a new GUI factory
199
    *
200
    * @param guiFactory
201
    *                the new GUI factory
202
    */
203
   public static void setGUIFactory(final IGUIFactory guiFactory) {
204

    
205
      m_GUIFactory = guiFactory;
206

    
207
   }
208

    
209

    
210
   /**
211
    * Returns the task to post-process the algorithm outputs, usually to add them to the GUI of the GIS app.
212
    *
213
    * @param alg
214
    *                the algorithm to postprocess. Since this task will mainly deal with output results, the algorithm should have
215
    *                been previously executed, so it contains non-null output values
216
    * @param bShowResultsDialog
217
    *                if this parameter is true, the task will show the results dialog if the algorithm has produced some kind of
218
    *                output other than layers or tables. If it is false, those results will be added to the set of current
219
    *                results, but the results dialog will not be shown
220
    *
221
    * @return a task to postprocess the given algorithm
222
    */
223
   public static Runnable getPostProcessTask(final GeoAlgorithm alg,
224
                                             final boolean bShowResultsDialog) {
225

    
226
      return m_PostProcessTaskFactory.getPostProcessTask(alg, bShowResultsDialog);
227

    
228
   }
229

    
230

    
231
   /**
232
    * Sets the current post process task factory
233
    *
234
    * @param factory
235
    *                the new post-process task factory
236
    */
237
   public static void setPostProcessTaskFactory(final IPostProcessTaskFactory factory) {
238

    
239
      m_PostProcessTaskFactory = factory;
240

    
241
   }
242

    
243

    
244
   /** ******************************************* */
245

    
246
   /**
247
    * Adds an algorithm provider. This has to be done before calling initialize(), so the providers can be initialized as well.
248
    *
249
    * @param provider
250
    *                the algorithm provider to add
251
    */
252
   public static void addAlgorithmProvider(final IAlgorithmProvider provider) {
253

    
254
      //providers are added at the beginning of the array, because models and scripts might depend on them
255
      m_AlgorithmProviders.add(0, provider);
256

    
257
   }
258

    
259

    
260
   /**
261
    * Checks if a portable directory exists and has the required access privileges.
262
    * Non-existing directories will be created if possible.
263
    * Displays a GUI warning message if there are problems, and exits with a corresponding error code.
264
    *
265
    * @param dir String with name of folder/directory to be checked. Use only a relative path here.
266
    * @param read_only set to "true" if only read access is required
267
    * @param provider name of the algorithm provider for which this folder is being checked.
268
    * @return "0" if all is OK, "1" if directory does not exist and could not be created, "2" if access is forbidden, "3" if a _file_ with that name already exists
269
    */
270
   public static int checkDir ( String dir, boolean read_only, String provider ) {
271

    
272
          final File f = new File ( SextanteGUI.getSextanteHomePath() + File.separator + dir );
273

    
274
          if ( f.exists() ) {
275
                  if ( f.isFile() ) {
276
                          JOptionPane.showMessageDialog(null,
277
                                          Sextante.getText("portable_dir_error") + " " + f.getAbsolutePath() + ".\n" +
278
                                          Sextante.getText("portable_dir_is_file") + "\n" +
279
                                          Sextante.getText("portable_provider_not_usable") + " <html></i>" + provider + "+</i>+</html>."
280
                                          , "Inane warning", JOptionPane.WARNING_MESSAGE);
281
                          return ( 3 );
282
                  }
283
                  if ( read_only ) {
284
                          if ( f.canRead() ) {
285
                                  return ( 0 );
286
                          }
287
                  }
288
                  if ( f.canWrite() ) {
289
                          return ( 0 );
290
                  }
291
                  if ( read_only ) {
292
                          JOptionPane.showMessageDialog(null,
293
                                          Sextante.getText("portable_dir_error") + " " + f.getAbsolutePath() +
294
                                          Sextante.getText("portable_dir_error_ro") + "\n" + ":" +
295
                                          Sextante.getText("portable_dir_no_access") + "\n" +
296
                                          Sextante.getText("portable_provider_not_usable") + " <html></i>" + provider + "+</i>+</html>."
297
                                          , "Inane warning", JOptionPane.WARNING_MESSAGE);
298
                  } else {
299
                          JOptionPane.showMessageDialog(null,
300
                                          Sextante.getText("portable_dir_error") + " " + f.getAbsolutePath() +
301
                                          Sextante.getText("portable_dir_error_rw") + "\n" + ":" +
302
                                          Sextante.getText("portable_dir_no_access") + "\n" +
303
                                          Sextante.getText("portable_provider_not_usable") + " <html></i>" + provider + "+</i>+</html>."
304
                                          , "Inane warning", JOptionPane.WARNING_MESSAGE);
305
                  }
306
                  return ( 2 );
307
          }
308

    
309
          /* directory does not exist: attempt to create it */
310
          if ( f.mkdir() == false ) {
311
                  JOptionPane.showMessageDialog(null,
312
                                  Sextante.getText("portable_dir_error") + " " + f.getAbsolutePath() + ".\n" +
313
                                  Sextante.getText("portable_dir_no_create") + "\n" +
314
                                  Sextante.getText("portable_provider_not_usable") + " <html></i>" + provider + "+</i>+</html>."
315
                                  , "Inane warning", JOptionPane.WARNING_MESSAGE);
316
                  return ( 1 );
317
          }
318

    
319
          return ( 0 );
320
   }
321

    
322

    
323
   /**
324
    * Checks if a file exists in one of the portable folders, and if it has the required access privileges.
325
    * Displays a GUI warning message if there are problems, and exits with a corresponding error code.
326
    *
327
    * @param file String with name of file to be checked. Use only a relative path here.
328
    * @param read_only set to "true" if only read access is required
329
    * @param provider name of the algorithm provider for which this file is being checked.
330
    * @return "0" if all is OK, "1" if file does not exist, "2" if access is forbidden, "3" if a _directory_ with that name already exists
331
    */
332
   public static int checkFile ( String file, boolean read_only, String provider ) {
333

    
334
          final File f = new File ( SextanteGUI.getSextanteHomePath() + File.separator + file );
335

    
336
          if ( f.exists() ) {
337
                  if ( f.isDirectory() ) {
338
                          JOptionPane.showMessageDialog(null,
339
                                          Sextante.getText("portable_file_error") + " " + f.getAbsolutePath() + ".\n" +
340
                                          Sextante.getText("portable_file_is_dir") + "\n" +
341
                                          Sextante.getText("portable_provider_not_usable") + " <html></i>" + provider + "+</i>+</html>."
342
                                          , "Inane warning", JOptionPane.WARNING_MESSAGE);
343
                          return ( 3 );
344
                  }
345
                  if ( read_only ) {
346
                          if ( f.canRead() ) {
347
                                  return ( 0 );
348
                          }
349
                  }
350
                  if ( f.canWrite() ) {
351
                          return ( 0 );
352
                  }
353
                  if ( read_only ) {
354
                          JOptionPane.showMessageDialog(null,
355
                                          Sextante.getText("portable_file_error") + " " + f.getAbsolutePath() +
356
                                          Sextante.getText("portable_file_error_ro") + "\n" + ":" +
357
                                          Sextante.getText("portable_file_no_access") + "\n" +
358
                                          Sextante.getText("portable_provider_not_usable") + " <html></i>" + provider + "+</i>+</html>."
359
                                          , "Inane warning", JOptionPane.WARNING_MESSAGE);
360
                  } else {
361
                          JOptionPane.showMessageDialog(null,
362
                                          Sextante.getText("portable_file_error") + " " + f.getAbsolutePath() +
363
                                          Sextante.getText("portable_file_error_rw") + "\n" + ":" +
364
                                          Sextante.getText("portable_file_no_access") + "\n" +
365
                                          Sextante.getText("portable_provider_not_usable") + " <html></i>" + provider + "+</i>+</html>."
366
                                          , "Inane warning", JOptionPane.WARNING_MESSAGE);
367
                  }
368
                  return ( 2 );
369
          }
370

    
371
          return ( 1 );
372
   }
373

    
374

    
375
   /**
376
    * Portable SEXTANTE requires that external providers' (e.g. GRASS) algorithms
377
    * and user-editable scripts are stored in folders within the SEXTANTE extension
378
    * folder. In some case, read access to these folders is fine, in others r/w is required.
379
    * This method checks whether an algorithm provider has been set to be portable and
380
    * if so, it makes sure that the required folder(s) is/are present with the required
381
    * access rights. It will attempt to create any missing folders and will display a
382
    * warning if anythign goes wrong.
383
    */
384
   public static void checkPortableFolders () {
385

    
386
           String sPath;
387
           int result;
388

    
389

    
390
           sPath = new String ("");
391

    
392
           if ( Boolean.parseBoolean(SextanteGUI.getSettingParameterValue(SextanteRSettings.R_PORTABLE)) == true ) {
393
                   /* set R binaries folder */
394
                   result = checkDir ( Sextante.PORTABLE_R_FOLDER, true, "R" );
395
                   sPath = SextanteGUI.getSextanteInstallPath() + File.separator + Sextante.PORTABLE_R_FOLDER;
396
                   SextanteGUI.setSettingParameterValue(SextanteRSettings.R_FOLDER, sPath);
397

    
398
                   /* set R user scripts folder */
399
                   result = checkDir ( Sextante.PORTABLE_R_SCRIPTS_FOLDER, false, "R user scripts" );
400
                   sPath = SextanteGUI.getSextanteInstallPath() + File.separator + Sextante.PORTABLE_R_SCRIPTS_FOLDER;
401
                   SextanteGUI.setSettingParameterValue(SextanteRSettings.R_SCRIPTS_FOLDER, sPath);
402
           }
403
           if ( Boolean.parseBoolean(SextanteGUI.getSettingParameterValue(SextanteGrassSettings.GRASS_PORTABLE)) == true ) {
404
                   /* set GRASS binaries folder */
405
                   result = checkDir ( Sextante.PORTABLE_GRASS_FOLDER, true, "GRASS GIS" );
406
                   sPath = SextanteGUI.getSextanteInstallPath() + File.separator + Sextante.PORTABLE_GRASS_FOLDER;
407
                   SextanteGUI.setSettingParameterValue(SextanteGrassSettings.GRASS_FOLDER, sPath);
408
                   /* set GRASS shell support (MSYS) binaries folder (Windows only) */
409
                   if ( Sextante.isWindows() ) {
410
                           result = checkFile ( Sextante.PORTABLE_MSYS_FILE, true, "GRASS GIS shell scripts" );
411
                           sPath = SextanteGUI.getSextanteInstallPath() + File.separator + Sextante.PORTABLE_MSYS_FILE;
412
                           SextanteGUI.setSettingParameterValue(SextanteGrassSettings.GRASS_WIN_SHELL, sPath);
413
                   }
414
           }
415
           if ( Boolean.parseBoolean(SextanteGUI.getSettingParameterValue(SextanteSagaSettings.SAGA_PORTABLE)) == true ) {
416
                   /* set SAGA binaries folder */
417
                   result = checkDir ( Sextante.PORTABLE_SAGA_FOLDER, true, "SAGA GIS" );
418
                   sPath = SextanteGUI.getSextanteInstallPath() + File.separator + Sextante.PORTABLE_SAGA_FOLDER;
419
                   SextanteGUI.setSettingParameterValue(SextanteSagaSettings.SAGA_FOLDER, sPath);
420
           }
421
           if ( Boolean.parseBoolean(SextanteGUI.getSettingParameterValue(SextanteScriptsSettings.SCRIPTS_PORTABLE)) == true ) {
422
                   /* set user scripts folder */
423
                   result = checkDir ( Sextante.PORTABLE_SCRIPTS_FOLDER, true, "Toolbox user scripts" );
424
                   sPath = SextanteGUI.getSextanteHomePath() + File.separator + Sextante.PORTABLE_SCRIPTS_FOLDER;
425
                   SextanteGUI.setSettingParameterValue(SextanteScriptsSettings.SCRIPTS_FOLDER, sPath);
426
           }
427
           if ( Boolean.parseBoolean(SextanteGUI.getSettingParameterValue(SextanteModelerSettings.MODELS_PORTABLE)) == true ) {
428
                   /* set user models folder */
429
                   result = checkDir ( Sextante.PORTABLE_MODELS_FOLDER, true, "Toolbox user models" );
430
                   sPath = SextanteGUI.getSextanteHomePath() + File.separator + Sextante.PORTABLE_MODELS_FOLDER;
431
                   SextanteGUI.setSettingParameterValue(SextanteModelerSettings.MODELS_FOLDER, sPath);
432
           }
433
   }
434

    
435

    
436
   /**
437
    * Initializes the GUI parameters and resources. It takes GUI resources (custom panels, etc.) from classpath jars. Should be
438
    * called before setting parameters using other methods from this class, except for the setSextantePath() and
439
    * setCustomDefaultSettings() methods.
440
    */
441
   public static void initialize() {
442

    
443
      GUIResources.addResourcesFromClasspath();
444
      _initialize();
445

    
446
   }
447

    
448

    
449
   /**
450
    * Initializes the GUI parameters and resources. It takes GUI resources (custom panels, etc.) from the specified urls. Should
451
    * be called before setting parameters using other methods from this class, except for the setSextantePath() method.
452
    *
453
    * @param jars
454
    *                the urls of the jar files with custom GUI resources
455
    */
456
   public static void initialize(final URL[] jars) {
457

    
458
      GUIResources.addResourcesFromURLs(jars);
459
      _initialize();
460

    
461
   }
462

    
463

    
464
   /**
465
    * Initializes the GUI parameters and resources. It takes GUI resources (custom panels, etc.) from the specified folder. Should
466
    * be called before setting parameters using other methods from this class, except for the setSextantePath() method.
467
    *
468
    * @param sFolder
469
    *                the folder with jars with custom GUI resources
470
    */
471
   public static void initialize(final String sFolder) {
472

    
473
      GUIResources.addResourcesFromFolder(sFolder);
474
      _initialize();
475

    
476

    
477
   }
478

    
479
    public static void addResourcesFromFolder(final String sFolder) {
480
        if (initialized) {
481
            GUIResources.addResourcesFromFolder(sFolder);
482
            loadResources();
483
        } else {
484
            foldersWithResources.add(sFolder);
485
        }
486
    }
487

    
488
    private static void _initialize() {
489

    
490
        setDefaultSettings();
491
        readConfigFile();
492

    
493
        checkPortableFolders();
494

    
495

    
496
        for (Iterator iterator = foldersWithResources.iterator(); iterator
497
            .hasNext();) {
498
            String sFolder = (String) iterator.next();
499
            GUIResources.addResourcesFromFolder(sFolder);
500
        }
501

    
502
        // this loads built-in SEXTANTE algorithms and resources
503
        loadResources();
504

    
505
        // and this loads additional algorithms from algorithm providers
506
        for (int i = 0; i < m_AlgorithmProviders.size(); i++) {
507
            final IAlgorithmProvider provider = m_AlgorithmProviders.get(i);
508
            provider.initialize();
509
            if (provider.getAlgorithms().size() > 0) {
510
                Sextante.addAlgorithmsFromProvider(provider.getName(),
511
                    provider.getAlgorithms());
512
                addCustomModelerParametersPanel(provider
513
                    .getCustomModelerParameterPanels());
514
                addCustomParametersPanel(provider.getCustomParameterPanels());
515
            }
516
        }
517

    
518
        initialized = true;
519

    
520
    }
521

    
522

    
523
   private static void setDefaultSettings() {
524

    
525
      final Setting[] baseSettings = new Setting[] { new SextanteGeneralSettings() };
526
      final ArrayList<IAlgorithmProvider> providers = SextanteGUI.getAlgorithmProviders();
527
      final Setting[] settings = new Setting[baseSettings.length + providers.size()];
528
      System.arraycopy(baseSettings, 0, settings, 0, baseSettings.length);
529
      for (int i = 0; i < providers.size(); i++) {
530
         settings[i + baseSettings.length] = providers.get(i).getSettings();
531
      }
532

    
533
      for (int i = 0; i < settings.length; i++) {
534
         final HashMap<String, String> map = settings[i].getInitValues();
535
         m_Settings.putAll(map);
536
      }
537

    
538
      if (m_DefaultSettings != null) {
539
         m_Settings.putAll(m_DefaultSettings);
540
      }
541

    
542
   }
543

    
544

    
545
   /**
546
    * This methods sets default setting values different from the hard-coded ones. It should be called right before initializing
547
    * this class
548
    *
549
    * @param map
550
    *                the map with new default settings
551
    */
552
   public static void setCustomDefaultSettings(final HashMap<String, String> map) {
553

    
554
      m_DefaultSettings = map;
555

    
556
   }
557

    
558

    
559
   private static void loadResources() {
560
       final Class[] sPanelClass = GUIResources.getParameterPanelClasses();
561
       for (final Class element : sPanelClass) {
562
          try {
563
             final Class panelClass = element;
564
             final String sAlgClassName = element.getName().substring(0, element.getName().indexOf("ParametersPanel")) + "Algorithm";
565
             final Class algClass = panelClass.getClassLoader().loadClass(sAlgClassName);
566
             final GeoAlgorithm alg = (GeoAlgorithm) algClass.newInstance();
567
             m_ParametersPanel.put(alg.getCommandLineName(), panelClass);
568
          }
569
          catch (final Exception e) {/*ignore it if there are problems*/
570
          }
571
       }
572

    
573
       final Class[] sModelerPanelClass = GUIResources.getModelerParameterPanelClasses();
574
       for (final Class element : sModelerPanelClass) {
575
          try {
576
             final Class panelClass = element;
577
             final String sAlgClassName = element.getName().substring(0, element.getName().indexOf("ModelerParametersPanel")) + "Algorithm";
578
             final Class algClass = panelClass.getClassLoader().loadClass(sAlgClassName);
579
             final GeoAlgorithm alg = (GeoAlgorithm) algClass.newInstance();
580
             m_ModelerParametersPanel.put(alg.getCommandLineName(), panelClass);
581
          }
582
          catch (final Exception e) {/*ignore it if there are problems*/
583
          }
584
       }
585
   }
586

    
587

    
588
   /**
589
    * Returns the path to help files
590
    *
591
    * @return the path to help files
592
    */
593
   public static String getHelpPath() {
594

    
595
      return getSextanteInstallPath() + File.separator + "help";
596

    
597
   }
598

    
599

    
600
   /**
601
    * Sets the current path to sextante folder. This is the folder where help files and additional software should be located.
602
    * This should be done before initializing this class, since this folder is used by some algorithm providers
603
    *
604
    * @param sPath
605
    *                the path to sextante help and additional programs
606
    * @deprecated Use {@link #setSextanteInstallPath(String)} or {@link #setSextanteHomePath(String)}
607
    */
608
   public static void setSextantePath(final String sPath) {
609

    
610
      m_sSextanteInstallPath = sPath;
611

    
612
   }
613

    
614

    
615
   /**
616
    * Returns the path to sextante help and additional programs
617
    *
618
    * @return the path to sextante help and additional programs
619
        *
620
    * @deprecated Use {@link #getSextanteInstallPath()} or {@link #getSextanteHomePath()}
621
    */
622
   public static String getSextantePath() {
623

    
624
      return m_sSextanteInstallPath;
625

    
626
   }
627

    
628
   public static String getSextanteHomePath() {
629
           return m_sSextanteHomePath;
630
   }
631

    
632
   public static String getSextanteInstallPath() {
633
           return m_sSextanteInstallPath;
634
   }
635

    
636
   public static void setSextanteHomePath(String path) {
637
           m_sSextanteHomePath = path;
638

    
639
   }
640

    
641
   public static void setSextanteInstallPath(String path) {
642
           m_sSextanteInstallPath = path;
643

    
644
   }
645

    
646

    
647

    
648
   /**
649
    * Returns the default folder for output data.
650
    *
651
    * @return the default folder for output data.
652
    */
653
   public static String getOutputFolder() {
654

    
655
      if ((m_sOutputFolder == null) || m_sOutputFolder.trim().equals("")) {
656
         return System.getProperty("user.home");
657
      }
658
      else {
659
         return m_sOutputFolder;
660
      }
661

    
662
   }
663

    
664

    
665
   /**
666
    * Returns the default value to represent "No Data" (null) raster cells.
667
    *
668
    * @return the current "No Data" value.
669
    */
670
   private static Double getDefaultNoDataValue() {
671

    
672
      try {
673
         final double dNoDataValue = Double.parseDouble(SextanteGUI.getSettingParameterValue(SextanteGeneralSettings.DEFAULT_NO_DATA_VALUE));
674
         return dNoDataValue;
675
      }
676
      catch (final Exception e) {
677
         return new Double(-99999d);
678
      }
679

    
680
   }
681

    
682

    
683
   /**
684
    * Loads configuration parameters from the config file
685
    */
686
   private static void readConfigFile() {
687

    
688
      BufferedReader input = null;
689
      try {
690
         input = new BufferedReader(new FileReader(getConfigFile()));
691
         String sLine = null;
692
         while ((sLine = input.readLine()) != null) {
693
            final String[] sTokens = sLine.split("=");
694
            if (sTokens.length == 2) {
695
               m_Settings.put(sTokens[0], sTokens[1]);
696
            }
697
         }
698
      }
699
      catch (final FileNotFoundException e) {
700
      }
701
      catch (final IOException e) {
702
      }
703
      finally {
704
         try {
705
            if (input != null) {
706
               input.close();
707
            }
708
         }
709
         catch (final IOException e) {
710
            Sextante.addErrorToLog(e);
711
         }
712
      }
713

    
714
   }
715

    
716

    
717
   /**
718
    * Saves current settings to the config file
719
    */
720
   public static void saveSettings() {
721

    
722
      Writer output = null;
723
      try {
724
         output = new BufferedWriter(new FileWriter(getConfigFile()));
725
         final Set<String> set = m_Settings.keySet();
726
         final Iterator<String> iter = set.iterator();
727
         while (iter.hasNext()) {
728
            final String sKey = iter.next();
729
            final String sValue = m_Settings.get(sKey);
730
            output.write(sKey + "=" + sValue + "\n");
731
         }
732
      }
733
      catch (final IOException e) {
734
         Sextante.addErrorToLog(e);
735
      }
736
      finally {
737
         if (output != null) {
738
            try {
739
               output.close();
740
            }
741
            catch (final IOException e) {
742
               Sextante.addErrorToLog(e);
743
            }
744
         }
745
      }
746

    
747
   }
748

    
749

    
750
   /**
751
    * Returns the path to the SEXTANTE config file.
752
    *
753
    * @return A string with the full the path and name of the SEXTANTE config file.
754
    */
755
   private static String getConfigFile() {
756

    
757
      final String sPath = getUserFolder();
758

    
759
      return sPath + File.separator + "sextante.settings";
760

    
761
   }
762

    
763

    
764
   /**
765
    * Returns the folder in which the SEXTANTE config file is stored.
766
    * By default, this is the folder "sextante" in the user's home folder.
767
    * But it is also possible to set a different folder through the
768
    * Java property "SEXTANTE.confDir" when launching the VM:
769
    *
770
    *   java -DSEXTANTE.confDir=<path>
771
    *
772
    * @return A string with the full path and name of the config folder.
773
    */
774
   public static String getUserFolder() {
775

    
776
      String sPath;
777
      String sConfDir;
778

    
779

    
780
      // default is to use system's home folder setting
781
//      sPath = System.getProperty("user.home") + File.separator + "sextante";
782
      sPath = SextanteGUI.getSextanteHomePath();
783
      // check if SEXTANTE.confDir has been set
784
      sConfDir = System.getProperty("SEXTANTE.confDir");
785
      if ( sConfDir != null ) {
786
              sConfDir = sConfDir.trim();
787
                      if ( sConfDir.length() > 0 ) {
788
                              // check if we have to append a separator char
789
                              if ( sConfDir.endsWith(File.separator) ) {
790
                                      sPath = sConfDir;
791
                              } else {
792
                                      sPath = sConfDir + File.separator;
793
                                }
794
                        }
795
      }
796

    
797
      final File sextanteFolder = new File(sPath);
798
      if (!sextanteFolder.exists()) {
799
              sextanteFolder.mkdir();
800
      }
801
      return sPath;
802

    
803
   }
804

    
805

    
806
   /**
807
    * Returns the type of the last element from which a command-line command was executed
808
    *
809
    * @return the type of the element from which a command-line command was executed. SextanteGUI.HISTORY if the last component
810
    *         was the history panel; SextanteGUI.COMMANDLINE if it was the regular SEXTANTE console
811
    */
812
   public static int getLastCommandOrigin() {
813

    
814
      return m_iLastCommandOrigin;
815

    
816
   }
817

    
818

    
819
   /**
820
    * Sets the type of the last element from which a command-line command was executed. This has to be called from any component
821
    * that allows execution of commands
822
    *
823
    * @param iLast
824
    *                one of the following constants: SextanteGUI.HISTORY if the last component was the history panel;
825
    *                SextanteGUI.COMMANDLINE if it was the regular SEXTANTE console
826
    */
827
   public static void setLastCommandOrigin(final int iLast) {
828

    
829
      m_iLastCommandOrigin = iLast;
830

    
831
   }
832

    
833

    
834
   /**
835
    * Gets the dialog from which the last command--line command was executed. This will be used as the parent dialog for task
836
    * monitors or message dialogs generated by the execution of that command.
837
    *
838
    * @return the dialog from which the last command--line command was executed
839
    */
840
   public static JDialog getLastCommandOriginParentDialog() {
841

    
842
      return m_LastCommandOriginParentPanel;
843

    
844
   }
845

    
846

    
847
   /**
848
    * Sets the dialog (if any) that contains the element from which the last command--line command was executed
849
    *
850
    * @param parent
851
    *                the dialog (if any) that contains the element from which the last command--line command was executed
852
    */
853
   public static void setLastCommandOriginParentDialog(final JDialog parent) {
854

    
855
      m_LastCommandOriginParentPanel = parent;
856

    
857
   }
858

    
859

    
860
   /**
861
    * Returns true if only active algorithms (those that can be executed with the current data objects) should be shown in the
862
    * toolbox
863
    *
864
    * @return true if only active algorithms (those that can be executed with the current data objects) should be shown in the
865
    *         toolbox
866
    */
867
   public static boolean getShowOnlyActiveAlgorithms() {
868

    
869
      return m_bShowOnlyActiveAlgorithms;
870

    
871
   }
872

    
873

    
874
   /**
875
    * Sets whether only active algorithms (those that can be executed with the current data objects) should be shown in the
876
    * toolbox
877
    *
878
    * @param showOnlyActiveAlgorithms
879
    *                must be true if only active algorithms (those that can be executed with the current data objects) should be
880
    *                shown in the toolbox
881
    */
882
   public static void setShowOnlyActiveAlgorithms(final boolean showOnlyActiveAlgorithms) {
883

    
884
      m_bShowOnlyActiveAlgorithms = showOnlyActiveAlgorithms;
885

    
886
   }
887

    
888

    
889
   /**
890
    * puts a collection of settings into the settings map
891
    *
892
    * @param settings
893
    *                the map with settings values.
894
    */
895
   public static void setSettings(final HashMap<String, String> settings) {
896

    
897
      m_Settings.putAll(settings);
898

    
899
   }
900

    
901

    
902
   /**
903
    * Modifies the passed string, so it can be used as a safe data object name (without special characters)
904
    *
905
    * @param sName
906
    *                the name to modify
907
    * @return the modified safe name (with no special characters)
908
    */
909
   public static String modifyResultName(String sName) {
910

    
911
      sName = sName.replaceAll("\\.", "_");
912
      sName = sName.replaceAll(" ", "_");
913
      sName = sName.replaceAll("\\[", "_");
914
      sName = sName.replaceAll("\\]", "_");
915
      sName = sName.replaceAll("\\(", "_");
916
      sName = sName.replaceAll("\\)", "_");
917
      sName = sName.replaceAll("á", "a");
918
      sName = sName.replaceAll("é", "e");
919
      sName = sName.replaceAll("í", "i");
920
      sName = sName.replaceAll("ó", "o");
921
      sName = sName.replaceAll("ú", "u");
922
      sName = sName.replaceAll("ñ", "n");
923

    
924
      return sName;
925

    
926
   }
927

    
928

    
929
   private static void addCustomParametersPanel(final HashMap<String, Class> map) {
930

    
931
      m_ParametersPanel.putAll(map);
932

    
933
   }
934

    
935

    
936
   private static void addCustomModelerParametersPanel(final HashMap<String, Class> map) {
937

    
938
      m_ModelerParametersPanel.putAll(map);
939

    
940
   }
941

    
942

    
943
   public static Class getModelerParametersPanel(final String sName) {
944

    
945
      return m_ModelerParametersPanel.get(sName);
946

    
947
   }
948

    
949

    
950
   public static Class getParametersPanel(final String sName) {
951

    
952
      return m_ParametersPanel.get(sName);
953

    
954
   }
955

    
956

    
957
   public static ImageIcon getAlgorithmIcon(final GeoAlgorithm alg) {
958

    
959
      final String sName = Sextante.getAlgorithmProviderName(alg);
960
      for (int i = 0; i < m_AlgorithmProviders.size(); i++) {
961
         if (m_AlgorithmProviders.get(i).getName().equals(sName)) {
962
            return m_AlgorithmProviders.get(i).getIcon();
963
         }
964
      }
965
      return SEXTANTE_ICON;
966

    
967
   }
968

    
969

    
970
   public static ArrayList<IAlgorithmProvider> getAlgorithmProviders() {
971

    
972
      return m_AlgorithmProviders;
973

    
974
   }
975

    
976

    
977
   public static String getSettingParameterValue(final String sParameterName) {
978

    
979
      return m_Settings.get(sParameterName);
980

    
981
   }
982

    
983

    
984
   public static String setSettingParameterValue(final String sParameterName,
985
                                                 final String sValue) {
986

    
987
      return m_Settings.put(sParameterName, sValue);
988

    
989
   }
990

    
991

    
992
   public static void updateAlgorithmProvider(final Class providerClass) {
993

    
994
      for (int i = 0; i < m_AlgorithmProviders.size(); i++) {
995
         final IAlgorithmProvider provider = m_AlgorithmProviders.get(i);
996
         if (providerClass.isInstance(provider)) {
997
            provider.update();
998
            Sextante.addAlgorithmsFromProvider(provider.getName(), provider.getAlgorithms());
999
         }
1000
      }
1001

    
1002
   }
1003

    
1004

    
1005
   public static Object getAlgorithmHelp(final GeoAlgorithm alg) {
1006

    
1007
      try {
1008
        File helpfile = alg.getHelpFile();
1009
        if( helpfile != null ) {
1010
            return HelpIO.getHelpAsHTMLCode(alg, helpfile.getAbsolutePath());
1011
        }
1012
      } catch(Throwable th) {
1013
          // Do nothing
1014
      }
1015
      final String sName = Sextante.getAlgorithmProviderName(alg);
1016
      for (int i = 0; i < m_AlgorithmProviders.size(); i++) {
1017
         if (m_AlgorithmProviders.get(i).getName().equals(sName)) {
1018
            return m_AlgorithmProviders.get(i).getAlgorithmHelp(alg);
1019
         }
1020
      }
1021
      String sFilename;
1022
      String sPath;
1023
      if (sName.equals("SEXTANTE")) {
1024
         sFilename = alg.getCommandLineName() + ".xml";
1025
         sPath = HelpIO.getHelpPath(alg, false);
1026
         return HelpIO.getHelpAsHTMLCode(alg, sPath + File.separator + sFilename);
1027
      }
1028
      else {
1029
         return ""; //TODO:create default help page
1030
      }
1031

    
1032
   }
1033

    
1034

    
1035
   public static String getAlgorithmHelpFilename(final GeoAlgorithm alg,
1036
                                                 final boolean bForceCurrentLocale) {
1037

    
1038
      final String sName = Sextante.getAlgorithmProviderName(alg);
1039
      for (int i = 0; i < m_AlgorithmProviders.size(); i++) {
1040
         if (m_AlgorithmProviders.get(i).getName().equals(sName)) {
1041
            return m_AlgorithmProviders.get(i).getAlgorithmHelpFilename(alg, bForceCurrentLocale);
1042
         }
1043
      }
1044
      String sFilename;
1045
      String sPath;
1046
      if (sName.equals("SEXTANTE")) {
1047
         sFilename = alg.getCommandLineName() + ".xml";
1048
         sPath = HelpIO.getHelpPath(alg, false);
1049
         return sPath + File.separator + sFilename;
1050
      }
1051
      else {
1052
         return ""; //TODO:create default help page
1053
      }
1054

    
1055
   }
1056

    
1057

    
1058
   public static HashMap<NameAndIcon, ArrayList<ToolboxAction>> getToolboxActions() {
1059

    
1060

    
1061
      final HashMap<NameAndIcon, ArrayList<ToolboxAction>> map = new HashMap<NameAndIcon, ArrayList<ToolboxAction>>();
1062
      for (int i = 0; i < m_AlgorithmProviders.size(); i++) {
1063
         final IAlgorithmProvider provider = m_AlgorithmProviders.get(i);
1064
         map.putAll(provider.getToolboxActions());
1065
      }
1066
      map.putAll(SextanteGUI.getGUIFactory().getToolboxActions());
1067
      return map;
1068
   }
1069

    
1070

    
1071
   public static IToolboxRightButtonAction[] getToolboxRightButtonActions() {
1072

    
1073
           final ArrayList<IToolboxRightButtonAction> list = new ArrayList<IToolboxRightButtonAction>();
1074
           for (int i = 0; i < m_AlgorithmProviders.size(); i++) {
1075
                   final IAlgorithmProvider provider = m_AlgorithmProviders.get(i);
1076
                   final IToolboxRightButtonAction[] actions = provider.getToolboxRightButtonActions();
1077
                   for (int j = 0; j < actions.length; j++) {
1078
                           list.add(actions[j]);
1079
                   }
1080
           }
1081
      return list.toArray(new IToolboxRightButtonAction[0]);
1082

    
1083
   }
1084

    
1085

    
1086
   /**
1087
    * Returns the renderer to use for layers created by SEXTANTE algorithms
1088
    *
1089
    */
1090
   public static IDataRenderer getDataRenderer() {
1091

    
1092
      return m_Renderer;
1093

    
1094
   }
1095

    
1096

    
1097
   public static void setDataRenderer(final IDataRenderer renderer) {
1098

    
1099
      m_Renderer = renderer;
1100

    
1101
   }
1102
}