Statistics
| Revision:

gvsig-scripting / trunk / org.gvsig.scripting / org.gvsig.scripting.swing / org.gvsig.scripting.swing.impl / src / main / java / org / gvsig / scripting / swing / impl / composer / DefaultJScriptingComposer.java @ 185

History | View | Annotate | Download (35.6 KB)

1
package org.gvsig.scripting.swing.impl.composer;
2

    
3
import java.awt.BorderLayout;
4
import java.awt.Dimension;
5
import java.awt.event.ActionEvent;
6
import java.awt.event.ActionListener;
7
import java.io.File;
8
import java.io.OutputStream;
9
import java.util.ArrayList;
10
import java.util.Iterator;
11
import java.util.List;
12

    
13
import javax.script.ScriptException;
14
import javax.swing.JButton;
15
import javax.swing.JEditorPane;
16
import javax.swing.JLabel;
17
import javax.swing.JMenu;
18
import javax.swing.JMenuBar;
19
import javax.swing.JMenuItem;
20
import javax.swing.JOptionPane;
21
import javax.swing.JPanel;
22
import javax.swing.JScrollPane;
23
import javax.swing.JSplitPane;
24
import javax.swing.JTabbedPane;
25
import javax.swing.JTable;
26
import javax.swing.JTextArea;
27
import javax.swing.JToolBar;
28
import javax.swing.ListSelectionModel;
29
import javax.swing.SwingConstants;
30
import javax.swing.event.ChangeEvent;
31
import javax.swing.event.ChangeListener;
32
import javax.swing.event.ListSelectionEvent;
33
import javax.swing.event.ListSelectionListener;
34
import javax.swing.table.DefaultTableModel;
35

    
36
import org.gvsig.scripting.ScriptingBaseScript;
37
import org.gvsig.scripting.ScriptingDialog;
38
import org.gvsig.scripting.ScriptingFolder;
39
import org.gvsig.scripting.ScriptingManager;
40
import org.gvsig.scripting.ScriptingNotification;
41
import org.gvsig.scripting.ScriptingScript;
42
import org.gvsig.scripting.ScriptingUnit;
43
import org.gvsig.scripting.swing.api.JEditor;
44
import org.gvsig.scripting.swing.api.JCodeEditor;
45
import org.gvsig.scripting.swing.api.JScriptingBrowser;
46
import org.gvsig.scripting.swing.api.JScriptingComposer;
47
import org.gvsig.scripting.swing.api.ScriptingUIManager;
48
import org.gvsig.scripting.swing.impl.DefaultJScriptingBrowser;
49
import org.gvsig.scripting.swing.impl.DefaultJScriptingLauncher;
50
import org.gvsig.scripting.swing.impl.JDialogContent;
51
import org.gvsig.scripting.swing.impl.DefaultJScriptingLauncher.LauncherActionEvent;
52
import org.gvsig.scripting.swing.impl.composer.DefaultJCodeEditor.EditorActionEvent;
53
import org.gvsig.tools.observer.Observable;
54
import org.gvsig.tools.observer.Observer;
55

    
56

    
57
public class DefaultJScriptingComposer extends JScriptingComposer implements Observer, ActionListener{
58

    
59
        /**
60
         * 
61
         */
62
        private static final long serialVersionUID = 1L;
63

    
64
        public static final int CLOSE_ACTION = 1;
65
        public List<JEditor> unitsEditor;
66

    
67
        /* Generales */ 
68
        ScriptingUIManager uimanager;
69
        ScriptingManager manager;
70
        ClassLoader loader;
71

    
72
        /* Ventana inicial y componentes*/
73
        JSplitPane mainPane;
74
        JSplitPane editionPane;
75
        JTabbedPane problemsPane;
76
        JTabbedPane scriptEditors;
77
        JMenuBar menuBar;
78
        JToolBar file;
79
        JToolBar edit;
80
        JToolBar script;
81
        JToolBar help;
82
        JPanel statusBar;
83
        JLabel currentLine;
84
        JLabel statusBarMessage;
85
        JTextArea problems;
86
        JTextArea console;
87
        DefaultJScriptingLauncher launcher;
88
        JToolBar launcherButtons;
89

    
90
        /* JFrame para la creación de nuevos ScriptingBaseScripts o modificación de atributos */
91
        //JFrame NewUnitFrame; 
92

    
93
        /* Para el mantenimiento de la tabla de problemas en el código*/
94
        Object[][] tableData; 
95
        JTable table;
96
        DefaultTableModel tableModel;
97
        protected ActionListener defaultActionlistener = null;
98

    
99
        /**
100
         * Instanciación de un JComposer con todos sus elementos y acciones
101
         * @param manager
102
         */
103
        public DefaultJScriptingComposer(final ScriptingUIManager uimanager) {
104
                loader = this.getClass().getClassLoader();
105
                this.uimanager = uimanager;
106
                this.manager = uimanager.getManager();
107

    
108
                unitsEditor = new ArrayList<JEditor>();
109

    
110
                // Barra de menú
111
                menuBar = new JMenuBar();
112

    
113
                // Construimos los componentes del menú
114
                JMenu menu_file = new JMenu("File");
115
                JMenuItem menuItem_new = new JMenuItem("New",uimanager.getIcon("document-new"));
116
                menuItem_new.addActionListener(new ActionListener(){
117
                        public void actionPerformed(ActionEvent e) {
118
                                try {
119
                                        newScriptingBaseScript();
120
                                } catch (Exception e1) {
121
                                        // TODO Auto-generated catch block
122
                                        e1.printStackTrace();
123
                                }
124
                        }
125
                });
126
                menu_file.add(menuItem_new);
127
                menu_file.addSeparator();
128
                JMenuItem menuItem_close = new JMenuItem("Close document",uimanager.getIcon("emblem-unreadable"));
129
                menuItem_close.addActionListener(new ActionListener(){
130
                        public void actionPerformed(ActionEvent e) {
131
                                closeScriptingBaseScript();
132
                        }
133
                });
134
                menu_file.add(menuItem_close);
135
                JMenuItem menuItem_closeAll = new JMenuItem("Close all documents",uimanager.getIcon("emblem-unreadable"));
136
                menuItem_closeAll.addActionListener(new ActionListener(){
137
                        public void actionPerformed(ActionEvent e) {
138
                                closeAllScriptingBaseScript();
139
                        }
140
                });
141
                menu_file.add(menuItem_closeAll);
142
                menu_file.addSeparator();
143
                JMenuItem menuItem_run = new JMenuItem("Run",uimanager.getIcon("applications-system"));
144
                menuItem_run.addActionListener(new ActionListener(){
145
                        public void actionPerformed(ActionEvent e) {
146
                                runScriptingBaseScript();
147
                        }
148
                });
149
                menu_file.add(menuItem_run);
150
                menu_file.addSeparator();
151
                JMenuItem menuItem_save = new JMenuItem("Save",uimanager.getIcon("media-floppy"));
152
                menuItem_save.addActionListener(new ActionListener(){
153
                        public void actionPerformed(ActionEvent e) {
154
                                saveScriptingBaseScript();
155
                        }
156
                });
157
                menu_file.add(menuItem_save);
158
                menu_file.addSeparator();
159
                JMenuItem menuItem_exit = new JMenuItem("Close",uimanager.getIcon("system-log-out"));
160
                menuItem_exit.addActionListener(new ActionListener(){
161
                        public void actionPerformed(ActionEvent e) {
162
                                closeAllScriptingBaseScript();
163
                                if(defaultActionlistener!=null){
164
                                        ActionEvent event = new ActionEvent(this,CLOSE_ACTION,"close");
165
                                        defaultActionlistener.actionPerformed(event);
166
                                }
167
                        
168
                        }
169
                });
170
                menu_file.add(menuItem_exit);
171

    
172
                JMenu menu_edit = new JMenu("Edit");
173
                JMenuItem menuItem_cut = new JMenuItem("cut",uimanager.getIcon("edit-cut"));
174
                menuItem_cut.addActionListener(new ActionListener(){
175
                        public void actionPerformed(ActionEvent e) {
176
                                cutScriptingBaseScript();
177
                        }
178
                });
179
                menu_edit.add(menuItem_cut);
180
                JMenuItem menuItem_copy = new JMenuItem("copy",uimanager.getIcon("edit-copy"));
181
                menuItem_copy.addActionListener(new ActionListener(){
182
                        public void actionPerformed(ActionEvent e) {
183
                                copyScriptingBaseScript();
184
                        }
185
                });
186
                menu_edit.add(menuItem_copy);
187
                JMenuItem menuItem_paste = new JMenuItem("paste",uimanager.getIcon("edit-paste"));
188
                menuItem_paste.addActionListener(new ActionListener(){
189
                        public void actionPerformed(ActionEvent e) {
190
                                pasteScriptingBaseScript();
191
                        }
192
                });
193
                menu_edit.add(menuItem_paste);
194
                menu_edit.addSeparator();
195
                JMenuItem menuItem_selectAll = new JMenuItem("select all",uimanager.getIcon("edit-select-all"));
196
                menuItem_selectAll.addActionListener(new ActionListener(){
197
                        public void actionPerformed(ActionEvent e) {
198
                                selectAllScriptingBaseScript();
199
                        }
200
                });
201
                menu_edit.add(menuItem_selectAll);
202

    
203
                JMenu menu_tools = new JMenu("Tools");
204
                JMenuItem menuItem_launcher = new JMenuItem("Launcher");
205
                menuItem_launcher.addActionListener(new ActionListener(){
206
                        public void actionPerformed(ActionEvent e) {
207
                                uimanager.showWindow(uimanager.createLauncher(), "Scripting Launcher");
208
                        }
209
                });
210
                menu_tools.add(menuItem_launcher);
211
                
212

    
213
                JMenu menu_help = new JMenu("Help");
214
                JMenuItem menuItem_import = new JMenuItem("Import JavaDoc",uimanager.getIcon("list-add"));
215
                menuItem_import.addActionListener(new ActionListener(){
216
                        public void actionPerformed(ActionEvent e) {
217
                                getImportHelpDialog();
218
                        }
219
                });
220
                menu_help.add(menuItem_import);
221
                JMenuItem menuItem_remove = new JMenuItem("Remove JavaDoc",uimanager.getIcon("list-remove"));
222
                menuItem_remove.addActionListener(new ActionListener(){
223
                        public void actionPerformed(ActionEvent e) {
224
                                try {
225
                                        getRemoveHelpDialog();
226
                                } catch (Exception e1) {
227
                                        // TODO Auto-generated catch block
228
                                        e1.printStackTrace();
229
                                }
230
                        }
231
                });
232
                menu_help.add(menuItem_remove);
233
                JMenuItem menuItem_show = new JMenuItem("Show JavaDoc",uimanager.getIcon("help-browser"));
234
                menuItem_show.addActionListener(new ActionListener(){
235
                        public void actionPerformed(ActionEvent e) {
236
                                uimanager.showWindow(uimanager.getAPIHelp(),"JavaDoc");
237
                        }
238
                });
239
                menu_help.add(menuItem_show);
240
                menu_help.addSeparator();
241
                JMenuItem menuItem_about = new JMenuItem("About us",uimanager.getIcon("system-users"));
242
                menuItem_about.addActionListener(new ActionListener(){
243
                        public void actionPerformed(ActionEvent e) {
244
                                getAboutUsDialog();
245
                        }
246
                });
247
                menu_help.add(menuItem_about);
248
                JMenuItem menuItem_help = new JMenuItem("Get help",uimanager.getIcon("help-browser"));
249
                menuItem_help.addActionListener(new ActionListener(){
250
                        public void actionPerformed(ActionEvent e) {
251
                                uimanager.showWindow(uimanager.getUserHelp(),"Scripting Framework Help");
252
                        }
253
                });
254
                menu_help.add(menuItem_help);
255

    
256
                menuBar.add(menu_file);
257
                menuBar.add(menu_edit);
258
                menuBar.add(menu_tools);
259
                menuBar.add(menu_help);
260

    
261
                // Botones de acción
262
                file = new JToolBar();
263
                help = new JToolBar();
264
                edit = new JToolBar();
265
                script = new JToolBar();
266
                setDefaultButtons();
267
                JPanel scriptButtonsPane = new JPanel(new BorderLayout());
268
                scriptButtonsPane.add(edit,BorderLayout.WEST);
269
                scriptButtonsPane.add(script,BorderLayout.CENTER);
270
                JPanel buttonsPane = new JPanel(new BorderLayout());
271
                buttonsPane.add(file, BorderLayout.WEST);
272
                buttonsPane.add(help, BorderLayout.EAST);
273
                buttonsPane.add(scriptButtonsPane, BorderLayout.CENTER);
274

    
275
                // Panel de selección de proyecto
276
                JPanel launcherPane = new JPanel(new BorderLayout());
277
                launcher = (DefaultJScriptingLauncher)uimanager.createLauncher();
278
                launcher.addDefaultActionListener(this);
279
                launcher.setPreferredSize(new Dimension(200, 450));
280
                launcherButtons = new JToolBar(SwingConstants.VERTICAL);
281
                setLauncherPaneButtons();
282

    
283
                launcherPane.add(launcher,BorderLayout.CENTER);
284
                launcherPane.add(launcherButtons,BorderLayout.WEST);
285

    
286

    
287
                // Panel de Edición
288
                scriptEditors = new JTabbedPane();
289
                scriptEditors.addChangeListener(new ChangeListener(){
290
                        public void stateChanged(ChangeEvent arg0) {
291
                                JPanel editor = (JPanel)scriptEditors.getSelectedComponent();
292
                                if(scriptEditors.getSelectedIndex()==-1)
293
                                        setDefaultButtons();
294
                                else if(editor instanceof DefaultJDialogEditor)
295
                                        setDialogButtons();
296
                                else if(editor instanceof DefaultJCodeEditor)
297
                                        setScriptButtons();
298
                        }
299
                });
300
                scriptEditors.setPreferredSize(new Dimension(500, 350));
301
                problemsPane = new JTabbedPane();
302

    
303
                tableData = null;
304
                tableModel = new AbstractTableModel();
305
                tableModel.addColumn("Description");
306
                tableModel.addColumn("Resource");
307
                tableModel.addColumn("Location");
308
                table = new JTable(tableModel);
309
                table.getColumnModel().getColumn(0).setPreferredWidth(300);
310
                //table.setFont(new Font("Serif",Font.PLAIN,13));
311
                
312
                table.getSelectionModel().addListSelectionListener(new RowListener());
313
                table.setRowSelectionAllowed(true);
314
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
315
                
316
                JScrollPane scrollProblems = new JScrollPane(table);        
317
                scrollProblems.setAutoscrolls(true);
318

    
319
                console = new JTextArea();
320
                /* Descomentarizar cuando se quiera redirigir la salida estándar
321
                 * a la consola de la aplicación*/ 
322
                
323
                /*JTextAreaOutputStream outputConsole = new JTextAreaOutputStream(console);   
324
            outputConsole.ta.setFont(new Font("Serif",Font.PLAIN,13));
325
            System.setOut(new PrintStream(outputConsole));         
326
            System.setErr(new PrintStream(outputConsole));*/
327

    
328
                JScrollPane scrollConsole = new JScrollPane(console);
329
                problemsPane.add("Problems", scrollProblems);
330
                problemsPane.add("Console", scrollConsole);
331
                problemsPane.setPreferredSize(new Dimension(450, 100));
332
                problemsPane.setSelectedIndex(1);
333

    
334
                /* Si no se desea cargar datos para que arranque con ellos,
335
                 * este if nunca será cierto */
336
                if(!unitsEditor.isEmpty()){;
337
                Iterator it = unitsEditor.iterator();
338
                while(it.hasNext()){
339
                        JEditor editor = (JEditor) it.next();
340
                        editor.addDefaultActionListener(this);
341
                        scriptEditors.addTab(editor.getScript().getName(), editor);
342
                }
343
                }
344
                editionPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,scriptEditors,problemsPane);
345
                editionPane.setOneTouchExpandable(true);
346

    
347
                mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,launcherPane, editionPane);
348
                mainPane.setOneTouchExpandable(true);
349

    
350
                // Barra de estado
351
                statusBar = new JPanel(new BorderLayout());
352
                statusBarMessage = new JLabel();
353
                statusBarMessage.setText("Welcome to ScriptingFramework v1.0");
354
                currentLine = new JLabel();
355
                currentLine.setText("Line 0:0");
356

    
357
                statusBar.add(statusBarMessage,BorderLayout.WEST);
358
                statusBar.add(currentLine,BorderLayout.EAST);
359
                
360
                // Integracíón en el frame principal de todos los componentes
361
                JPanel buttons = new JPanel();
362
                buttons.setLayout( new BorderLayout() );
363
                buttons.add(BorderLayout.NORTH, menuBar);
364
                buttons.add(BorderLayout.SOUTH, buttonsPane);
365
                
366
                this.setLayout(new BorderLayout());
367
                this.add(BorderLayout.NORTH, buttons);
368
                this.add(BorderLayout.CENTER, mainPane);
369
                this.add(BorderLayout.SOUTH, statusBar);
370
                this.setPreferredSize(new Dimension(800,600));
371
        }
372

    
373
        private class AbstractTableModel extends DefaultTableModel {
374

    
375
           /**
376
                 * 
377
                 */
378
                private static final long serialVersionUID = -5314938428821653641L;
379

    
380
        public boolean isCellEditable(int row, int col){
381
                   return false;
382
           }
383
        }
384

    
385
        
386
    private class RowListener implements ListSelectionListener {
387
        public void valueChanged(ListSelectionEvent event) {
388
            if (event.getValueIsAdjusting()) {
389
                return;
390
            }
391
            if(!table.getSelectionModel().isSelectionEmpty()){
392
                    String[] line = ((String)table.getValueAt(table.getSelectionModel().getLeadSelectionIndex(), 2)).split(":");
393
                    int row = 0;
394
                    if(line.length>2)
395
                            row = Integer.parseInt(line[1].trim());
396
                    setEditorSelection(((String)table.getValueAt(table.getSelectionModel().getLeadSelectionIndex(), 1)), row);
397
            }
398
        }
399
    }
400
        
401
    private void setEditorSelection(String name, int line){
402
            for (int i=0; i<scriptEditors.getTabCount(); i++){
403
                    
404
                    if(((JEditor)scriptEditors.getComponent(i)).getScript().getId().equals(name)){
405
                            scriptEditors.setSelectedIndex(i);
406
                            
407
                            JEditorPane editor = ((JCodeEditor)scriptEditors.getComponent(i)).getJEditorPanel();
408
                            editor.requestFocusInWindow();
409
                            
410
                            String code = editor.getText();
411
                            int lineCounter = 0;
412
                            int initialSelection = 0;
413
                            int finalSelection = 0;
414
                            for(int j=0; j<code.length(); j++){
415
                                    if (code.charAt(j) == '\n'){
416
                                            lineCounter++;
417
                                            if(lineCounter == line-1){
418
                                                    initialSelection = j;
419
                                            }
420
                                            if(lineCounter == line || (finalSelection==0 && j==code.length()-1)){
421
                                                    finalSelection = j;
422
                                            }
423
                                    }
424
                            }
425
                            
426
                            editor.select(initialSelection,finalSelection);   
427
                    }
428
            }
429
    }
430
    
431
        public void addDefaultActionListener(ActionListener actionlistener) {
432
                this.defaultActionlistener = actionlistener;  
433
        }
434
        
435
        /**
436
         * Función para obtener el elemento seleccionado del Launcher
437
         * @return Selected ScriptingUnit on the tree 
438
         */
439
        private ScriptingUnit getLauncherSelectedNode(){
440
                JTabbedPane tabbed = launcher.getTabbedPane();
441
                DefaultJScriptingBrowser browser = (DefaultJScriptingBrowser)tabbed.getSelectedComponent();
442
                ScriptingUnit unit = browser.getSelectedNode();
443
                return unit;
444
        }
445

    
446
        /**
447
         * Lanza el modo edición de un ScriptingBaseScript
448
         * @param unit
449
         */        
450
        private void editSelectedNode(ScriptingUnit unit){
451
                if(unit instanceof ScriptingBaseScript){
452
                        editUnit((ScriptingBaseScript)unit);
453
                }
454
        }
455

    
456
        /**
457
         * Lanza la ejecución de un ScriptingBaseScript
458
         * @param unit
459
         */
460
        private void runSelectedNode(ScriptingUnit unit){
461
                if(unit instanceof ScriptingBaseScript){
462
                        ((ScriptingBaseScript)unit).run();
463
                }
464
        }
465

    
466
        /**
467
         * Funciones para obtener las botoneras en función del tipo de ScriptingBaseScript
468
         * que se esté mostrando en ese momento. Está la estándar 'getDefaultButtons()' para
469
         * cuando no hay ninguno, 'getScriptButtons()' con los botones característicos para
470
         * el manejo de ScriptingScripts y 'getDialogButtons()' para los ScriptingDialogs.
471
         * También se incluye 'getEditButtons()' con las funciones sobre la edición de texto
472
         * como copiar, cortar y pegar.
473
         *
474
         */
475
        private void setDefaultButtons(){
476
                file.removeAll();
477
                edit.removeAll();
478
                script.removeAll();
479
                help.removeAll();
480
                JButton newb = new JButton(uimanager.getIcon("document-new"));
481
                newb.setToolTipText("New");
482
                newb.addActionListener(new ActionListener(){
483
                        public void actionPerformed(ActionEvent e) {
484
                                try {
485
                                        newScriptingBaseScript();
486
                                } catch (Exception e1) {
487
                                        // TODO Auto-generated catch block
488
                                        e1.printStackTrace();
489
                                }
490
                        }
491
                });
492
                file.add(newb);
493
                file.repaint();
494

    
495
                help.removeAll();
496
                JButton helpb = new JButton(uimanager.getIcon("help-browser"));
497
                helpb.setToolTipText("Help");
498
                helpb.addActionListener(new ActionListener(){
499
                        public void actionPerformed(ActionEvent e) {
500
                                uimanager.showWindow(uimanager.getAPIHelp(),"JavaDoc");
501
                        }
502
                });
503
                help.add(helpb);
504
                help.repaint();
505
                edit.setVisible(false);
506
                script.setVisible(false);
507
        }
508

    
509
        private void setScriptButtons(){
510
                file.removeAll();
511
                edit.removeAll();
512
                script.removeAll();
513
                setDefaultButtons();
514

    
515
                edit.setVisible(true);
516
                script.setVisible(true);
517
                setEditButtons();
518
                JButton close = new JButton(uimanager.getIcon("emblem-unreadable"));
519
                close.setToolTipText("Close current tab");
520
                close.addActionListener(new ActionListener(){
521
                        public void actionPerformed(ActionEvent e) {
522
                                closeScriptingBaseScript();
523
                        }
524
                });
525
                file.add(close);
526
                JButton save = new JButton(uimanager.getIcon("media-floppy"));
527
                save.setToolTipText("Save");
528
                save.addActionListener(new ActionListener(){
529
                        public void actionPerformed(ActionEvent e) {
530
                                saveScriptingBaseScript();
531
                        }
532
                });
533
                file.add(save);
534
                file.repaint();
535

    
536
                JButton run = new JButton(uimanager.getIcon("applications-system"));
537
                run.setToolTipText("Run");
538
                run.addActionListener(new ActionListener(){
539
                        public void actionPerformed(ActionEvent e) {
540
                                runScriptingBaseScript();
541
                        }
542
                });
543
                script.add(run);
544
                script.repaint();
545
        }
546

    
547
        private void setDialogButtons(){
548
                script.removeAll();
549
                setScriptButtons();
550
                script.addSeparator();
551
                JButton help = new JButton(uimanager.getIcon("help-browser"));
552
                help.setToolTipText("Help");
553
                script.add(help);        
554
                script.repaint();
555
        }
556

    
557
        private void setEditButtons(){
558
                JButton cut = new JButton(uimanager.getIcon("edit-cut"));
559
                cut.setToolTipText("Cut");
560
                cut.addActionListener(new ActionListener(){
561
                        public void actionPerformed(ActionEvent e) {
562
                                cutScriptingBaseScript();
563
                        }
564
                });
565
                edit.add(cut);
566
                JButton copy = new JButton(uimanager.getIcon("edit-copy"));
567
                copy.setToolTipText("Copy");
568
                copy.addActionListener(new ActionListener(){
569
                        public void actionPerformed(ActionEvent e) {
570
                                copyScriptingBaseScript();
571
                        }
572
                });
573
                edit.add(copy);
574
                JButton paste = new JButton(uimanager.getIcon("edit-paste"));
575
                paste.setToolTipText("Paste");
576
                paste.addActionListener(new ActionListener(){
577
                        public void actionPerformed(ActionEvent e) {
578
                                pasteScriptingBaseScript();
579
                        }
580
                });
581
                edit.add(paste);
582
                edit.repaint();
583
        }
584

    
585
        /**
586
         * Botonera con posibles acciones a realizar con el Panel Launcher
587
         *
588
         */
589
        private void setLauncherPaneButtons(){
590

    
591
                JButton newb = new JButton(uimanager.getIcon("document-new"));
592
                newb.setToolTipText("New");
593
                newb.addActionListener(new ActionListener(){
594
                        public void actionPerformed(ActionEvent e) {
595
                                try {
596
                                        newScriptingBaseScript();
597
                                } catch (Exception e1) {
598
                                        // TODO Auto-generated catch block
599
                                        e1.printStackTrace();
600
                                }
601
                        }
602
                });
603
                launcherButtons.add(newb);
604
                JButton edit = new JButton(uimanager.getIcon("applications-accessories"));
605
                edit.setToolTipText("Open edition mode");
606
                edit.addActionListener(new ActionListener(){
607
                        public void actionPerformed(ActionEvent e) {
608
                                editSelectedNode(getLauncherSelectedNode());
609
                        }
610
                });
611
                launcherButtons.add(edit);
612
                JButton run = new JButton(uimanager.getIcon("applications-system"));
613
                run.setToolTipText("Run selected script");
614
                run.addActionListener(new ActionListener(){
615
                        public void actionPerformed(ActionEvent e) {
616
                                runSelectedNode(getLauncherSelectedNode());
617
                        }
618
                });
619
                launcherButtons.add(run);
620
                launcherButtons.addSeparator();
621
                JButton refresh = new JButton(uimanager.getIcon("view-refresh"));
622
                refresh.setToolTipText("Refresh directories");
623
                refresh.addActionListener(new ActionListener(){
624
                        public void actionPerformed(ActionEvent e) {
625
                                launcherRefresh();
626
                        }
627
                });
628
                launcherButtons.add(refresh);
629
                launcherButtons.addSeparator();
630
                JButton rename = new JButton(uimanager.getIcon("preferences-system"));
631
                rename.setToolTipText("Set file properties");
632
                rename.addActionListener(new ActionListener(){
633
                        public void actionPerformed(ActionEvent e) {
634
                                try {
635
                                        renameSelectedNode(getLauncherSelectedNode());
636
                                } catch (Exception e1) {
637
                                        // TODO Auto-generated catch block
638
                                        e1.printStackTrace();
639
                                }
640
                        }
641
                });
642
                launcherButtons.add(rename);
643
                JButton move = new JButton(uimanager.getIcon("format-indent-more"));
644
                move.setToolTipText("Move files");
645
                move.addActionListener(new ActionListener(){
646
                        public void actionPerformed(ActionEvent e){
647
                                try {
648
                                        moveSelectedNode(getLauncherSelectedNode());
649
                                } catch (Exception e1) {
650
                                        // TODO Auto-generated catch block
651
                                        e1.printStackTrace();
652
                                }
653
                        }
654
                });
655
                launcherButtons.add(move);
656
                launcherButtons.addSeparator();
657
                JButton delete = new JButton(uimanager.getIcon("user-trash"));
658
                delete.setToolTipText("Delete selected script");
659
                delete.addActionListener(new ActionListener(){
660
                        public void actionPerformed(ActionEvent e) {
661
                                deleteSelectedNode(getLauncherSelectedNode(),false);
662
                        }
663
                });
664
                launcherButtons.add(delete);
665
        }
666

    
667
        /**
668
         * Función que abre en modo edición un ScriptingBaseScript
669
         * @param unit
670
         */
671
        public void editUnit(ScriptingBaseScript unit){
672
                JEditor panel = null;
673
                if( unit instanceof ScriptingDialog ) {
674
                        panel = new DefaultJDialogEditor(uimanager, (ScriptingDialog) unit);
675
                        if(panel instanceof DefaultJDialogEditor){
676
                                ((DefaultJDialogEditor)panel).addDefaultActionListener(this);
677
                        }
678
                }else if( unit instanceof ScriptingScript ) {
679
                        panel = new DefaultJCodeEditor(uimanager, (ScriptingScript) unit);
680
                        if(panel instanceof DefaultJCodeEditor){
681
                                ((DefaultJCodeEditor)panel).addDefaultActionListener(this);
682
                        }        
683
                }else{
684
                        JOptionPane.showMessageDialog(null, "Can't open editon view from this script type", "Info", JOptionPane.INFORMATION_MESSAGE);
685
                        return ;
686
                }
687
                unitsEditor.add(panel);
688

    
689
                Iterator it = unitsEditor.iterator();
690
                while(it.hasNext()){
691
                        JEditor editor = (JEditor) it.next();
692
                        String title;
693
                        if (editor.getScript().isSaved()){
694
                                title = editor.getScript().getName();
695
                        }else{
696
                                title = "*"+editor.getScript().getName();
697
                        }
698
                        
699
                        scriptEditors.addTab(title, editor);
700
                }
701
                scriptEditors.setSelectedIndex(unitsEditor.size()-1);
702
                editionPane.repaint();
703
                file.repaint();
704
        }
705

    
706

    
707
        /**
708
         * Ventana para creación de nuevos ScriptingBaseScripts
709
         * @throws Exception 
710
         *
711
         */
712
        public void newScriptingBaseScript() throws Exception{
713
                JNewScriptModel model = new JNewScriptModel(manager);
714
                JDialogContent dialog = new JDialogContent(
715
                                uimanager, 
716
                                "document-new",
717
                                "New Script",
718
                                "Create a new Script, Dialog, Project or Folder",
719
                                new JNewScriptPanel(uimanager,model)
720
                );
721
                dialog.showDialog();
722
                if(model.getAction()==JNewScriptModel.ACTION_ACCEPT){
723
                        this.createNewScriptingBaseScript(model);
724
                }
725
        }
726
        
727
        public void createNewScriptingBaseScript(JNewScriptModel model) throws Exception {
728
                model.validate();
729
                ScriptingUnit unit= this.manager.createUnit(
730
                                model.getType(),
731
                                manager.getFolder(new File(model.getPath())),
732
                                model.getName()+model.getExtension()
733
                );
734
                if(unit instanceof ScriptingBaseScript){
735
                        this.editUnit((ScriptingBaseScript) unit);
736
                }
737
                
738
                this.launcherRefresh();
739
        }
740
        
741
        public void getImportHelpDialog(){
742
                new JDialogContent(uimanager, "list-add","Import JavaDoc","Insert JavaDocs from system directories to the ScriptingFramework JavaDoc",new JImportHelp(uimanager,this));
743
        }
744
        
745
        public void getRemoveHelpDialog() throws Exception{
746
                JRemoveHelpModel model = new JRemoveHelpModel(manager);
747
                JDialogContent dialog = new JDialogContent(
748
                                uimanager, 
749
                                "list-remove",
750
                                "Remove JavaDoc",
751
                                "Remove JavaDocs from the ScriptingFramework JavaDoc",
752
                                new JRemoveHelpPanel(uimanager,model));
753
                dialog.showDialog();
754
                if(model.getAction()==JNewScriptModel.ACTION_ACCEPT){
755
                        this.removeHelps(model);
756
                }
757
        }
758
        
759
        public void removeHelps(JRemoveHelpModel model) throws Exception {
760
                model.validate();
761
                Object[] helps = model.getHelps();
762
                for (int i=0;i<helps.length;i++){
763
                        this.manager.getHelpManager().removeHelp(helps[i].toString());
764
                }
765
                //Recargar JavaHelp
766
                this.manager.getHelpManager().reloadHelp();
767
                JOptionPane.showMessageDialog(null, "Deleting JavaDocs successfully", "Info", JOptionPane.INFORMATION_MESSAGE);
768
                uimanager.showWindow(uimanager.getAPIHelp(),"JavaDoc");
769
        }
770
                
771
        public void moveSelectedNode(final ScriptingUnit unit) throws Exception{
772
                if (unit.getParent()==null){
773
                        JOptionPane.showMessageDialog(null, "Please, select first the file to move on the tree directory", "Error", JOptionPane.ERROR_MESSAGE);
774
                }else{
775
                        JMoveScriptModel model = new JMoveScriptModel(manager,unit);
776
                        JDialogContent dialog = new JDialogContent(
777
                                        uimanager, 
778
                                        "format-indent-more", 
779
                                        "Move '"+unit.getName()+ "' script", 
780
                                        "Change the location of the selected script", 
781
                                        new JMoveScriptPanel(uimanager,model)
782
                        );
783
                        dialog.showDialog();
784
                        if(model.getAction()==JMoveScriptModel.ACTION_ACCEPT){
785
                                this.moveScriptingUnitScript(model);
786
                        }
787
                }
788

    
789
        }
790
        
791
        public void moveScriptingUnitScript(JMoveScriptModel model) throws Exception {
792
                model.validate();
793
                ScriptingFolder folderDest = manager.getFolder(new File(model.getMoveTo()));
794
                if(model.getUnit().move(folderDest)){
795
                        JOptionPane.showMessageDialog(null, "File moved succesfully.", "Info", JOptionPane.INFORMATION_MESSAGE);
796
                        this.launcherRefresh();
797
                }else{
798
                        JOptionPane.showMessageDialog(null, "Unexpected error moving the file", "Error", JOptionPane.ERROR_MESSAGE);
799
                }
800
        }
801

    
802
        public void renameSelectedNode(final ScriptingUnit unit) throws Exception{
803
                if (unit.getParent()==null){
804
                        JOptionPane.showMessageDialog(null, "Please, select first the file to move on the tree directory", "Error", JOptionPane.ERROR_MESSAGE);
805
                }else{
806
                        JRenameModel model = new JRenameModel(manager,unit);
807
                        JDialogContent dialog = new JDialogContent(
808
                                        uimanager, 
809
                                        "preferences-system", 
810
                                        "Rename files of '"+unit.getName()+ "' script on the filesystem", 
811
                                        "Change the filenames of the selected script and other properties", 
812
                                        new JRenamePanel(uimanager,model)
813
                        );
814
                        dialog.showDialog();
815
                        if(model.getAction()==JRenameModel.ACTION_ACCEPT){
816
                                this.renameScriptingUnitScript(model);
817
                        }
818
                }
819
        }
820
        
821
        public void renameScriptingUnitScript(JRenameModel model) throws Exception {
822
                model.validate();
823
                ScriptingUnit unit = model.getUnit();
824
                if (!model.getNewName().equals(unit.getId())){
825
                        if(unit.rename(model.getNewName())){
826
                                JOptionPane.showMessageDialog(null, "Rename succesfully", "Info", JOptionPane.INFORMATION_MESSAGE);
827
                                this.launcherRefresh();
828
                        }else{
829
                                JOptionPane.showMessageDialog(null, "Unexpected error renaming the file", "Error", JOptionPane.ERROR_MESSAGE);
830
                        }
831
                        if(unit instanceof ScriptingScript){
832
                                ((ScriptingScript)unit).save();
833
                        }        
834
                }
835
        }
836
        
837
        public void getAboutUsDialog(){
838
                new JDialogContent(uimanager, "system-users","About us","Information about the contributors to gvSIG project",new  JDefaultDialog(uimanager,this,uimanager.getAboutManager().getAboutPanel()));
839
        }
840
        
841

    
842
        public void deleteSelectedNode(final ScriptingUnit unit, boolean isRecursive){
843
                int n = 0;
844
                if(!isRecursive){
845
                n=JOptionPane.showConfirmDialog(
846
                            this.getRootPane(),
847
                            "Are you sure?\nAll the contents will be deleted too.",
848
                            "Delete this Unit and all the contents",
849
                            JOptionPane.YES_NO_OPTION);
850
                }
851
                if (n==0){
852
                        //Si es un folder borramos recursivamente sus subdirectorios
853
                        if(unit instanceof ScriptingFolder){
854
                                List subunits = ((ScriptingFolder)unit).getUnits();
855
                                Iterator it = subunits.iterator();
856
                                while(it.hasNext()){
857
                                        ScriptingUnit subunit = (ScriptingUnit)it.next();
858
                                        deleteSelectedNode(subunit, true);
859
                                }
860
                        }
861
                        // Por último borramos el nodo seleccionado
862
                        unit.getParent().remove(unit);
863
                        launcherRefresh();
864
                        
865
                }
866
        }
867
        
868
        /**
869
         * Función que cierra la pestaña de edición actual
870
         *
871
         */
872
        public void closeScriptingBaseScript(){
873
                if (!unitsEditor.isEmpty()){
874
                        int position = scriptEditors.getSelectedIndex();
875
                        String title = scriptEditors.getTitleAt(position);
876
                        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(position);
877
                        int respuesta=1;
878
                        if(!pestanaEditor.getScript().isSaved()){
879
                                respuesta = JOptionPane.showConfirmDialog(
880
                                            scriptEditors, 
881
                                            "'" + title.substring(1)+"' has been modified. Save changes?",
882
                                            "An Inane Question",
883
                                            JOptionPane.YES_NO_CANCEL_OPTION);
884
                                if(respuesta == 0)
885
                                        saveScriptingBaseScript();
886
                        }
887
                        
888
                        if(respuesta<2){
889
                                pestanaEditor.getScript().setSaved(true);
890
                                scriptEditors.remove(position);
891
                                unitsEditor.remove(position);
892
                                scriptEditors.repaint();
893
                        } 
894
                }
895
        }
896

    
897
        /**
898
         * Función que cierra todas las pestañas de edición abiertas
899
         *
900
         */
901
        public void closeAllScriptingBaseScript(){
902
                boolean exit=false;
903
                while (!unitsEditor.isEmpty() && !exit){
904
                        int action=1;
905
                        int i=0;
906
                        boolean answered=false;
907
                        while(i<scriptEditors.getComponentCount() && !answered){
908
                                JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(i);
909
                                if(!pestanaEditor.getScript().isSaved()){
910
                                        action = JOptionPane.showConfirmDialog(
911
                                                    scriptEditors, 
912
                                                    "Some projects has been modified. Save changes?",
913
                                                    "An Inane Question",
914
                                                    JOptionPane.YES_NO_CANCEL_OPTION);
915
                                        answered=true;
916
                                }
917
                                i++;
918
                        }
919
                        if(action == 0){
920
                                for(i=0;i<scriptEditors.getComponentCount();i++){
921
                                        scriptEditors.setSelectedIndex(i);
922
                                        saveScriptingBaseScript();                        
923
                                }
924
                        } 
925
                        if(action < 2){
926
                                for(i=scriptEditors.getComponentCount()-1;i>=0;i--){
927
                                        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(i);
928
                                        pestanaEditor.getScript().setSaved(true);
929
                                        scriptEditors.setSelectedIndex(i);
930
                                        closeScriptingBaseScript();
931
                                }
932
                        } else{
933
                                exit=true;
934
                        }
935
                        
936
                }
937
        }
938

    
939
        /**
940
         * Función que ejecuta el ScriptingBaseScript de la pestaña actual
941
         *
942
         */
943
        public void runScriptingBaseScript(){
944
                if (!unitsEditor.isEmpty()){
945
                        int pestanaIndex = scriptEditors.getSelectedIndex();
946
                        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
947
                        tableModel.setRowCount(0);
948
                        console.setText("Running '"+ pestanaEditor.getScript().getName() +"'...\n");
949
                        pestanaEditor.getScript().addObserver(this);
950
                        pestanaEditor.getScript().run();
951
                }
952
        }
953

    
954
        /**
955
         * Funciones de 'cortar', 'copiar', 'pegar' y 'seleccionar todo' para los JEditors
956
         * 
957
         */
958
        public void copyScriptingBaseScript(){
959
                if (!unitsEditor.isEmpty()){
960
                        int pestanaIndex = scriptEditors.getSelectedIndex();
961
                        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
962
                        pestanaEditor.getJEditorPanel().copy();
963
                }
964
        }
965

    
966
        public void cutScriptingBaseScript(){
967
                if (!unitsEditor.isEmpty()){
968
                        int pestanaIndex = scriptEditors.getSelectedIndex();
969
                        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
970
                        pestanaEditor.getJEditorPanel().cut();
971
                        JTabbedPane tabs = (JTabbedPane)pestanaEditor.getParent();
972
                        
973
                        String title = tabs.getTitleAt(pestanaIndex);
974
                        if(title.length()>0 && !title.substring(0,1).equals("*")){
975
                                tabs.setTitleAt(tabs.getSelectedIndex(), "*"+title);
976
                                pestanaEditor.getScript().setSaved(false);
977
                        }
978
                }
979
        }
980

    
981
        public void pasteScriptingBaseScript(){
982
                if (!unitsEditor.isEmpty()){
983
                        int pestanaIndex = scriptEditors.getSelectedIndex();
984
                        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
985
                        pestanaEditor.getJEditorPanel().paste();
986
                        JTabbedPane tabs = (JTabbedPane)pestanaEditor.getParent();
987
                        
988
                        String title = tabs.getTitleAt(pestanaIndex);
989
                        if(title.length()>0 && !title.substring(0,1).equals("*")){
990
                                tabs.setTitleAt(tabs.getSelectedIndex(), "*"+title);
991
                                pestanaEditor.getScript().setSaved(false);
992
                        }
993
                }
994
        }
995

    
996
        public void selectAllScriptingBaseScript(){
997
                if (!unitsEditor.isEmpty()){
998
                        int pestanaIndex = scriptEditors.getSelectedIndex();
999
                        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1000
                        pestanaEditor.getJEditorPanel().selectAll();
1001
                }
1002
        }
1003

    
1004
        /**
1005
         * Función para el guardado del ScriptingBaseScript de la pestaña actual
1006
         *
1007
         */
1008
        public void saveScriptingBaseScript(){
1009
                if (!unitsEditor.isEmpty()){
1010
                        int pestanaIndex = scriptEditors.getSelectedIndex();
1011
                        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1012
                        pestanaEditor.save();
1013
                        String title = scriptEditors.getTitleAt(pestanaIndex);
1014
                        if (title.substring(0, 1).equals("*")){
1015
                                scriptEditors.setTitleAt(pestanaIndex, title.substring(1));
1016
                        }
1017
                }
1018
        }
1019

    
1020
        /**
1021
         * Actualización del Launcher
1022
         *
1023
         */
1024
        public void launcherRefresh(){
1025
                launcher.refresh();
1026
                launcher.addDefaultActionListener(this);
1027
                launcher.setPreferredSize(new Dimension(200, 450));
1028
        }
1029

    
1030
        /**
1031
         * Función para indicar la posición del cursor en un JEditor
1032
         * @param line
1033
         * @param column
1034
         */
1035
        public void setEditorCursorPosition(int line, int column){
1036
                if (line==0 && column ==0)
1037
                        currentLine.setText("");
1038
                else
1039
                        currentLine.setText("Line "+line+":"+column);
1040
                statusBar.repaint();
1041
        }
1042

    
1043
        /**
1044
         * Función para la actualización del mensaje de la barra de estado
1045
         * @param message
1046
         */
1047
        public void setMessage(String message){
1048
                statusBarMessage.setText(message);
1049
                statusBar.repaint();
1050
        }
1051

    
1052
        /**
1053
         * Función para la actualización del mensaje de la barra de estado un tiempo limitado
1054
         * @param message
1055
         * @param seconds
1056
         */
1057
        public void setMessage(String message, int seconds){
1058
                setMessage(message);
1059
        }
1060

    
1061
        /**
1062
         * 
1063
         */
1064
        public void actionPerformed(ActionEvent e) {
1065

    
1066
                if(e instanceof EditorActionEvent){
1067
                        EditorActionEvent e2 = (EditorActionEvent) e;
1068

    
1069
                        int lineAndColumn[] = e2.getLineAndColumn();
1070
                        if (lineAndColumn.length>=2){
1071
                                setEditorCursorPosition(lineAndColumn[0],lineAndColumn[1]);
1072
                        }else{
1073
                                setEditorCursorPosition(0,0);
1074
                        }
1075
                }else if (e instanceof LauncherActionEvent){
1076
                        LauncherActionEvent e2 = (LauncherActionEvent) e;
1077

    
1078
                        switch(e.getID()){
1079
                        case JScriptingBrowser.DEFAULT_ACTION:
1080
                                editUnit(e2.getScript());
1081
                                break;                
1082
                        case JScriptingBrowser.DROPDOWN_ACTION:
1083
                        case JScriptingBrowser.SELECTION_ACTION:
1084

    
1085
                                break;
1086
                        }
1087
                }
1088
        }
1089

    
1090
        /**
1091
         * Clase empleada para crear un objeto JTextArea que hereda 
1092
         * de OutputStream en el que volcar las salidas estándar.
1093
         */
1094

    
1095
        public class JTextAreaOutputStream extends OutputStream {
1096
                JTextArea ta;
1097

    
1098
                public JTextAreaOutputStream(JTextArea t) {
1099
                        super();
1100
                        ta = t;
1101
                }
1102

    
1103
                public void write(int i) {
1104
                        ta.append(Character.toString((char)i));
1105
                }
1106

    
1107
                public void write(char[] buf, int off, int len) {
1108
                        String s = new String(buf, off, len);
1109
                        ta.append(s);
1110
                }
1111
        }
1112

    
1113
        public void update(Observable observable, Object notification) {
1114
                if(notification instanceof ScriptingNotification){
1115
                        ScriptingNotification e= (ScriptingNotification) notification;
1116

    
1117
                        if(e.getException() instanceof ScriptException){
1118
                                ScriptException se =  (ScriptException) e.getException();
1119
                                Object[] row = null;
1120
                                if(se.getLineNumber() == -1 && se.getColumnNumber() == -1){
1121
                                        Object[] rowData = {se.getMessage(),se.getFileName(),"Line: "+"no available"};
1122
                                        row = rowData;
1123
                                } else if(se.getColumnNumber() == -1){
1124
                                        Object[] rowData = {se.getMessage(),se.getFileName(),"Line: "+se.getLineNumber()};
1125
                                        row = rowData;
1126
                                }
1127
                                else{
1128
                                        Object[] rowData = {se.getMessage(),se.getFileName(),"Line: "+se.getLineNumber()+":"+se.getColumnNumber()};
1129
                                        row = rowData;
1130
                                }
1131
                                tableModel.addRow(row);
1132
                        }else if(e.getException() instanceof NoSuchMethodException){
1133
                                Object[] rowData = {"No Main function",e.getId(),"No line"};
1134
                                tableModel.addRow(rowData);
1135
                        }        else{
1136
                                System.out.println("JComposer"+e.getException().getCause().toString());
1137
                                System.out.println("JComposer"+e.getException().toString());
1138
                        }
1139
                }
1140
        }
1141
}