bab62144b5e514ffbcdd6f6984b650e7875a4e76
[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"; //$NON-NLS-1$
47     public static final String IMPORTS = "imports"; //$NON-NLS-1$
48     public static final String REFRESH_AUTOMATICALLY = "refresh-automatically"; //$NON-NLS-1$
49     public static final String SEPARATOR = ";"; //$NON-NLS-1$
50     public static final String DISABLED_TAG = "[DISABLED]"; //$NON-NLS-1$
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("="); //$NON-NLS-1$
71             CommandSessionImportEntry entry;
72             if(parts.length == 1)
73                 entry = new CommandSessionImportEntry(parts[0], "", true); //$NON-NLS-1$
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("="); //$NON-NLS-1$
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\""); //$NON-NLS-1$
135                     console.execute("runByName \"" + test.getName() + "\""); //$NON-NLS-1$ //$NON-NLS-2$
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         store.setDefault(REFRESH_AUTOMATICALLY, true);
174         
175         this.console = new SCLConsole(parent, SWT.NONE);
176
177         IToolBarManager toolBarManager = getViewSite().getActionBars().getToolBarManager();
178         
179         // Interrupt action
180         Action interruptAction = ConsoleActions.createInterruptAction(console);
181         toolBarManager.add(interruptAction);
182         
183         // Clear console action
184         Action clearAction = ConsoleActions.createClearAction(console);
185         toolBarManager.add(clearAction);
186         
187         console.addListener(new SCLConsoleListener() {
188             @Override
189             public void startedExecution() {
190                 interruptAction.setEnabled(true);
191             }
192             @Override
193             public void finishedExecution() {
194                 interruptAction.setEnabled(false);
195             }
196             @Override
197             public void consoleIsNotEmptyAnymore() {
198                 clearAction.setEnabled(true);
199             }
200         });
201         
202         // Refresh action
203         toolBarManager.add(new Action(Messages.SCLConsoleView_RefreshModules, IAction.AS_DROP_DOWN_MENU) {
204             {
205                 setImageDescriptor(Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/arrow_refresh.png")); //$NON-NLS-1$ //$NON-NLS-2$
206                 setMenuCreator(new IMenuCreator() {
207                     Menu menu;
208                     @Override
209                     public Menu getMenu(Menu parent) {
210                         throw new UnsupportedOperationException();
211                     }
212                     
213                     @Override
214                     public Menu getMenu(Control parent) {
215                         if(menu == null) {
216                             menu = new Menu(parent);
217                             refreshAutomaticallyItem = new MenuItem(menu, SWT.CHECK);
218                             refreshAutomaticallyItem.setText(Messages.SCLConsoleView_RefreshAutomatically);
219                             refreshAutomaticallyItem.setSelection(refreshAutomatically);
220                             refreshAutomaticallyItem.addSelectionListener(new SelectionAdapter() {
221                                 @Override
222                                 public void widgetSelected(SelectionEvent e) {
223                                     setRefreshAutomatically(!refreshAutomatically, true);
224                                 }
225                             });
226                         }
227                         return menu;
228                     }
229                     
230                     @Override
231                     public void dispose() {
232                         if(menu != null)
233                             menu.dispose();
234                     }
235                 });
236             }
237             @Override
238             public void run() {
239                 console.getSession().getModuleRepository().getSourceRepository().checkUpdates();
240                 console.getSession().updateRuntimeEnvironment(true);
241                 console.appendOutput(Messages.SCLConsoleView_RefreshCompleted, console.greenColor, null);
242             }
243         });
244         toolBarManager.add(new Action(Messages.SCLConsoleView_ManageImports,
245                 Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/configure_imports.png")) { //$NON-NLS-1$ //$NON-NLS-2$
246             @Override
247             public void run() {
248                 manageImports();
249             }
250         });
251
252         // Show action for running SCL tests if in development mode
253         if (Platform.inDevelopmentMode()) {
254             toolBarManager.add(new Action(Messages.SCLConsoleView_RunTests,
255                     Activator.imageDescriptorFromPlugin("org.simantics.scl.ui", "icons/run_tests.png")) { //$NON-NLS-1$ //$NON-NLS-2$
256                 @Override
257                 public void run() {
258                     sclTestDialog();
259                 }
260             });
261         }
262         
263         toolBarManager.update(true);
264
265         setRefreshAutomatically(store.getBoolean(REFRESH_AUTOMATICALLY), false);
266         // Do this after the actions and SCLConsoleListener are
267         // registered because it can cause output to the console.
268         setCurrentImports(readImportPreferences());
269         addScriptDropSupport(console);
270     }
271
272     private class ScriptRunningDropTarget extends DropTargetAdapter {
273         @Override
274         public void dragEnter(DropTargetEvent event) {
275             if (event.detail == DND.DROP_DEFAULT) {
276                 event.detail = DND.DROP_LINK;
277             }
278         }
279
280         @Override
281         public void dragOperationChanged(DropTargetEvent event) {
282             if (event.detail == DND.DROP_DEFAULT) {
283                 event.detail = DND.DROP_LINK;
284             }
285         }
286
287         public void drop(DropTargetEvent event) {
288             if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) {
289                 String[] files = ((String[]) event.data).clone();
290                 // Sort files by name to allow deterministic multi-file drop
291                 Arrays.sort(files);
292                 for (String file : files) {
293                     Path p = Paths.get(file).toAbsolutePath();
294                     if (isScriptFile(p)) {
295                         console.execute("runFromFile \"" + p.toString().replace('\\', '/') + "\""); //$NON-NLS-1$ //$NON-NLS-2$
296                     }
297                 }
298             }
299         }
300
301         private boolean isScriptFile(Path p) {
302             return Files.isRegularFile(p)
303                     //&& p.toString().toLowerCase().endsWith(".scl")
304                     ;
305         }
306     }
307
308     private void addScriptDropSupport(SCLConsole console) {
309         DropTarget target = new DropTarget(console.getOutputWidget(), DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT);
310         target.setTransfer(new Transfer[] { FileTransfer.getInstance() });
311         target.addDropListener(new ScriptRunningDropTarget());
312     }
313
314     @Override
315     public void setFocus() {
316         console.setFocus();
317     }
318     
319     @Override
320     public void dispose() {
321         super.dispose();
322         console.dispose();
323     }
324
325     @SuppressWarnings("unchecked")
326     @Override
327     public <T> T getAdapter(Class<T> adapter) {
328         if (adapter == CommandSession.class)
329             return (T) console.getSession();
330         if (adapter == SCLReportingHandler.class)
331             return (T) console.getHandler();
332         return super.getAdapter(adapter);
333     }
334
335 }