Statistics
| Revision:

gvsig-scripting / org.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 @ 471

History | View | Annotate | Download (58.8 KB)

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

    
3
import java.awt.BorderLayout;
4
import java.awt.Dialog;
5
import java.awt.Dimension;
6
import java.awt.Font;
7
import java.awt.event.ActionEvent;
8
import java.awt.event.ActionListener;
9
import java.awt.event.KeyEvent;
10
import java.io.File;
11
import java.io.OutputStream;
12
import java.io.PrintStream;
13
import java.util.Iterator;
14
import java.util.LinkedHashMap;
15
import java.util.List;
16
import java.util.Map;
17
import javax.swing.AbstractAction;
18

    
19
import javax.swing.JButton;
20
import javax.swing.JLabel;
21
import javax.swing.JMenu;
22
import javax.swing.JMenuBar;
23
import javax.swing.JMenuItem;
24
import javax.swing.JOptionPane;
25
import javax.swing.JPanel;
26
import javax.swing.JScrollPane;
27
import javax.swing.JSplitPane;
28
import javax.swing.JTabbedPane;
29
import javax.swing.JTable;
30
import javax.swing.JTextArea;
31
import javax.swing.JToolBar;
32
import javax.swing.KeyStroke;
33
import javax.swing.ListSelectionModel;
34
import javax.swing.SwingConstants;
35
import javax.swing.SwingUtilities;
36
import javax.swing.UIManager;
37
import javax.swing.event.ChangeEvent;
38
import javax.swing.event.ChangeListener;
39
import javax.swing.event.ListSelectionEvent;
40
import javax.swing.event.ListSelectionListener;
41
import javax.swing.table.DefaultTableModel;
42
import javax.swing.text.BadLocationException;
43
import javax.swing.text.JTextComponent;
44
import org.fife.rsta.ui.GoToDialog;
45
import org.fife.rsta.ui.search.FindDialog;
46
import org.fife.rsta.ui.search.ReplaceDialog;
47
import org.fife.rsta.ui.search.SearchEvent;
48
import org.fife.rsta.ui.search.SearchListener;
49
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
50
import org.fife.ui.rtextarea.SearchContext;
51
import org.fife.ui.rtextarea.SearchEngine;
52
import org.fife.ui.rtextarea.SearchResult;
53
import org.gvsig.installer.swing.api.SwingInstallerLocator;
54
import org.gvsig.installer.swing.api.SwingInstallerManager;
55
import org.gvsig.installer.swing.api.packagebuilder.PackageBuildder;
56

    
57
import org.gvsig.scripting.CompileErrorException;
58
import org.gvsig.scripting.ExecuteErrorException;
59
import org.gvsig.scripting.ScriptingBaseScript;
60
import org.gvsig.scripting.ScriptingDialog;
61
import org.gvsig.scripting.ScriptingFolder;
62
import org.gvsig.scripting.ScriptingManager;
63
import org.gvsig.scripting.ScriptingNotification;
64
import org.gvsig.scripting.ScriptingScript;
65
import org.gvsig.scripting.ScriptingUnit;
66
import org.gvsig.scripting.swing.api.JCodeEditor;
67
import org.gvsig.scripting.swing.api.JEditor;
68
import org.gvsig.scripting.swing.api.JScriptingBrowser;
69
import org.gvsig.scripting.swing.api.JScriptingComposer;
70
import org.gvsig.scripting.swing.api.ScriptingUIManager;
71
import org.gvsig.scripting.swing.api.SyntaxtHighlightTextComponent.UpdateCaretPositionActionEvent;
72
import org.gvsig.scripting.swing.impl.DefaultJScriptingBrowser;
73
import org.gvsig.scripting.swing.impl.DefaultJScriptingLauncher;
74
import org.gvsig.scripting.swing.impl.DefaultJScriptingLauncher.LauncherActionEvent;
75
import org.gvsig.scripting.swing.impl.DefaultScriptingUIManager;
76
import org.gvsig.scripting.swing.impl.JDialogContent;
77
import org.gvsig.tools.ToolsLocator;
78
import org.gvsig.tools.i18n.I18nManager;
79
import org.gvsig.tools.observer.Observable;
80
import org.gvsig.tools.observer.Observer;
81
import org.gvsig.tools.packageutils.PackageInfo;
82
import org.gvsig.tools.packageutils.PackageManager;
83
import org.gvsig.tools.packageutils.Version;
84
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
85
import org.slf4j.Logger;
86
import org.slf4j.LoggerFactory;
87

    
88
public class DefaultJScriptingComposer extends JScriptingComposer implements Observer, ActionListener, SearchListener {
89

    
90
    /**
91
     *
92
     */
93
    private static final long serialVersionUID = 1L;
94

    
95
    private static final Logger logger = LoggerFactory.getLogger(DefaultJScriptingComposer.class);
96

    
97
    public static final int CLOSE_ACTION = 1;
98
    public Map<String, JEditor> unitsEditor;
99

    
100
    /* Generales */
101
    ScriptingUIManager uimanager;
102
    ScriptingManager manager;
103
    ClassLoader loader;
104

    
105
    /* Ventana inicial y componentes*/
106
    JSplitPane mainPane;
107
    JSplitPane editionPane;
108
    JTabbedPane problemsPane;
109
    JTabbedPane scriptEditors;
110
    JMenuBar menuBar;
111
    JToolBar file;
112
    JToolBar edit;
113
    JToolBar script;
114
    JToolBar help;
115
    JPanel statusBar;
116
    JLabel currentLine;
117
    JLabel statusBarMessage;
118
    JTextArea problems;
119
    JTextArea console;
120
    DefaultJScriptingLauncher launcher;
121
    JToolBar launcherButtons;
122
    PrintStream consolePrintStream = null;
123

    
124
    private FindDialog findDialog;
125
    private ReplaceDialog replaceDialog;
126
    private GoToDialog gotoDialog;
127
    
128
    JTable table;
129
    DefaultTableModel tableModel;
130
    protected ActionListener defaultActionlistener = null;
131

    
132
    /**
133
     * Instanciacion de un JComposer con todos sus elementos y acciones
134
     *
135
     * @param manager
136
     */
137
    public DefaultJScriptingComposer(final ScriptingUIManager uimanager) {
138
        loader = this.getClass().getClassLoader();
139
        this.uimanager = uimanager;
140
        this.manager = uimanager.getManager();
141

    
142
        unitsEditor = new LinkedHashMap<String, JEditor>();
143

    
144
        initComponents();
145

    
146
        System.setOut(this.getConsolePrintStream());
147
        System.setErr(this.getConsolePrintStream());
148

    
149
    }
150

    
151
    @Override
152
    public WindowManager getWindowManager() {
153
        return ((DefaultScriptingUIManager)(this.uimanager)).getWindowManager();
154
    }
155

    
156
    @Override
157
    public void setWindowManager(WindowManager windowsManager) {
158
        ((DefaultScriptingUIManager)(this.uimanager)).setWindowManager(windowsManager);
159
    }
160

    
161
    private void initComponents() {
162
        
163
        findDialog = new FindDialog((Dialog)null, this);
164
        replaceDialog = new ReplaceDialog((Dialog)null, this);
165
        gotoDialog = new GoToDialog((Dialog) null);
166
        
167
        SearchContext searchContext = findDialog.getSearchContext();
168
        replaceDialog.setSearchContext(searchContext);
169
        
170
        // Barra de menu
171
        menuBar = new JMenuBar();
172

    
173
        // Construimos los componentes del menu
174
        JMenu menu_file = new JMenu(this.uimanager.getTranslation("File"));
175
        JMenuItem menuItem_new = new JMenuItem(this.uimanager.getTranslation("New"), uimanager.getIcon("document-new"));
176
        menuItem_new.addActionListener(new ActionListener() {
177
            public void actionPerformed(ActionEvent e) {
178
                try {
179
                    scriptNew();
180
                } catch (Exception e1) {
181
                    // TODO Auto-generated catch block
182
                    e1.printStackTrace();
183
                }
184
            }
185
        });
186
        menu_file.add(menuItem_new);
187
        menu_file.addSeparator();
188
        JMenuItem menuItem_close = new JMenuItem(this.uimanager.getTranslation("Close_document"), uimanager.getIcon("emblem-unreadable"));
189
        menuItem_close.addActionListener(new ActionListener() {
190
            public void actionPerformed(ActionEvent e) {
191
                currentScriptClose();
192
            }
193
        });
194
        menu_file.add(menuItem_close);
195
        JMenuItem menuItem_closeAll = new JMenuItem(this.uimanager.getTranslation("Close_all_documents"), uimanager.getIcon("emblem-unreadable"));
196
        menuItem_closeAll.addActionListener(new ActionListener() {
197
            public void actionPerformed(ActionEvent e) {
198
                closeAllScripts();
199
            }
200
        });
201
        menu_file.add(menuItem_closeAll);
202
        menu_file.addSeparator();
203
        JMenuItem menuItem_run = new JMenuItem(this.uimanager.getTranslation("Run"), uimanager.getIcon("applications-system"));
204
        menuItem_run.addActionListener(new ActionListener() {
205
            public void actionPerformed(ActionEvent e) {
206
                currentScriptExecute();
207
            }
208
        });
209
        menu_file.add(menuItem_run);
210
        menu_file.addSeparator();
211
        JMenuItem menuItem_save = new JMenuItem(this.uimanager.getTranslation("Save"), uimanager.getIcon("media-floppy"));
212
        menuItem_save.addActionListener(new ActionListener() {
213
            public void actionPerformed(ActionEvent e) {
214
                currentScriptSave();
215
            }
216
        });
217
        menu_file.add(menuItem_save);
218
        menu_file.addSeparator();
219
        JMenuItem menuItem_exit = new JMenuItem(this.uimanager.getTranslation("Close"), uimanager.getIcon("system-log-out"));
220
        menuItem_exit.addActionListener(new ActionListener() {
221
            public void actionPerformed(ActionEvent e) {
222
                closeAllScripts();
223
                closeWindow();
224
                if (defaultActionlistener != null) {
225
                    ActionEvent event = new ActionEvent(this, CLOSE_ACTION, "close");
226
                    defaultActionlistener.actionPerformed(event);
227
                }
228

    
229
            }
230
        });
231
        menu_file.add(menuItem_exit);
232

    
233
        JMenu menu_edit = new JMenu(this.uimanager.getTranslation("Edit"));
234
        JMenuItem menuItem_cut = new JMenuItem(this.uimanager.getTranslation("Cut"), uimanager.getIcon("edit-cut"));
235
        menuItem_cut.addActionListener(new ActionListener() {
236
            @Override
237
            public void actionPerformed(ActionEvent e) {
238
                currentScriptCut();
239
            }
240
        });
241
        menu_edit.add(menuItem_cut);
242
        JMenuItem menuItem_copy = new JMenuItem(this.uimanager.getTranslation("Copy"), uimanager.getIcon("edit-copy"));
243
        menuItem_copy.addActionListener(new ActionListener() {
244
            @Override
245
            public void actionPerformed(ActionEvent e) {
246
                currentScriptCopy();
247
            }
248
        });
249
        menu_edit.add(menuItem_copy);
250
        JMenuItem menuItem_paste = new JMenuItem(this.uimanager.getTranslation("Paste"), uimanager.getIcon("edit-paste"));
251
        menuItem_paste.addActionListener(new ActionListener() {
252
            @Override
253
            public void actionPerformed(ActionEvent e) {
254
                currentScriptPaste();
255
            }
256
        });
257
        menu_edit.add(menuItem_paste);
258
        menu_edit.addSeparator();
259
        
260
        JMenuItem menuItem_selectAll = new JMenuItem(this.uimanager.getTranslation("Select_all"), uimanager.getIcon("edit-select-all"));
261
        menuItem_selectAll.addActionListener(new ActionListener() {
262
            @Override
263
            public void actionPerformed(ActionEvent e) {
264
                currentScriptSelectAll();
265
            }
266
        });
267
        menu_edit.add(menuItem_selectAll);
268
        menu_edit.addSeparator();
269
        
270
        menu_edit.add(new JMenuItem(new ShowFindDialogAction()));
271
        menu_edit.add(new JMenuItem(new ShowReplaceDialogAction()));
272
        menu_edit.add(new JMenuItem(new GoToLineAction()));
273
        
274
        JMenu menu_tools = new JMenu(this.uimanager.getTranslation("Tools"));
275
        JMenuItem menuItem_launcher = new JMenuItem(this.uimanager.getTranslation("Launcher"));
276
        menuItem_launcher.addActionListener(new ActionListener() {
277
            @Override
278
            public void actionPerformed(ActionEvent e) {
279
                getWindowManager().showWindow(uimanager.createLauncher(), uimanager.getTranslation("Scripting_Launcher"), WindowManager.MODE.TOOL);
280
            }
281
        });
282
        menu_tools.add(menuItem_launcher);
283

    
284
        JMenuItem menuItem_packager = new JMenuItem(this.uimanager.getTranslation("_Scripting_packager"));
285
        menuItem_packager.addActionListener(new ActionListener() {
286

    
287
            @Override
288
            public void actionPerformed(ActionEvent ae) {
289
                createPackage();
290
            }
291
        });
292
        menu_tools.add(menuItem_packager);
293

    
294
        JMenu menu_help = new JMenu("Help");
295
        JMenuItem menuItem_import = new JMenuItem(this.uimanager.getTranslation("Import_JavaDoc"), uimanager.getIcon("list-add"));
296
        menuItem_import.addActionListener(new ActionListener() {
297
            @Override
298
            public void actionPerformed(ActionEvent e) {
299
                getWindowManager().showWindow(getImportHelpDialog(), uimanager.getTranslation("JavaDoc"), WindowManager.MODE.WINDOW);
300
            }
301
        });
302
        menu_help.add(menuItem_import);
303
        JMenuItem menuItem_remove = new JMenuItem(this.uimanager.getTranslation("Remove_JavaDoc"), uimanager.getIcon("list-remove"));
304
        menuItem_remove.addActionListener(new ActionListener() {
305
            @Override
306
            public void actionPerformed(ActionEvent e) {
307
                try {
308
                    getRemoveHelpDialog();
309
                } catch (Exception e1) {
310
                    // TODO Auto-generated catch block
311
                    e1.printStackTrace();
312
                }
313
            }
314
        });
315
        menu_help.add(menuItem_remove);
316
        JMenuItem menuItem_show = new JMenuItem(this.uimanager.getTranslation("Show_JavaDoc"), uimanager.getIcon("help-browser"));
317
        menuItem_show.addActionListener(new ActionListener() {
318
            @Override
319
            public void actionPerformed(ActionEvent e) {
320
                getWindowManager().showWindow(uimanager.getAPIHelp(), uimanager.getTranslation("JavaDoc"), WindowManager.MODE.WINDOW);
321
            }
322
        });
323
        menu_help.add(menuItem_show);
324
        menu_help.addSeparator();
325
        JMenuItem menuItem_about = new JMenuItem(this.uimanager.getTranslation("About_us"), uimanager.getIcon("system-users"));
326
        menuItem_about.addActionListener(new ActionListener() {
327
            @Override
328
            public void actionPerformed(ActionEvent e) {
329
                getWindowManager().showWindow(getAboutUsDialog(), uimanager.getTranslation("About_us"), WindowManager.MODE.WINDOW);
330

    
331
            }
332
        });
333
        menu_help.add(menuItem_about);
334
        JMenuItem menuItem_help = new JMenuItem(this.uimanager.getTranslation("Get_help"), uimanager.getIcon("help-browser"));
335
        menuItem_help.addActionListener(new ActionListener() {
336
            @Override
337
            public void actionPerformed(ActionEvent e) {
338
                getWindowManager().showWindow(uimanager.getUserHelp(), uimanager.getTranslation("Get_help"), WindowManager.MODE.WINDOW);
339
            }
340
        });
341
        menu_help.add(menuItem_help);
342

    
343
        menuBar.add(menu_file);
344
        menuBar.add(menu_edit);
345
        menuBar.add(menu_tools);
346
        menuBar.add(menu_help);
347

    
348
        // Botones de acción
349
        file = new JToolBar();
350
        help = new JToolBar();
351
        edit = new JToolBar();
352
        script = new JToolBar();
353
        setButtonsDefault();
354
        JPanel scriptButtonsPane = new JPanel(new BorderLayout());
355
        scriptButtonsPane.add(edit, BorderLayout.WEST);
356

    
357
        scriptButtonsPane.add(script, BorderLayout.CENTER);
358
        JPanel buttonsPane = new JPanel(new BorderLayout());
359
        buttonsPane.add(file, BorderLayout.WEST);
360
        buttonsPane.add(help, BorderLayout.EAST);
361
        buttonsPane.add(scriptButtonsPane, BorderLayout.CENTER);
362

    
363
        JPanel launcherPane = new JPanel(new BorderLayout());
364
        launcher = (DefaultJScriptingLauncher) uimanager.createLauncher();
365
        launcher.addDefaultActionListener(this);
366
        launcher.setPreferredSize(new Dimension(200, 450));
367
        launcherButtons = new JToolBar(SwingConstants.VERTICAL);
368
        setButtonsLauncherPanel();
369

    
370
        launcherPane.add(launcher, BorderLayout.CENTER);
371
        launcherPane.add(launcherButtons, BorderLayout.WEST);
372

    
373
        // Panel de Edición
374
        scriptEditors = new JTabbedPane();
375
        scriptEditors.addChangeListener(new ChangeListener() {
376
            public void stateChanged(ChangeEvent arg0) {
377
                JPanel editor = (JPanel) scriptEditors.getSelectedComponent();
378
                if (scriptEditors.getSelectedIndex() == -1) {
379
                    setButtonsDefault();
380
                } else if (editor instanceof DefaultJDialogEditor) {
381
                    setButtonsDialog();
382
                } else if (editor instanceof DefaultJCodeEditor) {
383
                    setButtonsScript();
384
                }
385
            }
386
        });
387
        scriptEditors.setPreferredSize(new Dimension(500, 350));
388
        problemsPane = new JTabbedPane();
389

    
390
        tableModel = new AbstractTableModel();
391
        tableModel.addColumn(this.uimanager.getTranslation("Description"));
392
        tableModel.addColumn(this.uimanager.getTranslation("Resource"));
393
        tableModel.addColumn(this.uimanager.getTranslation("Location"));
394
        table = new JTable(tableModel);
395
        table.getColumnModel().getColumn(0).setPreferredWidth(300);
396
                //table.setFont(new Font("Serif",Font.PLAIN,13));
397

    
398
        table.getSelectionModel().addListSelectionListener(new RowListener());
399
        table.setRowSelectionAllowed(true);
400
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
401

    
402
        JScrollPane scrollProblems = new JScrollPane(table);
403
        scrollProblems.setAutoscrolls(true);
404

    
405
        console = new JTextArea();
406
        console.setFont(new Font("monospaced", Font.PLAIN, 13));
407

    
408
        JScrollPane scrollConsole = new JScrollPane(console);
409
        problemsPane.add(this.uimanager.getTranslation("Problems"), scrollProblems);
410
        problemsPane.add(this.uimanager.getTranslation("Console"), scrollConsole);
411
        problemsPane.setPreferredSize(new Dimension(450, 100));
412
        problemsPane.setSelectedIndex(1);
413

    
414
        /* Si no se desea cargar datos para que arranque con ellos,
415
         * este if nunca será cierto */
416
        if (!unitsEditor.isEmpty()) {;
417
            Iterator<JEditor> it = unitsEditor.values().iterator();
418
            while (it.hasNext()) {
419
                JEditor editor = it.next();
420
                editor.addDefaultActionListener(this);
421
                scriptEditors.addTab(editor.getScript().getName(), editor);
422
            }
423
        }
424
        editionPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scriptEditors, problemsPane);
425
        editionPane.setOneTouchExpandable(true);
426

    
427
        mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, launcherPane, editionPane);
428
        mainPane.setOneTouchExpandable(true);
429

    
430
        // Barra de estado
431
        statusBar = new JPanel(new BorderLayout());
432
        statusBarMessage = new JLabel();
433
        statusBarMessage.setText(this.uimanager.getTranslation("Welcome_message"));
434
        currentLine = new JLabel();
435
        currentLine.setText("Line 0:0");
436

    
437
        statusBar.add(statusBarMessage, BorderLayout.WEST);
438
        statusBar.add(currentLine, BorderLayout.EAST);
439

    
440
        // Integracíón en el frame principal de todos los componentes
441
        JPanel buttons = new JPanel();
442
        buttons.setLayout(new BorderLayout());
443
        buttons.add(BorderLayout.NORTH, menuBar);
444
        buttons.add(BorderLayout.SOUTH, buttonsPane);
445

    
446
        this.setLayout(new BorderLayout());
447
        this.add(BorderLayout.NORTH, buttons);
448
        this.add(BorderLayout.CENTER, mainPane);
449
        this.add(BorderLayout.SOUTH, statusBar);
450
        this.setPreferredSize(new Dimension(800, 600));
451
    }
452

    
453
    private void createPackage() {
454
        I18nManager i18nManager = ToolsLocator.getI18nManager();
455
        SwingInstallerManager installerManager = SwingInstallerLocator.getSwingInstallerManager();
456
        PackageBuildder packager = installerManager.createPackagerPanel(
457
                ScriptingManager.INSTALLER_PROVIDER_NAME,
458
                manager.getRootUserFolder(),
459
                manager.getPackagesFolder()
460
        );
461
        PackageInfo packageInfo = packager.getPackageInfo();
462
        packageInfo.setArchitecture(PackageManager.ARCH.ALL);
463
        packageInfo.setJavaVM(PackageManager.JVM.J1_7);
464
        packageInfo.setOperatingSystem(PackageManager.OS.ALL);
465
        packageInfo.setOfficial(false);
466
        packageInfo.setState(PackageManager.STATE.TESTING);
467
        packageInfo.setType(ScriptingManager.INSTALLER_PROVIDER_NAME);
468
        Version version = ToolsLocator.getPackageManager().createVersion();
469
        version.parse("1.0.0");
470
        packageInfo.setVersion(version);
471
        this.uimanager.showWindow(
472
                (JPanel) packager.asJComponent(),
473
                i18nManager.getTranslation("_Scripting_packager")
474
        );
475
    }
476
    
477
    private PrintStream getConsolePrintStream() {
478
        if (this.consolePrintStream == null) {
479
            JTextAreaOutputStream outputConsole = new JTextAreaOutputStream(console);
480
            this.consolePrintStream = new PrintStream(outputConsole);
481
        }
482
        return this.consolePrintStream;
483
    }
484

    
485
    private class AbstractTableModel extends DefaultTableModel {
486

    
487
        /**
488
         *
489
         */
490
        private static final long serialVersionUID = -5314938428821653641L;
491

    
492
        @Override
493
        public boolean isCellEditable(int row, int col) {
494
            return false;
495
        }
496
    }
497

    
498
    private class RowListener implements ListSelectionListener {
499

    
500
        public void valueChanged(ListSelectionEvent event) {
501
            if (event.getValueIsAdjusting()) {
502
                return;
503
            }
504
            if (!table.getSelectionModel().isSelectionEmpty()) {
505
                int index = table.getSelectionModel().getLeadSelectionIndex();
506
                String[] lineAndColumn = ((String) table.getValueAt(index, 2)).split(":");
507
                int line = -1;
508
                if (lineAndColumn.length > 0) {
509
                    try {
510
                        line = Integer.parseInt(lineAndColumn[0].trim());
511
                    } catch (Exception e) {
512
                        // Do nothing
513
                    }
514
                }
515
                if (line >= 0) {
516
                    setEditorSelection(((String) table.getValueAt(index, 1)), line);
517
                }
518
            }
519
        }
520
    }
521

    
522
    private void setEditorSelection(String name, int line) {
523
        for (int i = 0; i < scriptEditors.getTabCount(); i++) {
524

    
525
            if (((JEditor) scriptEditors.getComponent(i)).getScript().getId().equals(name)) {
526
                scriptEditors.setSelectedIndex(i);
527

    
528
                JTextComponent editor = ((JCodeEditor) scriptEditors.getComponent(i)).getJTextComponent();
529
                editor.requestFocusInWindow();
530

    
531
                String code = editor.getText();
532
                int lineCounter = 0;
533
                int initialSelection = 0;
534
                int finalSelection = 0;
535
                for (int j = 0; j < code.length(); j++) {
536
                    if (code.charAt(j) == '\n') {
537
                        lineCounter++;
538
                        if (lineCounter == line - 1) {
539
                            initialSelection = j;
540
                        }
541
                        if (lineCounter == line || (finalSelection == 0 && j == code.length() - 1)) {
542
                            finalSelection = j;
543
                        }
544
                    }
545
                }
546

    
547
                editor.select(initialSelection, finalSelection);
548
            }
549
        }
550
    }
551

    
552
    public void addDefaultActionListener(ActionListener actionlistener) {
553
        this.defaultActionlistener = actionlistener;
554
    }
555

    
556
    /**
557
     * Función para obtener el elemento seleccionado del Launcher
558
     *
559
     * @return Selected ScriptingUnit on the tree
560
     */
561
    private ScriptingUnit getLauncherSelectedScript() {
562
        JTabbedPane tabbed = launcher.getTabbedPane();
563
        DefaultJScriptingBrowser browser = (DefaultJScriptingBrowser) tabbed.getSelectedComponent();
564
        ScriptingUnit unit = browser.getSelectedNode();
565
        return unit;
566
    }
567

    
568
    /**
569
     * Lanza la ejecución de un ScriptingBaseScript
570
     *
571
     * @param unit
572
     */
573
    private void scriptExecute(ScriptingUnit unit) {
574
        if (unit instanceof ScriptingBaseScript) {
575
            ((ScriptingBaseScript) unit).run();
576
        }
577
    }
578

    
579
    /**
580
     * Funciones para obtener las botoneras en función del tipo de
581
     * ScriptingBaseScript que se esté mostrando en ese momento. Está la
582
     * estándar 'getDefaultButtons()' para cuando no hay ninguno,
583
     * 'getScriptButtons()' con los botones característicos para el manejo de
584
     * ScriptingScripts y 'getDialogButtons()' para los ScriptingDialogs.
585
     * También se incluye 'getEditButtons()' con las funciones sobre la
586
     * edición de texto como copiar, cortar y pegar.
587
     *
588
     */
589
    private void setButtonsDefault() {
590
        file.removeAll();
591
        edit.removeAll();
592
        script.removeAll();
593
        help.removeAll();
594
        JButton newb = new JButton(uimanager.getIcon("document-new"));
595
        newb.setToolTipText(this.uimanager.getTranslation("New"));
596
        newb.setBorderPainted(false);
597
        newb.addActionListener(new ActionListener() {
598
            public void actionPerformed(ActionEvent e) {
599
                try {
600
                    scriptNew();
601
                } catch (Exception e1) {
602
                    // TODO Auto-generated catch block
603
                    e1.printStackTrace();
604
                }
605
            }
606
        });
607
        file.add(newb);
608
        file.repaint();
609

    
610
        help.removeAll();
611
        JButton helpb = new JButton(uimanager.getIcon("help-browser"));
612
        helpb.setBorderPainted(false);
613
        helpb.setToolTipText(this.uimanager.getTranslation("Help"));
614
        helpb.addActionListener(new ActionListener() {
615
            public void actionPerformed(ActionEvent e) {
616
                uimanager.showWindow(uimanager.getAPIHelp(), uimanager.getTranslation("JavaDoc"));
617
            }
618
        });
619
        help.add(helpb);
620
        help.repaint();
621
        edit.setVisible(false);
622
        script.setVisible(false);
623
    }
624

    
625
    private void setButtonsScript() {
626
        file.removeAll();
627
        edit.removeAll();
628
        script.removeAll();
629
        setButtonsDefault();
630

    
631
        edit.setVisible(true);
632
        script.setVisible(true);
633
        setButtonsEdit();
634
        JButton close = new JButton(uimanager.getIcon("emblem-unreadable"));
635
        close.setBorderPainted(false);
636
        close.setToolTipText(this.uimanager.getTranslation("Close_current_tab"));
637
        close.addActionListener(new ActionListener() {
638
            public void actionPerformed(ActionEvent e) {
639
                currentScriptClose();
640
            }
641
        });
642
        file.add(close);
643
        JButton save = new JButton(uimanager.getIcon("media-floppy"));
644
        save.setBorderPainted(false);
645
        save.setToolTipText(this.uimanager.getTranslation("Save"));
646
        save.addActionListener(new ActionListener() {
647
            public void actionPerformed(ActionEvent e) {
648
                currentScriptSave();
649
            }
650
        });
651
        file.add(save);
652
        file.repaint();
653

    
654
        JButton run = new JButton(uimanager.getIcon("applications-system"));
655
        run.setBorderPainted(false);
656
        run.setToolTipText(this.uimanager.getTranslation("Run"));
657
        run.addActionListener(new ActionListener() {
658
            public void actionPerformed(ActionEvent e) {
659
                currentScriptExecute();
660
            }
661
        });
662
        script.add(run);
663
        script.repaint();
664
    }
665

    
666
    private void setButtonsDialog() {
667
        script.removeAll();
668
        setButtonsScript();
669
        script.addSeparator();
670
        JButton help = new JButton(uimanager.getIcon("help-browser"));
671
        help.setBorderPainted(false);
672
        help.setToolTipText(this.uimanager.getTranslation("Help"));
673
        script.add(help);
674
        script.repaint();
675
    }
676

    
677
    private void setButtonsEdit() {
678
        JButton cut = new JButton(uimanager.getIcon("edit-cut"));
679
        cut.setBorderPainted(false);
680
        cut.setToolTipText(this.uimanager.getTranslation("Cut"));
681
        cut.addActionListener(new ActionListener() {
682
            public void actionPerformed(ActionEvent e) {
683
                currentScriptCut();
684
            }
685
        });
686
        edit.add(cut);
687
        JButton copy = new JButton(uimanager.getIcon("edit-copy"));
688
        copy.setBorderPainted(false);
689
        copy.setToolTipText(this.uimanager.getTranslation("Copy"));
690
        copy.addActionListener(new ActionListener() {
691
            public void actionPerformed(ActionEvent e) {
692
                currentScriptCopy();
693
            }
694
        });
695
        edit.add(copy);
696
        JButton paste = new JButton(uimanager.getIcon("edit-paste"));
697
        paste.setBorderPainted(false);
698
        paste.setToolTipText(this.uimanager.getTranslation("Paste"));
699
        paste.addActionListener(new ActionListener() {
700
            public void actionPerformed(ActionEvent e) {
701
                currentScriptPaste();
702
            }
703
        });
704
        edit.add(paste);
705
        edit.repaint();
706
    }
707

    
708
    /**
709
     * Botonera con posibles acciones a realizar con el Panel Launcher
710
     *
711
     */
712
    private void setButtonsLauncherPanel() {
713

    
714
        JButton newb = new JButton(uimanager.getIcon("document-new"));
715
        newb.setBorderPainted(false);
716
        newb.setToolTipText(this.uimanager.getTranslation("New"));
717
        newb.addActionListener(new ActionListener() {
718
            public void actionPerformed(ActionEvent e) {
719
                try {
720
                    scriptNew();
721
                } catch (Exception e1) {
722
                    // TODO Auto-generated catch block
723
                    e1.printStackTrace();
724
                }
725
            }
726
        });
727
        launcherButtons.add(newb);
728
        JButton edit = new JButton(uimanager.getIcon("applications-accessories"));
729
        edit.setBorderPainted(false);
730
        edit.setToolTipText(this.uimanager.getTranslation("Open_edition_mode"));
731
        edit.addActionListener(new ActionListener() {
732
            public void actionPerformed(ActionEvent e) {
733
                scriptEdit((ScriptingBaseScript)getLauncherSelectedScript());
734
            }
735
        });
736
        launcherButtons.add(edit);
737
        JButton run = new JButton(uimanager.getIcon("applications-system"));
738
        run.setBorderPainted(false);
739
        run.setToolTipText(this.uimanager.getTranslation("Run_selected_script"));
740
        run.addActionListener(new ActionListener() {
741
            public void actionPerformed(ActionEvent e) {
742
                scriptExecute(getLauncherSelectedScript());
743
            }
744
        });
745
        launcherButtons.add(run);
746
        launcherButtons.addSeparator();
747
        JButton refresh = new JButton(uimanager.getIcon("view-refresh"));
748
        refresh.setBorderPainted(false);
749
        refresh.setToolTipText(this.uimanager.getTranslation("Refresh_directories"));
750
        refresh.addActionListener(new ActionListener() {
751
            public void actionPerformed(ActionEvent e) {
752
                launcherRefresh();
753
            }
754
        });
755
        launcherButtons.add(refresh);
756
        launcherButtons.addSeparator();
757
        JButton rename = new JButton(uimanager.getIcon("preferences-system"));
758
        rename.setBorderPainted(false);
759
        rename.setToolTipText(this.uimanager.getTranslation("Set_file_properties"));
760
        rename.addActionListener(new ActionListener() {
761
            public void actionPerformed(ActionEvent e) {
762
                try {
763
                    scriptRename(getLauncherSelectedScript());
764
                } catch (Exception e1) {
765
                    // TODO Auto-generated catch block
766
                    e1.printStackTrace();
767
                }
768
            }
769
        });
770
        launcherButtons.add(rename);
771
        JButton move = new JButton(uimanager.getIcon("format-indent-more"));
772
        move.setBorderPainted(false);
773
        move.setToolTipText(this.uimanager.getTranslation("Move_files"));
774
        move.addActionListener(new ActionListener() {
775
            public void actionPerformed(ActionEvent e) {
776
                try {
777
                    scriptMove(getLauncherSelectedScript());
778
                } catch (Exception e1) {
779
                    // TODO Auto-generated catch block
780
                    e1.printStackTrace();
781
                }
782
            }
783
        });
784
        launcherButtons.add(move);
785
        launcherButtons.addSeparator();
786
        JButton delete = new JButton(uimanager.getIcon("user-trash"));
787
        delete.setBorderPainted(false);
788
        delete.setToolTipText(this.uimanager.getTranslation("Delete_selected_script"));
789
        delete.addActionListener(new ActionListener() {
790
            public void actionPerformed(ActionEvent e) {
791
                scriptDelete(getLauncherSelectedScript(), false);
792
            }
793
        });
794
        launcherButtons.add(delete);
795
    }
796

    
797
    /**
798
     * Función que abre en modo edición un ScriptingBaseScript
799
     *
800
     * @param unit
801
     */
802
    public void scriptEdit(ScriptingBaseScript unit) {
803
        if( ! unitsEditor.containsKey(unit.getFile().getAbsolutePath()) ) {
804
            JEditor panel = null;
805
            if (unit instanceof ScriptingDialog) {
806
                panel = new DefaultJDialogEditor(uimanager, (ScriptingDialog) unit);
807
                if (panel instanceof DefaultJDialogEditor) {
808
                    ((DefaultJDialogEditor) panel).addDefaultActionListener(this);
809
                }
810
            } else if (unit instanceof ScriptingScript) {
811
                panel = new DefaultJCodeEditor(uimanager, (ScriptingScript) unit);
812
                if (panel instanceof DefaultJCodeEditor) {
813
                    ((DefaultJCodeEditor) panel).addDefaultActionListener(this);
814
                }
815
            } else {
816
                JOptionPane.showMessageDialog(null, this.uimanager.getTranslation("Error_opening_in_edition_mode"), this.uimanager.getTranslation("Error_opening_in_edition_mode_title"), JOptionPane.INFORMATION_MESSAGE);
817
                return;
818
            }
819
            unitsEditor.put(unit.getFile().getAbsolutePath(), panel);
820
        }
821
        int n = 0;
822
        int selected = unitsEditor.size() - 1;
823
        Iterator<JEditor> it = unitsEditor.values().iterator();
824
        while (it.hasNext()) {
825
            JEditor editor = it.next();
826
            String title;
827
            if (editor.getScript().isSaved()) {
828
                title = editor.getScript().getName();
829
            } else {
830
                title = "*" + editor.getScript().getName();
831
            }
832
            scriptEditors.addTab(title, editor);
833
            if( editor.getScript().getFile().getAbsolutePath().equals(unit.getFile().getAbsolutePath()) ) {
834
                selected = n;
835
            }
836
            n++;
837
        }
838
        scriptEditors.setSelectedIndex(selected);
839
        editionPane.repaint();
840
        file.repaint();
841
    }
842

    
843
    /**
844
     * Ventana para creación de nuevos ScriptingBaseScripts
845
     *
846
     * @throws Exception
847
     *
848
     */
849
    public void scriptNew() throws Exception {
850
        JNewScriptModel model = new JNewScriptModel(manager);
851
        JDialogContent dialog = new JDialogContent(
852
                uimanager,
853
                "document-new",
854
                this.uimanager.getTranslation("New_Script"),
855
                this.uimanager.getTranslation("New_Script_Description"),
856
                new JNewScriptPanel(uimanager, model)
857
        );
858
        dialog.showDialog();
859
        if (model.getAction() == JNewScriptModel.ACTION_ACCEPT) {
860
            model.validate();
861
            ScriptingUnit unit = this.manager.createUnit(
862
                    model.getType(),
863
                    manager.getFolder(new File(model.getPath())),
864
                    model.getName(),
865
                    model.getLanguage()
866
            );
867
            if (unit instanceof ScriptingBaseScript) {
868
                this.scriptEdit((ScriptingBaseScript) unit);
869
            }
870

    
871
            this.launcherRefresh();
872
        }
873
    }
874

    
875
    public JPanel getImportHelpDialog() {
876
        return new JDialogContent(
877
                uimanager,
878
                "list-add",
879
                this.uimanager.getTranslation("Import_JavaDoc"),
880
                this.uimanager.getTranslation("Import_JavaDoc_title"),
881
                new JImportHelpController(uimanager, this));
882
    }
883

    
884
    public void getRemoveHelpDialog() throws Exception {
885
        JRemoveHelpModel model = new JRemoveHelpModel(manager);
886
        JDialogContent dialog = new JDialogContent(
887
                uimanager,
888
                "list-remove",
889
                this.uimanager.getTranslation("Remove_JavaDoc"),
890
                this.uimanager.getTranslation("Remove_JavaDoc_title"),
891
                new JRemoveHelpPanel(uimanager, model));
892
        dialog.showDialog();
893
        if (model.getAction() == JNewScriptModel.ACTION_ACCEPT) {
894
            this.removeHelps(model);
895
        }
896
    }
897

    
898
    public void removeHelps(JRemoveHelpModel model) throws Exception {
899
        model.validate();
900
        Object[] helps = model.getHelps();
901
        for (int i = 0; i < helps.length; i++) {
902
            this.manager.getHelpManager().removeHelp(helps[i].toString());
903
        }
904
        //Recargar JavaHelp
905
        this.manager.getHelpManager().reloadHelp();
906
        JOptionPane.showMessageDialog(null,
907
                this.uimanager.getTranslation("Deleting_JavaDocs_successfully"),
908
                this.uimanager.getTranslation("Deleting_JavaDocs_successfully_title"),
909
                JOptionPane.INFORMATION_MESSAGE);
910
        uimanager.showWindow(uimanager.getAPIHelp(), this.uimanager.getTranslation("JavaDoc"));
911
    }
912

    
913
    public void scriptMove(final ScriptingUnit theUnit) throws Exception {
914
        if (theUnit.getParent() == null) {
915
            JOptionPane.showMessageDialog(null, "Please, select first the file to move on the tree directory", "Error", JOptionPane.ERROR_MESSAGE);
916
        } else {
917
            JMoveScriptModel model = new JMoveScriptModel(manager, theUnit);
918
            JDialogContent dialog = new JDialogContent(
919
                    uimanager,
920
                    "format-indent-more",
921
                    this.uimanager.getTranslation("Move") + " '" + theUnit.getName() + "' " + this.uimanager.getTranslation("script_filesystem"),
922
                    this.uimanager.getTranslation("move_desc"),
923
                    new JMoveScriptPanel(uimanager, model)
924
            );
925
            dialog.showDialog();
926
            if (model.getAction() == JMoveScriptModel.ACTION_ACCEPT) {
927
                model.validate();
928
                ScriptingFolder folderDest = manager.getFolder(model.getMoveTo());
929
                if (model.getUnit().move(folderDest)) {
930
                    JOptionPane.showMessageDialog(null,
931
                            this.uimanager.getTranslation("Moving_succesfully"),
932
                            this.uimanager.getTranslation("Success"), JOptionPane.INFORMATION_MESSAGE);
933
                    this.launcherRefresh();
934
                } else {
935
                    JOptionPane.showMessageDialog(null,
936
                            this.uimanager.getTranslation("Error_moving"),
937
                            this.uimanager.getTranslation("Error"), JOptionPane.ERROR_MESSAGE);
938
                }
939
            }
940
        }
941

    
942
    }
943

    
944
    public void scriptRename(ScriptingUnit theUnit) throws Exception {
945
        if (theUnit.getParent() == null) {
946
            JOptionPane.showMessageDialog(null,
947
                    this.uimanager.getTranslation("Select_first"),
948
                    this.uimanager.getTranslation("Error"), JOptionPane.ERROR_MESSAGE);
949
        } else {
950
            JRenameModel model = new JRenameModel(manager, theUnit);
951
            JDialogContent dialog = new JDialogContent(
952
                    uimanager,
953
                    "preferences-system",
954
                    this.uimanager.getTranslation("Rename") + " '" + theUnit.getName() + "' " + this.uimanager.getTranslation("script_filesystem"),
955
                    this.uimanager.getTranslation("rename_desc"),
956
                    new JRenamePanel(uimanager, model)
957
            );
958
            dialog.showDialog();
959
            if (model.getAction() == JRenameModel.ACTION_ACCEPT) {
960
                model.validate();
961
                ScriptingUnit unit = model.getUnit();
962
                if (!model.getNewName().equals(unit.getId())) {
963
                    if (unit.rename(model.getNewName())) {
964
                        JOptionPane.showMessageDialog(null,
965
                                this.uimanager.getTranslation("Rename_succesfully"),
966
                                this.uimanager.getTranslation("Success"), JOptionPane.INFORMATION_MESSAGE);
967
                        this.launcherRefresh();
968
                    } else {
969
                        JOptionPane.showMessageDialog(null,
970
                                this.uimanager.getTranslation(this.uimanager.getTranslation("Error_renaming")),
971
                                this.uimanager.getTranslation("Error"), JOptionPane.ERROR_MESSAGE);
972
                    }
973
                    if (unit instanceof ScriptingScript) {
974
                        ((ScriptingScript) unit).save();
975
                    }
976
                }                
977
            }
978
        }
979
    }
980

    
981
    @Override
982
    public JPanel getAboutUsDialog() {
983
        return new JDialogContent(uimanager,
984
                "system-users",
985
                this.uimanager.getTranslation("About_us"),
986
                this.uimanager.getTranslation("About_us_title"),
987
                new JDefaultDialog(uimanager, this, uimanager.getAboutManager().getAboutPanel()));
988
    }
989

    
990
    public void scriptDelete(final ScriptingUnit unit, boolean isRecursive) {
991
        int n = 0;
992
        if (!isRecursive) {
993
            n = JOptionPane.showConfirmDialog(
994
                    this.getRootPane(),
995
                    this.uimanager.getTranslation("Delete_all_message"),
996
                    this.uimanager.getTranslation("Delete_all_title"),
997
                    JOptionPane.YES_NO_OPTION);
998
        }
999
        if (n == 0) {
1000
            //Si es un folder borramos recursivamente sus subdirectorios
1001
            if (unit instanceof ScriptingFolder) {
1002
                List<ScriptingUnit> subunits
1003
                        = ((ScriptingFolder) unit).getUnits();
1004
                Iterator<ScriptingUnit> it = subunits.iterator();
1005
                while (it.hasNext()) {
1006
                    ScriptingUnit subunit = it.next();
1007
                    scriptDelete(subunit, true);
1008
                }
1009
            }
1010
            // Por último borramos el nodo seleccionado
1011
            unit.getParent().remove(unit);
1012
            launcherRefresh();
1013

    
1014
        }
1015
    }
1016

    
1017
    /**
1018
     * Función que cierra la pestaña de edición actual
1019
     *
1020
     */
1021
    public void currentScriptClose() {
1022
        if (!unitsEditor.isEmpty()) {
1023
            int position = scriptEditors.getSelectedIndex();
1024
            String title = scriptEditors.getTitleAt(position);
1025
            JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(position);
1026
            ScriptingScript script = pestanaEditor.getScript();
1027
            int respuesta = 1;
1028
            if (!script.isSaved()) {
1029
                respuesta = JOptionPane.showConfirmDialog(
1030
                        scriptEditors,
1031
                        "'" + title.substring(1) + "' " + this.uimanager.getTranslation("project_modified"),
1032
                        this.uimanager.getTranslation("projects_modified_title"),
1033
                        JOptionPane.YES_NO_CANCEL_OPTION);
1034
                if (respuesta == 0) {
1035
                    currentScriptSave();
1036
                }
1037
            }
1038

    
1039
            if (respuesta < 2) {
1040
                pestanaEditor.getScript().setSaved(true);
1041
                scriptEditors.remove(position);
1042
                unitsEditor.remove(script.getFile().getAbsolutePath());
1043
                scriptEditors.repaint();
1044
            }
1045
        }
1046
    }
1047

    
1048
    /**
1049
     * Función que cierra todas las pestañas de edición abiertas
1050
     *
1051
     */
1052
    public void closeAllScripts() {
1053
        boolean exit = false;
1054
        while (!unitsEditor.isEmpty() && !exit) {
1055
            int action = 1;
1056
            int i = 0;
1057
            boolean answered = false;
1058
            while (i < scriptEditors.getComponentCount() && !answered) {
1059
                JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(i);
1060
                if (!pestanaEditor.getScript().isSaved()) {
1061
                    action = JOptionPane.showConfirmDialog(
1062
                            scriptEditors,
1063
                            this.uimanager.getTranslation("projects_modified"),
1064
                            this.uimanager.getTranslation("projects_modified_title"),
1065
                            JOptionPane.YES_NO_CANCEL_OPTION);
1066
                    answered = true;
1067
                }
1068
                i++;
1069
            }
1070
            if (action == 0) {
1071
                for (i = 0; i < scriptEditors.getComponentCount(); i++) {
1072
                    scriptEditors.setSelectedIndex(i);
1073
                    currentScriptSave();
1074
                }
1075
            }
1076
            if (action < 2) {
1077
                for (i = scriptEditors.getComponentCount() - 1; i >= 0; i--) {
1078
                    JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(i);
1079
                    pestanaEditor.getScript().setSaved(true);
1080
                    scriptEditors.setSelectedIndex(i);
1081
                    currentScriptClose();
1082
                }
1083
            } else {
1084
                exit = true;
1085
            }
1086

    
1087
        }
1088
    }
1089

    
1090
    /**
1091
     * Función que ejecuta el ScriptingBaseScript de la pestaña actual
1092
     *
1093
     */
1094
    public void currentScriptExecute() {
1095
        if (!unitsEditor.isEmpty()) {
1096
            int pestanaIndex = scriptEditors.getSelectedIndex();
1097
            JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1098
            consoleClear();
1099
            errorsClear();
1100
            pestanaEditor.getScript().addObserver(this);
1101
            try {
1102
                ScriptingScript script = pestanaEditor.getScript();
1103
                script.compile();
1104
                script.runAsTask(null);
1105

    
1106
            } catch (Throwable e) {
1107
                 logger.info("Can't execute dialog-", e);
1108
            }
1109
        }
1110
    }
1111

    
1112
    /*
1113
     class ScriptTask extends AbstractMonitorableTask {
1114

1115
     ScriptingScript script;
1116
     DefaultJScriptingComposer composer; 
1117
                
1118
     protected ScriptTask(DefaultJScriptingComposer composer,  ScriptingScript script) {
1119
     super(script.getName());
1120
     this.composer = composer;
1121
     this.script = script;
1122
     this.script.put("task",this);
1123
     this.script.put("taskStatus",this.getTaskStatus());
1124
     }
1125
                
1126
     public void run() {
1127
     try {
1128
     composer.consolePrintln("Running '"+ script.getName() +"'...");
1129
     script.run();
1130
     composer.consolePrintln("Quit '"+ script.getName() +"'");
1131
     } catch (Throwable e) {
1132
     ((SimpleTaskStatus)this.getTaskStatus()).abort();
1133
     composer.consolePrintln("Aborted '"+ script.getName() +"'");
1134
     }
1135
     }
1136
     }
1137
     */
1138
    /**
1139
     * Funciones de 'cortar', 'copiar', 'pegar' y 'seleccionar todo' para los
1140
     * JEditors
1141
     *
1142
     */
1143
    public void currentScriptCopy() {
1144
        if (!unitsEditor.isEmpty()) {
1145
            int pestanaIndex = scriptEditors.getSelectedIndex();
1146
            JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1147
            pestanaEditor.getJTextComponent().copy();
1148
        }
1149
    }
1150

    
1151
    public void currentScriptCut() {
1152
        if (!unitsEditor.isEmpty()) {
1153
            int pestanaIndex = scriptEditors.getSelectedIndex();
1154
            JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1155
            pestanaEditor.getJTextComponent().cut();
1156
            JTabbedPane tabs = (JTabbedPane) pestanaEditor.getParent();
1157

    
1158
            String title = tabs.getTitleAt(pestanaIndex);
1159
            if (title.length() > 0 && !title.substring(0, 1).equals("*")) {
1160
                tabs.setTitleAt(tabs.getSelectedIndex(), "*" + title);
1161
                pestanaEditor.getScript().setSaved(false);
1162
            }
1163
        }
1164
    }
1165

    
1166
    public void currentScriptPaste() {
1167
        if (!unitsEditor.isEmpty()) {
1168
            int pestanaIndex = scriptEditors.getSelectedIndex();
1169
            JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1170
            pestanaEditor.getJTextComponent().paste();
1171
            JTabbedPane tabs = (JTabbedPane) pestanaEditor.getParent();
1172

    
1173
            String title = tabs.getTitleAt(pestanaIndex);
1174
            if (title.length() > 0 && !title.substring(0, 1).equals("*")) {
1175
                tabs.setTitleAt(tabs.getSelectedIndex(), "*" + title);
1176
                pestanaEditor.getScript().setSaved(false);
1177
            }
1178
        }
1179
    }
1180

    
1181
    public void currentScriptSelectAll() {
1182
        if (!unitsEditor.isEmpty()) {
1183
            int pestanaIndex = scriptEditors.getSelectedIndex();
1184
            JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1185
            pestanaEditor.getJTextComponent().selectAll();
1186
        }
1187
    }
1188

    
1189
    /**
1190
     * Función para el guardado del ScriptingBaseScript de la pestaña actual
1191
     *
1192
     */
1193
    public void currentScriptSave() {
1194
        if (!unitsEditor.isEmpty()) {
1195
            int pestanaIndex = scriptEditors.getSelectedIndex();
1196
            JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1197
            pestanaEditor.save();
1198
            String title = scriptEditors.getTitleAt(pestanaIndex);
1199
            if (title.substring(0, 1).equals("*")) {
1200
                scriptEditors.setTitleAt(pestanaIndex, title.substring(1));
1201
            }
1202
        }
1203
    }
1204

    
1205
    /**
1206
     * Actualización del Launcher
1207
     *
1208
     */
1209
    public void launcherRefresh() {
1210
        launcher.refresh();
1211
//        launcher.addDefaultActionListener(this);
1212
//        launcher.setPreferredSize(new Dimension(200, 450));
1213
    }
1214

    
1215
    /**
1216
     * Función para indicar la posición del cursor en un JEditor
1217
     *
1218
     * @param line
1219
     * @param column
1220
     */
1221
    public void setEditorCursorPosition(int line, int column) {
1222
        if (line == 0 && column == 0) {
1223
            currentLine.setText("");
1224
        } else {
1225
            currentLine.setText(
1226
                    this.uimanager.getTranslation("Line") + " " + line + ":" + column);
1227
        }
1228
        statusBar.repaint();
1229
    }
1230

    
1231
    /**
1232
     * Función para la actualización del mensaje de la barra de estado
1233
     *
1234
     * @param message
1235
     */
1236
    public void setMessage(String message) {
1237
        statusBarMessage.setText(message);
1238
        statusBar.repaint();
1239
    }
1240

    
1241
    /**
1242
     * Función para la actualización del mensaje de la barra de estado un
1243
     * tiempo limitado
1244
     *
1245
     * @param message
1246
     * @param seconds
1247
     */
1248
    public void setMessage(String message, int seconds) {
1249
        setMessage(message);
1250
    }
1251

    
1252
    /**
1253
     *
1254
     */
1255
    public void actionPerformed(ActionEvent e) {
1256

    
1257
        if (e instanceof UpdateCaretPositionActionEvent) {
1258
            UpdateCaretPositionActionEvent e2 = (UpdateCaretPositionActionEvent) e;
1259

    
1260
            if (e2.hasLineAndColumn()) {
1261
                setEditorCursorPosition(e2.getLine(), e2.getColumn());
1262
            } else {
1263
                setEditorCursorPosition(0, 0);
1264
            }
1265
        } else if (e instanceof LauncherActionEvent) {
1266
            LauncherActionEvent e2 = (LauncherActionEvent) e;
1267

    
1268
            switch (e.getID()) {
1269
                case JScriptingBrowser.DEFAULT_ACTION:
1270
                    scriptEdit(e2.getScript());
1271
                    break;
1272
                case JScriptingBrowser.DROPDOWN_ACTION:
1273
                case JScriptingBrowser.SELECTION_ACTION:
1274

    
1275
                    break;
1276
            }
1277
        }
1278
    }
1279

    
1280
    /**
1281
     * Clase empleada para crear un objeto JTextArea que hereda de OutputStream
1282
     * en el que volcar las salidas estándar.
1283
     */
1284
    public class JTextAreaOutputStream extends OutputStream {
1285

    
1286
        JTextArea ta;
1287

    
1288
        public JTextAreaOutputStream(JTextArea t) {
1289
            super();
1290
            ta = t;
1291
        }
1292

    
1293
        @Override
1294
        public void write(int i) {
1295
            ta.append(Character.toString((char) i));
1296
        }
1297

    
1298
        public void write(char[] buf, int off, int len) {
1299
            String s = new String(buf, off, len);
1300
            ta.append(s);
1301
        }
1302
    }
1303

    
1304
    public void update(final Observable observable, final Object notification) {
1305
        if (!SwingUtilities.isEventDispatchThread()) {
1306
            SwingUtilities.invokeLater(new Runnable() {
1307
                public void run() {
1308
                    update(observable, notification);
1309
                }
1310
            });
1311
            return;
1312
        }
1313
        if (notification instanceof ScriptingNotification) {
1314
            ScriptingNotification e = (ScriptingNotification) notification;
1315

    
1316
            if (e.getException() instanceof CompileErrorException) {
1317
                CompileErrorException ce = (CompileErrorException) e.getException();
1318
                errorsAdd(ce.getMessage(), ce.getScriptName(), ce.getLineNumber(), ce.getColumnNumber());
1319

    
1320
            } else if (e.getException() instanceof ExecuteErrorException) {
1321
                ExecuteErrorException ee = (ExecuteErrorException) e.getException();
1322
                errorsAdd(ee.getMessage(), ee.getScriptName(), ee.getLineNumber(), ee.getColumnNumber());
1323
                consolePrintln(ee.getMessage());
1324
                ee.printStackTrace(this.getConsolePrintStream());
1325

    
1326
            } else {
1327
                Throwable ex = e.getException();
1328
                errorsAdd(ex.getMessage());
1329
                consolePrintln(ex.getMessage());
1330
                ex.printStackTrace(this.getConsolePrintStream());
1331
            }
1332
        }
1333
    }
1334

    
1335
    public void errorsAdd(final String description, final String resource, final int line, final int column) {
1336
        if (!SwingUtilities.isEventDispatchThread()) {
1337
            SwingUtilities.invokeLater(new Runnable() {
1338
                public void run() {
1339
                    errorsAdd(description, resource, line, column);
1340
                }
1341
            });
1342
            return;
1343
        }
1344
        String location1;
1345
        if (line < 0) {
1346
            location1 = "(" + this.uimanager.getTranslation("no_line") + ")";
1347
        } else if (column < 0) {
1348
            location1 = String.valueOf(line);
1349
        } else {
1350
            location1 = String.valueOf(line) + ":" + String.valueOf(column);
1351
        }
1352
        Object[] rowData = {description, resource, location1};
1353
        tableModel.addRow(rowData);
1354
        problemsPane.setSelectedIndex(0);
1355
    }
1356

    
1357
    public void errorsAdd(String description, String resource) {
1358
        errorsAdd(description, resource, -1, -1);
1359
    }
1360

    
1361
    public void errorsAdd(String description) {
1362
        errorsAdd(description, null, -1, -1);
1363
    }
1364

    
1365
    public void errorsClear() {
1366
        if (!SwingUtilities.isEventDispatchThread()) {
1367
            SwingUtilities.invokeLater(new Runnable() {
1368
                public void run() {
1369
                    errorsClear();
1370
                }
1371
            });
1372
            return;
1373
        }
1374
        while (tableModel.getRowCount() > 0) {
1375
            tableModel.removeRow(0);
1376
        }
1377
    }
1378

    
1379
    public void consoleClear() {
1380
        if (!SwingUtilities.isEventDispatchThread()) {
1381
            SwingUtilities.invokeLater(new Runnable() {
1382
                public void run() {
1383
                    consoleClear();
1384
                }
1385
            });
1386
            return;
1387
        }
1388
        console.setText("");
1389
        problemsPane.setSelectedIndex(1);
1390
    }
1391

    
1392
    public void consolePrintln(final String str) {
1393
        if (!SwingUtilities.isEventDispatchThread()) {
1394
            SwingUtilities.invokeLater(new Runnable() {
1395
                public void run() {
1396
                    consolePrintln(str);
1397
                }
1398
            });
1399
            return;
1400
        }
1401
        console.append(str);
1402
        console.append("\n");
1403
        problemsPane.setSelectedIndex(1);
1404
    }
1405

    
1406
    public void consolePrint(final String str) {
1407
        if (!SwingUtilities.isEventDispatchThread()) {
1408
            SwingUtilities.invokeLater(new Runnable() {
1409
                public void run() {
1410
                    consolePrint(str);
1411
                }
1412
            });
1413
            return;
1414
        }
1415
        console.append(str);
1416
        problemsPane.setSelectedIndex(1);
1417
    }
1418

    
1419
    public void closeWindow() {
1420
        this.setVisible(false);
1421
    }
1422

    
1423

    
1424
    private RSyntaxTextArea getCurrentRSyntaxTextArea() {
1425
        int pestanaIndex = scriptEditors.getSelectedIndex();
1426
        JEditor pestanaEditor = (JEditor) scriptEditors.getComponentAt(pestanaIndex);
1427
        JTextComponent textComponent = pestanaEditor.getJTextComponent();
1428
        if( !(textComponent instanceof RSyntaxTextArea) ) {
1429
            return null;
1430
        }
1431
        return (RSyntaxTextArea)textComponent;
1432
    }
1433

    
1434
    private class GoToLineAction extends AbstractAction {
1435

    
1436
        public GoToLineAction() {
1437
            super("Go To Line...");
1438
            int c = getToolkit().getMenuShortcutKeyMask();
1439
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_L, c));
1440
        }
1441

    
1442
        public void actionPerformed(ActionEvent e) {
1443

    
1444
            RSyntaxTextArea textArea = getCurrentRSyntaxTextArea();
1445
            if (textArea == null) {
1446
                return;
1447
            }
1448

    
1449
            if (findDialog.isVisible()) {
1450
                findDialog.setVisible(false);
1451
            }
1452
            if (replaceDialog.isVisible()) {
1453
                replaceDialog.setVisible(false);
1454
            }
1455
            gotoDialog.setMaxLineNumberAllowed(textArea.getLineCount());
1456
            gotoDialog.setVisible(true);
1457
            int line = gotoDialog.getLineNumber();
1458
            if (line > 0) {
1459
                try {
1460
                    textArea.setCaretPosition(textArea.getLineStartOffset(line - 1));
1461
                } catch (BadLocationException ble) { // Never happens
1462
                    UIManager.getLookAndFeel().provideErrorFeedback(textArea);
1463
                    ble.printStackTrace();
1464
                }
1465
            }
1466
        }
1467
    }
1468

    
1469
    private class ShowFindDialogAction extends AbstractAction {
1470

    
1471
        public ShowFindDialogAction() {
1472
            super("Find...");
1473
            int c = getToolkit().getMenuShortcutKeyMask();
1474
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, c));
1475
        }
1476

    
1477
        public void actionPerformed(ActionEvent e) {
1478
            if (replaceDialog.isVisible()) {
1479
                replaceDialog.setVisible(false);
1480
            }
1481
            findDialog.setVisible(true);
1482
        }
1483
    }
1484
    
1485
    private class ShowReplaceDialogAction extends AbstractAction {
1486

    
1487
        public ShowReplaceDialogAction() {
1488
            super("Replace...");
1489
            int c = getToolkit().getMenuShortcutKeyMask();
1490
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_H, c));
1491
        }
1492

    
1493
        public void actionPerformed(ActionEvent e) {
1494
            if (findDialog.isVisible()) {
1495
                findDialog.setVisible(false);
1496
            }
1497
            replaceDialog.setVisible(true);
1498
        }
1499
    }
1500
    
1501
    @Override
1502
    public void searchEvent(SearchEvent e) {
1503

    
1504
        RSyntaxTextArea textArea = getCurrentRSyntaxTextArea();
1505
        if( textArea == null ) {
1506
            return;
1507
        }
1508
        
1509
        SearchEvent.Type type = e.getType();
1510
        SearchContext context = e.getSearchContext();
1511
        SearchResult result = null;
1512
        
1513
        switch (type) {
1514
            default: // Prevent FindBugs warning later
1515
            case MARK_ALL:
1516
                result = SearchEngine.markAll(textArea, context);
1517
                break;
1518
            case FIND:
1519
                result = SearchEngine.find(textArea, context);
1520
                if (!result.wasFound()) {
1521
                    UIManager.getLookAndFeel().provideErrorFeedback(textArea);
1522
                }
1523
                break;
1524
            case REPLACE:
1525
                result = SearchEngine.replace(textArea, context);
1526
                if (!result.wasFound()) {
1527
                    UIManager.getLookAndFeel().provideErrorFeedback(textArea);
1528
                }
1529
                break;
1530
            case REPLACE_ALL:
1531
                result = SearchEngine.replaceAll(textArea, context);
1532
                JOptionPane.showMessageDialog(null, result.getCount()
1533
                        + " occurrences replaced.");
1534
                break;
1535
        }
1536
        String text = null;
1537
        if (result.wasFound()) {
1538
            text = "Text found; occurrences marked: " + result.getMarkedCount();
1539
        } else if (type == SearchEvent.Type.MARK_ALL) {
1540
            if (result.getMarkedCount() > 0) {
1541
                text = "Occurrences marked: " + result.getMarkedCount();
1542
            } else {
1543
                text = "";
1544
            }
1545
        } else {
1546
            text = "Text not found";
1547
        }
1548
        setMessage(text);
1549
    }
1550

    
1551
    @Override
1552
    public String getSelectedText() {
1553
        RSyntaxTextArea textArea = getCurrentRSyntaxTextArea();
1554
        if( textArea == null ) {
1555
            return "";
1556
        }
1557
        return textArea.getSelectedText();
1558
    }
1559

    
1560
}