Code

dc4b8dc34f7b0a1fcc15986d97ab73d08778ceea
[inkscape.git] / src / bind / java / org / inkscape / script / ScriptConsole.java
3 package org.inkscape.script;
5 import org.inkscape.cmn.Resource;
7 import javax.script.*;
9 import javax.swing.WindowConstants;
10 import javax.swing.JFrame;
11 import javax.swing.JButton;
12 import javax.swing.JMenu;
13 import javax.swing.JMenuBar;
14 import javax.swing.JMenuItem;
15 import javax.swing.JRadioButtonMenuItem;
16 import javax.swing.ButtonGroup;
17 import javax.swing.JOptionPane;
18 import javax.swing.JFileChooser;
19 import javax.swing.JTabbedPane;
20 import javax.swing.JToolBar;
21 import javax.swing.filechooser.FileNameExtensionFilter;
22 import javax.swing.Action;
23 import javax.swing.AbstractAction;
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.awt.BorderLayout;
30 import java.io.File;
31 import java.io.FileReader;
33 import java.util.List;
34 import java.util.HashMap;
38 /**
39  *
40  */
41 public class ScriptConsole extends JFrame
42 {
43 Terminal    terminal;
44 Editor      editor;
46 JTabbedPane tabPane;
47 JToolBar    toolbar;
48 JMenuBar    menubar;
51 //########################################################################
52 //# MESSSAGES
53 //########################################################################
54 void err(String fmt, Object... arguments)
55 {
56     terminal.errorf("ScriptConsole err:" + fmt, arguments);
57 }
59 void msg(String fmt, Object... arguments)
60 {
61     terminal.outputf("ScriptConsole:" + fmt, arguments);
62 }
64 void trace(String fmt, Object... arguments)
65 {
66     terminal.outputf("ScriptConsole:" + fmt, arguments);
67 }
74 void alert(String msg)
75 {
76     JOptionPane.showMessageDialog(this, msg);
77 }
80 //########################################################################
81 //# U T I L I T Y
82 //########################################################################
84 private JFileChooser _chooser;
86 JFileChooser getChooser()
87 {
88     if (_chooser == null)
89         {
90         _chooser = new JFileChooser();
91         _chooser.setAcceptAllFileFilterUsed(false);
92         FileNameExtensionFilter filter = new FileNameExtensionFilter(
93               "Script Files", "js", "py", "r");
94         _chooser.setFileFilter(filter);
95         }
96     return _chooser;
97 }
101 //########################################################################
102 //# S C R I P T S
103 //########################################################################
104 ScriptEngine engine;
106 HashMap<String, ScriptEngineAction> scriptEngineActions;
108 public void setEngine(ScriptEngine engine)
110     this.engine = engine;
111     this.engine.getContext().setWriter(terminal.getOutWriter());
112     this.engine.getContext().setErrorWriter(terminal.getErrWriter());
116 public ScriptEngine getEngine()
118     return engine;
122 public boolean setEngine(String name)
124     ScriptEngineAction action = scriptEngineActions.get(name);
125     if (action == null)
126         return false;
127     action.setEnabled(true);
128     setEngine(action.factory.getScriptEngine());
129     return true;
133 /**
134  * Run a script buffer
135  *
136  * @param str the script buffer to execute
137  * @return true if successful, else false
138  */
139 public boolean doRunCmd(String str)
141     if (engine == null)
142         {
143         err("No engine set");
144         return false;
145         }
147     //execute script from buffer
148     try
149         {
150         getEngine().eval(str);
151         }
152     catch (javax.script.ScriptException e)
153         {
154         err("Executing script: " + e);
155         //e.printStackTrace();
156         }
157     terminal.output("\nscript> ");
158     return true;
161 /**
162  * Run a script buffer
163  *
164  * @param str the script buffer to execute
165  * @return true if successful, else false
166  */
167 public boolean doRun(String str)
169     if (engine == null)
170         {
171         err("No engine set");
172         return false;
173         }
175     //execute script from buffer
176     try
177         {
178         getEngine().eval(str);
179         }
180     catch (javax.script.ScriptException e)
181         {
182         err("Executing script: " + e);
183         //e.printStackTrace();
184         }
185     return true;
189 /**
190  * Run a script buffer
191  *
192  * @param lang the scripting language to run
193  * @param str the script buffer to execute
194  * @return true if successful, else false
195  */
196 public boolean doRun(String lang, String str)
198     // find script engine
199     if (!setEngine(lang))
200         {
201         err("doRun: cannot find script engine '" + lang + "'");
202         return false;
203                 }
204     return doRun(str);
208 /**
209  * Run a script file
210  *
211  * @param fname the script file to execute
212  * @return true if successful, else false
213  */
214 public boolean doRunFile(String fname)
216     if (engine == null)
217         {
218         err("No engine set");
219         return false;
220         }
222     //try opening file and feeding into engine
223     FileReader in = null;
224     boolean ret = true;
225     try
226         {
227         in = new FileReader(fname);
228         }
229     catch (java.io.IOException e)
230         {
231         err("Executing file: " + e);
232         return false;
233         }
234     try
235         {
236         engine.eval(in);
237         }
238     catch (javax.script.ScriptException e)
239         {
240         err("Executing file: " + e);
241         ret = false;
242         }
243     try
244         {
245         in.close();
246         }
247     catch (java.io.IOException e)
248         {
249         err("Executing file: " + e);
250         return false;
251         }
252     return ret;
256 /**
257  * Run a script file
258  *
259  * @param lang the scripting language to run
260  * @param fname the script file to execute
261  * @return true if successful, else false
262  */
263 public boolean doRunFile(String lang, String fname)
265     // find script engine
266     if (!setEngine(lang))
267         {
268         err("doRunFile: cannot find script engine '" + lang + "'");
269         return false;
270                 }
271     return doRunFile(fname);
275 class ScriptEngineAction extends AbstractAction
277 ScriptEngineFactory factory;
280 public void actionPerformed(ActionEvent evt)
282     setEngine(factory.getScriptEngine());
285 public ScriptEngineAction(ScriptEngineFactory factory)
287     super(factory.getEngineName(), null);
288     putValue(SHORT_DESCRIPTION, factory.getLanguageName());
289     this.factory = factory;
295 private void initScripts()
297     JMenu menu = new JMenu("Language");
298     ButtonGroup group = new ButtonGroup();
299     menubar.add(menu);
301     ScriptEngineManager scriptEngineManager =
302              new ScriptEngineManager();
303     List<ScriptEngineFactory> factories =
304           scriptEngineManager.getEngineFactories();
305     for (ScriptEngineFactory factory: factories)
306             {
307         trace("ScriptEngineFactory Info");
308         String engName     = factory.getEngineName();
309         String engVersion  = factory.getEngineVersion();
310         String langName    = factory.getLanguageName();
311         String langVersion = factory.getLanguageVersion();
312         trace("\tScript Engine: %s (%s)\n", engName, engVersion);
313         List<String> engNames = factory.getNames();
314         for(String name: engNames)
315                     {
316             trace("\tEngine Alias: %s\n", name);
317             }
318         trace("\tLanguage: %s (%s)\n", langName, langVersion);
319         ScriptEngineAction action = new ScriptEngineAction(factory);
320         JRadioButtonMenuItem item = new JRadioButtonMenuItem(action);
321         group.add(item);
322         menu.add(item);
323         }
324     if (menu.getItemCount()>0)
325         {
326         JMenuItem item = menu.getItem(0);
327         group.setSelected(item.getModel(), true);
328         ScriptEngineAction action = (ScriptEngineAction)item.getAction();
329         setEngine(action.factory.getScriptEngine());
330         }
334 static final String defaultCodeStr =
335     "/**\n" +
336     " * This is some example Javascript.\n" +
337     " * Try executing\n" +
338     " */\n" +
339     "importPackage(javax.swing);\n" +
340     "function sayHello() {\n" +
341     "  JOptionPane.showMessageDialog(null, 'Hello, world!',\n" +
342         "     'Welcome to Inkscape', JOptionPane.WARNING_MESSAGE);\n" +
343     "}\n" +
344     "\n" +
345     "sayHello();\n" +
346     "\n";
349 //########################################################################
350 //# A C T I O N S
351 //########################################################################
352 Action newAction;
353 Action openAction;
354 Action quitAction;
355 Action runAction;
356 Action saveAction;
357 Action saveAsAction;
358 Action stopAction;
362 class NewAction extends AbstractAction
365 public void actionPerformed(ActionEvent evt)
367     //
370 public NewAction()
372     super("New", Resource.getIcon("document-new.png"));
373     putValue(SHORT_DESCRIPTION, "Create a new script file");
380 class OpenAction extends AbstractAction
383 public void actionPerformed(ActionEvent evt)
385     JFileChooser chooser = getChooser();
386     int ret = chooser.showOpenDialog(ScriptConsole.this);
387     if (ret != JFileChooser.APPROVE_OPTION)
388         return;
389     File f = chooser.getSelectedFile();
390     String fname = f.getName();
391     alert("You selected : " + fname);
394 public OpenAction()
396     super("Open", Resource.getIcon("document-open.png"));
397     putValue(SHORT_DESCRIPTION, "Open a script file");
404 class QuitAction extends AbstractAction
407 public void actionPerformed(ActionEvent evt)
409     setVisible(false);
412 public QuitAction()
414     super("Quit", Resource.getIcon("system-log-out.png"));
415     putValue(SHORT_DESCRIPTION, "Quit this script console");
422 class RunAction extends AbstractAction
425 public void actionPerformed(ActionEvent evt)
427     String txt = editor.getText();
428     doRun(txt);
431 public RunAction()
433     super("Run", Resource.getIcon("go-next.png"));
434     putValue(SHORT_DESCRIPTION, "Run the script in the editor");
441 class SaveAction extends AbstractAction
444 public void actionPerformed(ActionEvent evt)
446     JFileChooser chooser = getChooser();
447     int ret = chooser.showSaveDialog(ScriptConsole.this);
448     if (ret != JFileChooser.APPROVE_OPTION)
449         return;
450     File f = chooser.getSelectedFile();
451     String fname = f.getName();
452     alert("You selected : " + fname);
455 public SaveAction()
457     super("Save", Resource.getIcon("document-save.png"));
458     putValue(SHORT_DESCRIPTION, "Save file");
465 class SaveAsAction extends AbstractAction
468 public void actionPerformed(ActionEvent evt)
470     JFileChooser chooser = getChooser();
471     int ret = chooser.showSaveDialog(ScriptConsole.this);
472     if (ret != JFileChooser.APPROVE_OPTION)
473         return;
474     File f = chooser.getSelectedFile();
475     String fname = f.getName();
476     alert("You selected : " + fname);
479 public SaveAsAction()
481     super("SaveAs", Resource.getIcon("document-save-as.png"));
482     putValue(SHORT_DESCRIPTION, "Save under a new file name");
489 class StopAction extends AbstractAction
492 public void actionPerformed(ActionEvent evt)
494     //#
497 public StopAction()
499     super("Stop", Resource.getIcon("process-stop.png"));
500     putValue(SHORT_DESCRIPTION, "Stop the running script");
507 HashMap<String, Action> actions;
508 void setupActions()
510     actions = new HashMap<String, Action>();
511     actions.put("New",    newAction    = new NewAction());
512     actions.put("Open",   openAction   = new OpenAction());
513     actions.put("Quit",   quitAction   = new QuitAction());
514     actions.put("Run",    runAction    = new RunAction());
515     actions.put("Save",   saveAction   = new SaveAction());
516     actions.put("SaveAs", saveAsAction = new SaveAsAction());
517     actions.put("Stop",   stopAction   = new StopAction());
521 public void enableAction(String name)
523     Action action = actions.get(name);
524     if (action == null)
525         return;
526     action.setEnabled(true);
529 public void disableAction(String name)
531     Action action = actions.get(name);
532     if (action == null)
533         return;
534     action.setEnabled(false);
539 //########################################################################
540 //# S E T U P
541 //########################################################################
543 JButton toolbarButton(Action action)
545     JButton btn = new JButton(action);
546     btn.setText("");
547     btn.setToolTipText((String)action.getValue(Action.SHORT_DESCRIPTION));
548     return btn;
552 private boolean setup()
554     setTitle("Inkscape Script Console");
555     setSize(600, 400);
556     setIconImage(Resource.getImage("inkscape.png"));
557     setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
559     //######################################################
560     //#  A C T I O N S
561     //######################################################
562     setupActions();
564     //######################################################
565     //# M E N U
566     //######################################################
567     menubar = new JMenuBar();
568     setJMenuBar(menubar);
570     JMenu menu = new JMenu("File");
571     menubar.add(menu);
572     menu.add(new JMenuItem(openAction));
573     menu.add(new JMenuItem(saveAction));
574     menu.add(new JMenuItem(saveAsAction));
575     menu.add(new JMenuItem(quitAction));
576         
577     menu = new JMenu("Run");
578     menubar.add(menu);
579     menu.add(new JMenuItem(runAction));
580     menu.add(new JMenuItem(stopAction));
582     //######################################################
583     //# T O O L B A R
584     //######################################################
585     toolbar = new JToolBar();
586     getContentPane().add(toolbar, BorderLayout.NORTH);
587     toolbar.add(toolbarButton(openAction));
588     toolbar.add(toolbarButton(saveAction));
589     toolbar.add(toolbarButton(runAction));
590     toolbar.add(toolbarButton(stopAction));
592     //######################################################
593     //# C O N T E N T
594     //######################################################
595     tabPane = new JTabbedPane();
596     getContentPane().add(tabPane, BorderLayout.CENTER);
597     
598     terminal = new Terminal();
599     tabPane.addTab("Console",
600                    Resource.getIcon("utilities-terminal.png"),
601                    terminal);
602     terminal.output("\nscript> ");
604     editor = new Editor();
605     tabPane.addTab("Script",
606                    Resource.getIcon("accessories-text-editor.png"),
607                    editor);
609     editor.setText(defaultCodeStr);
610     
611     //######################################################
612     //#  E N G I N E
613     //######################################################
614     initScripts();
616     return true;
624 public ScriptConsole()
626     setup();
630 private static ScriptConsole _instance = null;
631 public static ScriptConsole getInstance()
633     if (_instance == null)
634         _instance = new ScriptConsole();
635     return _instance;
639 public static void main(String argv[])
641     ScriptConsole sc = getInstance();
642     sc.setVisible(true);
647 //########################################################################
648 //# E N D    O F    F I L E
649 //########################################################################