]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.ui/src/org/simantics/scl/ui/console/SCLConsoleView.java
Support for SCL script database storage, editing and execution
[simantics/platform.git] / bundles / org.simantics.scl.ui / src / org / simantics / scl / ui / console / SCLConsoleView.java
1 package org.simantics.scl.ui.console;
2
3 import java.nio.file.Files;
4 import java.nio.file.Path;
5 import java.nio.file.Paths;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.List;
9
10 import org.eclipse.core.runtime.Platform;
11 import org.eclipse.core.runtime.preferences.InstanceScope;
12 import org.eclipse.jface.action.Action;
13 import org.eclipse.jface.action.IAction;
14 import org.eclipse.jface.action.IMenuCreator;
15 import org.eclipse.jface.action.IToolBarManager;
16 import org.eclipse.jface.dialogs.Dialog;
17 import org.eclipse.jface.preference.IPersistentPreferenceStore;
18 import org.eclipse.swt.SWT;
19 import org.eclipse.swt.dnd.DND;
20 import org.eclipse.swt.dnd.DropTarget;
21 import org.eclipse.swt.dnd.DropTargetAdapter;
22 import org.eclipse.swt.dnd.DropTargetEvent;
23 import org.eclipse.swt.dnd.FileTransfer;
24 import org.eclipse.swt.dnd.Transfer;
25 import org.eclipse.swt.events.SelectionAdapter;
26 import org.eclipse.swt.events.SelectionEvent;
27 import org.eclipse.swt.widgets.Composite;
28 import org.eclipse.swt.widgets.Control;
29 import org.eclipse.swt.widgets.Menu;
30 import org.eclipse.swt.widgets.MenuItem;
31 import org.eclipse.ui.part.ViewPart;
32 import org.eclipse.ui.preferences.ScopedPreferenceStore;
33 import org.simantics.scl.compiler.commands.CommandSession;
34 import org.simantics.scl.compiler.commands.CommandSessionImportEntry;
35 import org.simantics.scl.compiler.commands.SCLConsoleListener;
36 import org.simantics.scl.compiler.module.repository.UpdateListener;
37 import org.simantics.scl.compiler.testing.TestRunnable;
38 import org.simantics.scl.osgi.internal.TestUtils;
39 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
40 import org.simantics.scl.ui.Activator;
41 import org.simantics.scl.ui.imports.internal.ManageImportsDialog;
42 import org.simantics.scl.ui.tests.SCLTestsDialog;
43
44 public class SCLConsoleView extends ViewPart {
45
46     public static final String PLUGIN_ID = "org.simantics.scl.ui";
47     public static final String IMPORTS = "imports";
48     public static final String REFRESH_AUTOMATICALLY = "refresh-automatically";
49     public static final String SEPARATOR = ";";
50     public static final String DISABLED_TAG = "[DISABLED]";
51     
52     IPersistentPreferenceStore store;
53     SCLConsole console;
54     boolean refreshAutomatically = false;
55     MenuItem refreshAutomaticallyItem;
56     
57     private ArrayList<CommandSessionImportEntry> readImportPreferences() {
58         String importsString = store.getString(IMPORTS);
59         
60         String[] splitted = importsString.split(SEPARATOR);
61         ArrayList<CommandSessionImportEntry> result = new ArrayList<CommandSessionImportEntry>(splitted.length);
62         for(String entryString : splitted) {
63             if(entryString.isEmpty())
64                 continue;
65             boolean disabled = false;
66             if(entryString.startsWith(DISABLED_TAG)) {
67                 disabled = true;
68                 entryString = entryString.substring(DISABLED_TAG.length());
69             }
70             String[] parts = entryString.split("=");
71             CommandSessionImportEntry entry;
72             if(parts.length == 1)
73                 entry = new CommandSessionImportEntry(parts[0], "", true);
74             else
75                 entry = new CommandSessionImportEntry(parts[1], parts[0], true);
76             entry.disabled = disabled;
77             result.add(entry);
78         }
79         return result;
80     }
81     
82     private void writeImportPreferences(ArrayList<CommandSessionImportEntry> entries) {
83         StringBuilder b = new StringBuilder();
84         
85         boolean first = true;
86         for(CommandSessionImportEntry entry : entries)
87             if(entry.persistent) {
88                 if(first)
89                     first = false;
90                 else
91                     b.append(SEPARATOR);
92                 if(entry.disabled)
93                     b.append(DISABLED_TAG);
94                 if(!entry.localName.isEmpty()) {
95                     b.append(entry.localName);
96                     b.append("=");
97                 }
98                 b.append(entry.moduleName);
99             }
100         
101         IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, PLUGIN_ID);
102         store.setValue(IMPORTS, b.toString());
103     }
104     
105     private ArrayList<CommandSessionImportEntry> getCurrentImports() {
106         return console.getSession().getImportEntries();
107     }
108     
109     private void setCurrentImports(ArrayList<CommandSessionImportEntry> entries) {
110         console.getSession().setImportEntries(entries);
111     }
112     
113     private void manageImports() {
114         ManageImportsDialog dialog = new ManageImportsDialog(
115                 getSite().getShell(),
116                 getCurrentImports());
117         if(dialog.open() == Dialog.OK) {
118             writeImportPreferences(dialog.getImports());
119             setCurrentImports(dialog.getImports());
120         }
121     }
122     
123     private void sclTestDialog() {
124         List<TestRunnable> tests = TestUtils.getTests();
125         SCLTestsDialog dialog = new SCLTestsDialog(
126                 getSite().getShell(),
127                 tests, true);
128         if(dialog.open() == Dialog.OK) {
129             for(Object result : dialog.getResult()) {
130                 TestRunnable test = (TestRunnable) result;
131                 try {
132                     // Bit of a haxx solution to get around a deadlock caused by simply
133                     // running the test with test.run()
134                     console.execute("import \"Commands/Tests\"");
135                     console.execute("runByName \"" + test.getName() + "\"");
136 //                    test.run();
137                 } catch (Exception e) {
138                     e.printStackTrace();
139                 }
140             }
141         }
142     }
143     
144     private UpdateListener dependencyListener = new UpdateListener() {
145         @Override
146         public void notifyAboutUpdate() {
147             if(refreshAutomatically)
148                 console.getSession().updateRuntimeEnvironment(true);
149         }
150     };
151
152     private void setRefreshAutomatically(boolean refreshAutomatically, boolean refreshAlso) {
153         this.refreshAutomatically = refreshAutomatically;
154         if(refreshAutomaticallyItem != null)
155             refreshAutomaticallyItem.setSelection(refreshAutomatically);
156         
157         store.setValue(REFRESH_AUTOMATICALLY, refreshAutomatically);
158         
159         if(refreshAutomatically) {
160             console.getSession().setDependenciesListener(dependencyListener);
161             if(refreshAlso)
162                 console.getSession().updateRuntimeEnvironment(true);
163         }
164         else {
165             console.getSession().setDependenciesListener(null);
166             dependencyListener.stopListening();
167         }
168     }
169     
170     @Override
171     public void createPartControl(Composite parent) {
172         store = new ScopedPreferenceStore(InstanceScope.INSTANCE, PLUGIN_ID);
173         this.console = new SCLConsole(parent, SWT.NONE);
174         
175         setRefreshAutomatically(store.getBoolean(REFRESH_AUTOMATICALLY), false);
176         setCurrentImports(readImportPreferences());
177
178         addScriptDropSupport(console);
179
180         IToolBarManager toolBarManager = getViewSite().getActionBars().getToolBarManager();
181         
182         // Interrupt action
183         final Action interruptAction = new Action("Interrupt current command",
184                 Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/stop.png")) {
185             @Override
186             public void run() {
187                 console.interruptCurrentCommands();
188             }
189         };
190         interruptAction.setDisabledImageDescriptor(
191                 Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/stop_disabled.png"));
192         interruptAction.setEnabled(false);
193         toolBarManager.add(interruptAction);
194         
195         // Clear console action
196         final Action clearAction = new Action("Clear console",
197                 Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/clear_console.png")) {
198             @Override
199             public void run() {
200                 setEnabled(false);
201                 console.clear();
202             }
203         };
204         clearAction.setDisabledImageDescriptor(
205                 Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/clear_console_disabled.png"));
206         clearAction.setEnabled(false);
207         toolBarManager.add(clearAction);
208         console.addListener(new SCLConsoleListener() {
209             @Override
210             public void startedExecution() {
211                 interruptAction.setEnabled(true);
212             }
213             @Override
214             public void finishedExecution() {
215                 interruptAction.setEnabled(false);
216             }
217             @Override
218             public void consoleIsNotEmptyAnymore() {
219                 clearAction.setEnabled(true);
220             }
221         });
222         
223         // Refresh action
224         toolBarManager.add(new Action("Refresh modules", IAction.AS_DROP_DOWN_MENU) {
225             {
226                 setImageDescriptor(Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/arrow_refresh.png"));
227                 setMenuCreator(new IMenuCreator() {
228                     Menu menu;
229                     @Override
230                     public Menu getMenu(Menu parent) {
231                         throw new UnsupportedOperationException();
232                     }
233                     
234                     @Override
235                     public Menu getMenu(Control parent) {
236                         if(menu == null) {
237                             menu = new Menu(parent);
238                             refreshAutomaticallyItem = new MenuItem(menu, SWT.CHECK);
239                             refreshAutomaticallyItem.setText("Refresh automatically");
240                             refreshAutomaticallyItem.setSelection(refreshAutomatically);
241                             refreshAutomaticallyItem.addSelectionListener(new SelectionAdapter() {
242                                 @Override
243                                 public void widgetSelected(SelectionEvent e) {
244                                     setRefreshAutomatically(!refreshAutomatically, true);
245                                 }
246                             });
247                         }
248                         return menu;
249                     }
250                     
251                     @Override
252                     public void dispose() {
253                         if(menu != null)
254                             menu.dispose();
255                     }
256                 });
257             }
258             @Override
259             public void run() {
260                 console.getSession().getModuleRepository().getSourceRepository().checkUpdates();
261                 console.getSession().updateRuntimeEnvironment(true);
262                 console.appendOutput("refresh completed\n", console.greenColor, null);
263             }
264         });
265         toolBarManager.add(new Action("Manage imports",
266                 Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/configure_imports.png")) {
267             @Override
268             public void run() {
269                 manageImports();
270             }
271         });
272         
273         // Show action for running SCL tests if in development mode
274         if (Platform.inDevelopmentMode()) {
275             toolBarManager.add(new Action("Run tests",
276                     Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/run_tests.png")) {
277                 @Override
278                 public void run() {
279                     sclTestDialog();
280                 }
281             });
282         }
283         
284         toolBarManager.update(true);
285     }
286
287     private class ScriptRunningDropTarget extends DropTargetAdapter {
288         @Override
289         public void dragEnter(DropTargetEvent event) {
290             if (event.detail == DND.DROP_DEFAULT) {
291                 event.detail = DND.DROP_LINK;
292             }
293         }
294
295         @Override
296         public void dragOperationChanged(DropTargetEvent event) {
297             if (event.detail == DND.DROP_DEFAULT) {
298                 event.detail = DND.DROP_LINK;
299             }
300         }
301
302         public void drop(DropTargetEvent event) {
303             if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) {
304                 String[] files = ((String[]) event.data).clone();
305                 // Sort files by name to allow deterministic multi-file drop
306                 Arrays.sort(files);
307                 for (String file : files) {
308                     Path p = Paths.get(file).toAbsolutePath();
309                     if (isScriptFile(p)) {
310                         console.execute("runFromFile \"" + p.toString().replace('\\', '/') + "\"");
311                     }
312                 }
313             }
314         }
315
316         private boolean isScriptFile(Path p) {
317             return Files.isRegularFile(p)
318                     //&& p.toString().toLowerCase().endsWith(".scl")
319                     ;
320         }
321     }
322
323     private void addScriptDropSupport(SCLConsole console) {
324         DropTarget target = new DropTarget(console.getOutputWidget(), DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT);
325         target.setTransfer(new Transfer[] { FileTransfer.getInstance() });
326         target.addDropListener(new ScriptRunningDropTarget());
327     }
328
329     @Override
330     public void setFocus() {
331         console.setFocus();
332     }
333     
334     @Override
335     public void dispose() {
336         super.dispose();
337         console.dispose();
338     }
339
340     @SuppressWarnings("unchecked")
341     @Override
342     public <T> T getAdapter(Class<T> adapter) {
343         if (adapter == CommandSession.class)
344             return (T) console.getSession();
345         if (adapter == SCLReportingHandler.class)
346             return (T) console.getHandler();
347         return super.getAdapter(adapter);
348     }
349
350 }