() {
97 | @Override
98 | public Object call() throws Exception {
99 | final Object[] arguments = new Object[] { monitor };
100 | try {
101 | return function.call(cx, topLevelScope, topLevelScope, arguments);
102 | } catch (Throwable t) {
103 | handleExceptionFromScriptRuntime(t);
104 | return null;
105 | }
106 | }
107 | });
108 | }
109 | });
110 | if (functionReturnValue instanceof IStatus) {
111 | return (IStatus) functionReturnValue;
112 | } else if (functionReturnValue instanceof Boolean) {
113 | return (Boolean.TRUE.equals(functionReturnValue)) ? Status.OK_STATUS : Status.CANCEL_STATUS;
114 | }
115 | return Status.OK_STATUS;
116 | }
117 | };
118 | }
119 | return null;
120 | }
121 |
122 | @Override
123 | public void disableTimeout() {
124 | context.useTimeout = false;
125 | }
126 |
127 | @Override
128 | public void evaluate(IFile file, boolean nested) throws IOException {
129 | // Cleanup eventual error markers from last run of this file since it may now be fixed - if an error remains it
130 | // will be re-added later when it fails again:
131 | MarkerManager.clearMarkers(file);
132 |
133 | InputStreamReader reader = null;
134 | IFile previousFile = getExecutingFile();
135 | try {
136 | setExecutingFile(file);
137 | reader = new InputStreamReader(file.getContents(true), file.getCharset());
138 | String sourceName = file.getFullPath().toPortableString();
139 | Scriptable fileScope = nested ? topLevelScope : context.newObject(topLevelScope);
140 | context.evaluateReader(fileScope, reader, sourceName, 1, null);
141 | } catch (CoreException e) {
142 | throw new RuntimeException(e);
143 | } finally {
144 | setExecutingFile(previousFile);
145 | if (reader != null) {
146 | reader.close();
147 | }
148 | }
149 | }
150 |
151 | @Override
152 | public void exitRunningScript() {
153 | throw new ExitError();
154 | }
155 |
156 | @Override
157 | public IFile getExecutingFile() {
158 | return currentFile.get();
159 | }
160 |
161 | @Override
162 | public ScriptClassLoader getScriptClassLoader() {
163 | return (ScriptClassLoader) context.getApplicationClassLoader();
164 | }
165 |
166 | public void handleExceptionFromScriptRuntime(Throwable err) {
167 | if (err instanceof ExitError) {
168 | // do nothing, just exit quietly due to eclipse.runtime.exit() call
169 | } else if (err instanceof DieError) {
170 | DieError e = (DieError) err;
171 | RhinoException re = e.evalException;
172 | throw new ScriptException(e.getMessage(), re, re.sourceName(), re.lineNumber(), re.getScriptStackTrace(),
173 | false);
174 | } else if (err instanceof RhinoException) {
175 | RhinoException re = (RhinoException) err;
176 | boolean showStackTrace = (re instanceof WrappedException);
177 | Throwable cause = showStackTrace ? ((WrappedException) re).getCause() : re;
178 | throw new ScriptException(re.getMessage(), cause, re.sourceName(), re.lineNumber(),
179 | re.getScriptStackTrace(), showStackTrace);
180 | } else {
181 | if (err instanceof Error) {
182 | throw (Error) err;
183 | }
184 | throw JavaUtils.asRuntime(err);
185 | }
186 | }
187 |
188 | @Override
189 | public void setExecutingFile(IFile file) {
190 | currentFile.set(file);
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/messages/Messages.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.messages;
2 |
3 | import org.eclipse.osgi.util.NLS;
4 |
5 | /**
6 | * Localization messages using the {@link NLS} system. The static initializer block will initialize the fields of this
7 | * class with values loaded from the messages properties file.
8 | */
9 | public class Messages extends NLS {
10 |
11 | private static final String BUNDLE_NAME = Messages.class.getPackage().getName() + ".messages"; //$NON-NLS-1$
12 |
13 | public static String cannotRunCurrentScriptText;
14 | public static String cannotRunCurrentScriptTitle;
15 | public static String clearMarkersJobName;
16 | public static String fileToIncludeDoesNotExist;
17 | public static String fileToReadDoesNotExist;
18 | public static String internalErrorDialogDetails;
19 | public static String internalErrorDialogText;
20 | public static String internalErrorDialogTitle;
21 | public static String noDocumentSelected;
22 | public static String noSelectionSelected;
23 | public static String noTextEditorSelected;
24 | public static String notPossibleToScheduleObject;
25 | public static String removeAllTerminatedConsoles;
26 | public static String Resources_cannotReadFromObject;
27 | public static String runScriptBeforeRunningLast;
28 | public static String scriptAlertDialogTitle;
29 | public static String scriptBackgroundJobName;
30 | public static String scriptConfirmDialogTitle;
31 | public static String scriptConsoleName;
32 | public static String scriptErrorWhenRunningScriptDialogText;
33 | public static String scriptErrorWhenRunningScriptDialogTitle;
34 | public static String scriptErrorWhenRunningScriptJumpToScriptButton;
35 | public static String scriptErrorWhenRunningScriptOkButton;
36 | public static String scriptPromptDialogTitle;
37 | public static String scriptTimeout;
38 | public static String windowOpenArgumentNull;
39 |
40 | static {
41 | NLS.initializeMessages(BUNDLE_NAME, Messages.class);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/messages/messages.properties:
--------------------------------------------------------------------------------
1 | internalErrorDialogTitle=EclipseScript Internal Error
2 | internalErrorDialogText=The error has been logged. See below for details.
3 | internalErrorDialogDetails=Plug-in name: {0}\nPlug-in ID: {1}\nVersion: {2}\n\n{3}
4 | runScriptBeforeRunningLast=No EclipseScript script has been run\!
5 | scriptAlertDialogTitle=EclipseScript Alert
6 | scriptConfirmDialogTitle=EclipseScript Prompt
7 | scriptConsoleName=EclipseScript: {0}
8 | scriptErrorWhenRunningScriptDialogTitle=EclipseScript Error
9 | scriptErrorWhenRunningScriptDialogText=Execution of the script "{0}" failed at line {2} with the following message:\n\n{1}
10 | scriptErrorWhenRunningScriptJumpToScriptButton=&Go to script
11 | scriptErrorWhenRunningScriptOkButton=&Ok
12 | scriptTimeout = Script timeout after {0} seconds.\n\nTry using the eclipse.runtime.schedule(runnable) function for long-running background tasks.
13 | scriptBackgroundJobName=EclipseScript: {0}
14 | scriptPromptDialogTitle=EclipseScript Prompt
15 | cannotRunCurrentScriptText=Cannot run the currently edited script
16 | cannotRunCurrentScriptTitle=Cannot run
17 | clearMarkersJobName=Clear script markers
18 | fileToIncludeDoesNotExist=File does not exist:
19 | fileToReadDoesNotExist=File to read does not exist:
20 | noDocumentSelected=No document selected\!
21 | noSelectionSelected=No selection selected\!
22 | noTextEditorSelected=No text editor selected\!
23 | notPossibleToScheduleObject=Not possible to schedule object:
24 | Resources_cannotReadFromObject=Cannot read from object:
25 | windowOpenArgumentNull=The urlString argument to open(urlString) was null
26 | removeAllTerminatedConsoles=Remove All EclipseScript Consoles
--------------------------------------------------------------------------------
/src/org/eclipsescript/preferences/EclipseScriptPreferencePage.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.preferences;
2 |
3 | import org.eclipse.jface.preference.FieldEditorPreferencePage;
4 | import org.eclipse.jface.preference.IntegerFieldEditor;
5 | import org.eclipse.ui.IWorkbench;
6 | import org.eclipse.ui.IWorkbenchPreferencePage;
7 | import org.eclipsescript.core.Activator;
8 |
9 | /**
10 | * This class represents a preference page that is contributed to the Preferences dialog. By subclassing
11 | * FieldEditorPreferencePage , we can use the field support built into JFace that allows us to create a page
12 | * that is small and knows how to save, restore and apply itself.
13 | *
14 | * This page is used to modify preferences only. They are stored in the preference store that belongs to the main
15 | * plug-in class. That way, preferences can be accessed directly via the preference store.
16 | */
17 |
18 | public class EclipseScriptPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
19 |
20 | public EclipseScriptPreferencePage() {
21 | super(GRID);
22 | setPreferenceStore(Activator.getDefault().getPreferenceStore());
23 | setDescription(Messages.EclipseScriptPreferencePage_0);
24 | }
25 |
26 | /**
27 | * Creates the field editors. Field editors are abstractions of the common GUI blocks needed to manipulate various
28 | * types of preferences. Each field editor knows how to save and restore itself.
29 | */
30 | @Override
31 | public void createFieldEditors() {
32 | addField(new IntegerFieldEditor(PreferenceConstants.P_TIMEOUT, Messages.EclipseScriptPreferencePage_1,
33 | getFieldEditorParent()));
34 | }
35 |
36 | /*
37 | * (non-Javadoc)
38 | *
39 | * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
40 | */
41 | @Override
42 | public void init(IWorkbench workbench) {
43 | // nothing to do here
44 | }
45 |
46 | }
--------------------------------------------------------------------------------
/src/org/eclipsescript/preferences/Messages.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.preferences;
2 |
3 | import org.eclipse.osgi.util.NLS;
4 |
5 | public class Messages extends NLS {
6 | private static final String BUNDLE_NAME = "org.eclipsescript.preferences.messages"; //$NON-NLS-1$
7 | public static String EclipseScriptPreferencePage_0;
8 | public static String EclipseScriptPreferencePage_1;
9 | static {
10 | // initialize resource bundle
11 | NLS.initializeMessages(BUNDLE_NAME, Messages.class);
12 | }
13 |
14 | private Messages() {
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/preferences/PreferenceConstants.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.preferences;
2 |
3 | /**
4 | * Constant definitions for plug-in preferences
5 | */
6 | public class PreferenceConstants {
7 | public static final String P_TIMEOUT = "timeout"; //$NON-NLS-1$
8 | public static final int P_TIMEOUT_DEFAULT = 10;
9 | }
10 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/preferences/PreferenceInitializer.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.preferences;
2 |
3 | import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
4 | import org.eclipse.jface.preference.IPreferenceStore;
5 | import org.eclipsescript.core.Activator;
6 |
7 | /**
8 | * Class used to initialize default preference values.
9 | */
10 | public class PreferenceInitializer extends AbstractPreferenceInitializer {
11 |
12 | /*
13 | * (non-Javadoc)
14 | *
15 | * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
16 | */
17 | @Override
18 | public void initializeDefaultPreferences() {
19 | IPreferenceStore store = Activator.getDefault().getPreferenceStore();
20 | store.setDefault(PreferenceConstants.P_TIMEOUT, PreferenceConstants.P_TIMEOUT_DEFAULT);
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/preferences/messages.properties:
--------------------------------------------------------------------------------
1 | EclipseScriptPreferencePage_0=EclipseScript
2 | EclipseScriptPreferencePage_1=Script &timeout (seconds):
3 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scriptobjects/Console.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scriptobjects;
2 |
3 | import org.eclipse.jface.resource.ImageDescriptor;
4 | import org.eclipse.osgi.util.NLS;
5 | import org.eclipse.swt.widgets.Display;
6 | import org.eclipse.ui.console.ConsolePlugin;
7 | import org.eclipse.ui.console.IConsole;
8 | import org.eclipse.ui.console.IConsoleManager;
9 | import org.eclipse.ui.console.MessageConsole;
10 | import org.eclipse.ui.console.MessageConsoleStream;
11 | import org.eclipsescript.messages.Messages;
12 | import org.eclipsescript.scripts.IScriptRuntime;
13 | import org.eclipsescript.util.EclipseUtils;
14 | import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable;
15 |
16 | public class Console {
17 |
18 | // just a marker superclass for enablement in console closer, see plugin.xml
19 | public static class ConsoleClass extends MessageConsole {
20 | public boolean isDisposed = false;
21 |
22 | public ConsoleClass(String name, ImageDescriptor imageDescriptor) {
23 | super(name, imageDescriptor);
24 | }
25 |
26 | @Override
27 | protected void dispose() {
28 | isDisposed = true;
29 | super.dispose();
30 | }
31 |
32 | }
33 |
34 | private ConsoleClass console;
35 | private final String name;
36 | MessageConsoleStream out;
37 |
38 | public Console(IScriptRuntime runtime) {
39 | this.name = NLS.bind(Messages.scriptConsoleName, runtime.getExecutingFile().getName());
40 | }
41 |
42 | void init() {
43 | // Open a console for the first time or re-open
44 | if (console == null || console.isDisposed) {
45 | console = new ConsoleClass(name, null);
46 | out = console.newMessageStream();
47 | ConsolePlugin consolePlugin = ConsolePlugin.getDefault();
48 | IConsoleManager consoleManager = consolePlugin.getConsoleManager();
49 | consoleManager.addConsoles(new IConsole[] { console });
50 | consoleManager.showConsoleView(console);
51 | }
52 | }
53 |
54 | public void print(final String msg) throws Exception {
55 | EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() {
56 |
57 | @Override
58 | public void runWithDisplay(Display display) throws Exception {
59 | init();
60 | out.print(msg);
61 | }
62 |
63 | });
64 | }
65 |
66 | public void println(final String msg) throws Exception {
67 | EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() {
68 |
69 | @Override
70 | public void runWithDisplay(Display display) throws Exception {
71 | init();
72 | out.println(msg);
73 | }
74 |
75 | });
76 | }
77 |
78 | public void printStackTrace(final Throwable t) throws Exception {
79 | EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() {
80 |
81 | @Override
82 | public void runWithDisplay(Display display) throws Exception {
83 | init();
84 | out.println(t.getClass().getName());
85 | for (StackTraceElement stack : t.getStackTrace()) {
86 | out.println("\t at " + stack.toString()); //$NON-NLS-1$
87 | }
88 | }
89 |
90 | });
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scriptobjects/Eclipse.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scriptobjects;
2 |
3 | import org.eclipsescript.scripts.IScriptRuntime;
4 |
5 | public class Eclipse {
6 |
7 | public static final String VARIABLE_NAME = "eclipse"; //$NON-NLS-1$
8 |
9 | private final Console console;
10 | private final Editors editors;
11 | private final Resources resources;
12 | private final Runtime runtime;
13 | private final Window window;
14 | private final Xml xml;
15 |
16 | public Eclipse(IScriptRuntime scriptRuntime) {
17 | this.console = new Console(scriptRuntime);
18 | this.editors = new Editors();
19 | this.resources = new Resources(scriptRuntime);
20 | this.runtime = new Runtime(scriptRuntime);
21 | this.window = new Window();
22 | this.xml = new Xml(resources);
23 | }
24 |
25 | public Console getConsole() {
26 | return console;
27 | }
28 |
29 | public Editors getEditors() {
30 | return editors;
31 | }
32 |
33 | public Resources getResources() {
34 | return resources;
35 | }
36 |
37 | public Runtime getRuntime() {
38 | return runtime;
39 | }
40 |
41 | public Window getWindow() {
42 | return window;
43 | }
44 |
45 | public Xml getXml() {
46 | return xml;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scriptobjects/Editors.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scriptobjects;
2 |
3 | import org.eclipse.core.resources.IFile;
4 | import org.eclipse.jface.text.BadLocationException;
5 | import org.eclipse.jface.text.IDocument;
6 | import org.eclipse.jface.text.ITextSelection;
7 | import org.eclipse.jface.text.TextSelection;
8 | import org.eclipse.jface.viewers.ISelection;
9 | import org.eclipse.jface.viewers.ISelectionProvider;
10 | import org.eclipse.swt.custom.StyledText;
11 | import org.eclipse.swt.dnd.Clipboard;
12 | import org.eclipse.swt.dnd.TextTransfer;
13 | import org.eclipse.swt.dnd.Transfer;
14 | import org.eclipse.swt.widgets.Control;
15 | import org.eclipse.swt.widgets.Display;
16 | import org.eclipse.ui.IEditorDescriptor;
17 | import org.eclipse.ui.IEditorInput;
18 | import org.eclipse.ui.IEditorRegistry;
19 | import org.eclipse.ui.IWorkbench;
20 | import org.eclipse.ui.IWorkbenchPage;
21 | import org.eclipse.ui.PlatformUI;
22 | import org.eclipse.ui.part.FileEditorInput;
23 | import org.eclipse.ui.texteditor.IDocumentProvider;
24 | import org.eclipse.ui.texteditor.ITextEditor;
25 | import org.eclipsescript.messages.Messages;
26 | import org.eclipsescript.util.EclipseUtils;
27 | import org.eclipsescript.util.EclipseUtils.DisplayThreadCallable;
28 | import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable;
29 | import org.eclipsescript.util.JavaUtils.MutableObject;
30 |
31 | public class Editors {
32 |
33 | public String getClipboard() throws Exception {
34 | final MutableObject result = new MutableObject();
35 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
36 | @Override
37 | public void runWithDisplay(Display display) {
38 | Clipboard clipboard = new Clipboard(display);
39 | try {
40 | result.value = (String) clipboard.getContents(TextTransfer.getInstance());
41 | } finally {
42 | clipboard.dispose();
43 | }
44 | }
45 | });
46 | return result.value;
47 | }
48 |
49 | /** Returns the currently edited document or null if none. */
50 | public IDocument getDocument() throws Exception {
51 | return EclipseUtils.runInDisplayThreadSync(new DisplayThreadCallable() {
52 | @Override
53 | public IDocument callWithDisplay(Display display) throws Exception {
54 | return EclipseUtils.getCurrentDocument();
55 | }
56 | });
57 | }
58 |
59 | /** Returns the currently edited file or null if none. */
60 | public IFile getFile() throws Exception {
61 | return EclipseUtils.runInDisplayThreadSync(new DisplayThreadCallable() {
62 | @Override
63 | public IFile callWithDisplay(Display display) throws Exception {
64 | IEditorInput editorInput = EclipseUtils.getCurrentEditorInput();
65 | IFile fileEditorInput = null;
66 | if (editorInput != null) {
67 | fileEditorInput = editorInput.getAdapter(IFile.class);
68 | }
69 | return fileEditorInput;
70 | }
71 | });
72 | }
73 |
74 | /**
75 | * Returns the current text selection or null if none.
76 | */
77 | public ITextSelection getSelection() throws Exception {
78 | return EclipseUtils.runInDisplayThreadSync(new DisplayThreadCallable() {
79 | @Override
80 | public ITextSelection callWithDisplay(Display display) throws Exception {
81 | ITextEditor editor = EclipseUtils.getCurrentTextEditor();
82 | if (editor == null)
83 | return null;
84 | ISelectionProvider provider = editor.getSelectionProvider();
85 | if (provider == null)
86 | return null;
87 | ISelection selection = provider.getSelection();
88 | if (!(selection instanceof ITextSelection))
89 | return null;
90 | return (ITextSelection) selection;
91 | }
92 | });
93 | }
94 |
95 | public void insert(final String textToInsert) throws Exception {
96 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
97 | @Override
98 | public void runWithDisplay(Display display) throws BadLocationException {
99 |
100 | ITextEditor editor = EclipseUtils.getCurrentTextEditor();
101 | if (editor == null)
102 | throw new IllegalArgumentException(Messages.noTextEditorSelected);
103 | IDocument document = EclipseUtils.getCurrentDocument();
104 | if (document == null)
105 | throw new IllegalArgumentException(Messages.noDocumentSelected);
106 |
107 | StyledText styledText = (StyledText) editor.getAdapter(Control.class);
108 | int offset = styledText.getCaretOffset();
109 | document.replace(offset, 0, textToInsert);
110 | }
111 | });
112 | }
113 |
114 | public void open(final IFile file) throws Exception {
115 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
116 | @Override
117 | public void runWithDisplay(Display display) throws Exception {
118 |
119 | IWorkbench workbench = PlatformUI.getWorkbench();
120 | IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
121 |
122 | IEditorRegistry editorRegistry = PlatformUI.getWorkbench().getEditorRegistry();
123 | IEditorDescriptor editorDescriptor = editorRegistry.getDefaultEditor(file.getName());
124 |
125 | if (editorDescriptor == null) {
126 | // there is no default editor for the file, use text editor
127 | editorDescriptor = editorRegistry.getDefaultEditor("1.txt"); //$NON-NLS-1$
128 | }
129 |
130 | activePage.openEditor(new FileEditorInput(file), editorDescriptor.getId());
131 |
132 | }
133 | });
134 | }
135 |
136 | public void replaceSelection(final String newText) throws Exception {
137 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
138 | @Override
139 | public void runWithDisplay(Display display) throws Exception {
140 | TextSelection selection = EclipseUtils.getCurrentEditorSelection();
141 | if (selection == null)
142 | throw new IllegalArgumentException(Messages.noSelectionSelected);
143 | ITextEditor editor = EclipseUtils.getCurrentTextEditor();
144 | if (editor == null)
145 | throw new IllegalArgumentException(Messages.noTextEditorSelected);
146 | IDocumentProvider documentProvider = editor.getDocumentProvider();
147 | IDocument document = documentProvider.getDocument(editor.getEditorInput());
148 | if (document == null)
149 | throw new IllegalArgumentException(Messages.noDocumentSelected);
150 | document.replace(selection.getOffset(), selection.getLength(), newText);
151 | editor.selectAndReveal(selection.getOffset(), newText.length());
152 | }
153 | });
154 | }
155 |
156 | public void setClipboard(final String text) throws Exception {
157 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
158 | @Override
159 | public void runWithDisplay(Display display) {
160 | Clipboard clipboard = new Clipboard(display);
161 | try {
162 | clipboard.setContents(new Object[] { text }, new Transfer[] { TextTransfer.getInstance() });
163 | } finally {
164 | clipboard.dispose();
165 | }
166 | }
167 | });
168 | }
169 |
170 | }
171 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scriptobjects/Resources.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scriptobjects;
2 |
3 | import static java.util.regex.Pattern.compile;
4 |
5 | import java.io.InputStream;
6 | import java.io.Reader;
7 | import java.net.URL;
8 | import java.net.URLConnection;
9 | import java.util.ArrayList;
10 | import java.util.Collection;
11 | import java.util.List;
12 | import java.util.regex.Matcher;
13 | import java.util.regex.Pattern;
14 |
15 | import org.eclipse.core.resources.IContainer;
16 | import org.eclipse.core.resources.IFile;
17 | import org.eclipse.core.resources.IProject;
18 | import org.eclipse.core.resources.IResource;
19 | import org.eclipse.core.resources.IWorkspace;
20 | import org.eclipse.core.resources.ResourcesPlugin;
21 | import org.eclipse.core.runtime.CoreException;
22 | import org.eclipse.core.runtime.Path;
23 | import org.eclipse.ui.IEditorInput;
24 | import org.eclipse.ui.IEditorPart;
25 | import org.eclipse.ui.IWorkbench;
26 | import org.eclipse.ui.IWorkbenchPage;
27 | import org.eclipse.ui.IWorkbenchWindow;
28 | import org.eclipse.ui.PlatformUI;
29 | import org.eclipsescript.messages.Messages;
30 | import org.eclipsescript.scripts.IScriptRuntime;
31 | import org.eclipsescript.util.JavaUtils;
32 |
33 | public class Resources {
34 |
35 | private final IScriptRuntime scriptRuntime;
36 |
37 | public Resources(IScriptRuntime scriptRuntime) {
38 | this.scriptRuntime = scriptRuntime;
39 | }
40 |
41 | public IFile[] filesMatching(final String patternString, IResource startingPoint) {
42 | final Pattern pattern = compile(patternString);
43 | final List result = new ArrayList();
44 | try {
45 | walk(startingPoint, pattern, result);
46 | } catch (final CoreException x) {
47 | // ignore Eclipse internal errors
48 | }
49 | return result.toArray(new IFile[result.size()]);
50 | }
51 |
52 | /** Get the currently selected project. */
53 | public IProject getCurrentProject() {
54 | IWorkbench workbench = PlatformUI.getWorkbench();
55 | IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
56 | if (window == null) {
57 | IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
58 | if (windows != null) {
59 | window = windows[0];
60 | }
61 | }
62 | if (window == null)
63 | return null;
64 | IWorkbenchPage activePage = window.getActivePage();
65 | if (activePage == null)
66 | return null;
67 | IEditorPart activeEditor = activePage.getActiveEditor();
68 | if (activeEditor == null)
69 | return null;
70 | IEditorInput editorInput = activeEditor.getEditorInput();
71 | if (editorInput == null)
72 | return null;
73 | IResource resource = (IResource) editorInput.getAdapter(IResource.class);
74 | if (resource == null)
75 | return null;
76 | return resource.getProject();
77 | }
78 |
79 | // note that exists() should be called to determine existence
80 | public IProject getProject(String projectName) {
81 | return ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
82 | }
83 |
84 | /** Get the project of the currently executing script. */
85 | public IProject getScriptProject() {
86 | if (scriptRuntime == null)
87 | return null;
88 | if (scriptRuntime.getExecutingFile() == null)
89 | return null;
90 | return scriptRuntime.getExecutingFile().getProject();
91 | }
92 |
93 | public IWorkspace getWorkspace() {
94 | return ResourcesPlugin.getWorkspace();
95 | }
96 |
97 | public String read(Object objectToRead) throws Exception {
98 | if (objectToRead instanceof IFile) {
99 | IFile file = (IFile) objectToRead;
100 | return JavaUtils.readAllToStringAndClose(file.getContents(true), file.getCharset());
101 | } else if (objectToRead instanceof URLConnection) {
102 | URLConnection uc = (URLConnection) objectToRead;
103 | return JavaUtils.readURLConnection(uc);
104 | } else if (objectToRead instanceof URL) {
105 | URL url = (URL) objectToRead;
106 | return JavaUtils.readURL(url);
107 | } else if (objectToRead instanceof String) {
108 | String string = (String) objectToRead;
109 | if (string.contains("://")) { //$NON-NLS-1$
110 | URL url = new URL(string);
111 | return JavaUtils.readURL(url);
112 | } else {
113 | Path includePath = new Path(string);
114 | IContainer parent = string.startsWith("/") ? scriptRuntime.getExecutingFile().getProject() //$NON-NLS-1$
115 | : scriptRuntime.getExecutingFile().getParent();
116 | IFile fileToRead = parent.getFile(includePath);
117 | if (!fileToRead.exists())
118 | scriptRuntime.abortRunningScript(Messages.fileToReadDoesNotExist
119 | + fileToRead.getFullPath().toOSString());
120 | return JavaUtils.readAllToStringAndClose(fileToRead.getContents(true), fileToRead.getCharset());
121 | }
122 | } else if (objectToRead instanceof Reader) {
123 | Reader in = (Reader) objectToRead;
124 | return JavaUtils.readAllToStringAndClose(in);
125 | } else if (objectToRead instanceof InputStream) {
126 | InputStream in = (InputStream) objectToRead;
127 | return JavaUtils.readAllToStringAndClose(in);
128 | }
129 | throw new IllegalArgumentException(Messages.Resources_cannotReadFromObject + objectToRead);
130 | }
131 |
132 | private void walk(final IResource resource, final Pattern pattern, final Collection result)
133 | throws CoreException {
134 | if (resource instanceof IProject) {
135 | final IProject project = (IProject) resource;
136 | if (!project.isOpen())
137 | return;
138 | final IResource[] children = project.members();
139 | for (final IResource resource2 : children)
140 | walk(resource2, pattern, result);
141 | } else if (resource instanceof IContainer) {
142 | final IResource[] children = ((IContainer) resource).members();
143 | for (final IResource resource2 : children) {
144 | walk(resource2, pattern, result);
145 | }
146 | } else if (resource instanceof IFile) {
147 | final String path = resource.getFullPath().toString();
148 | final Matcher match = pattern.matcher(path);
149 | if (match.matches())
150 | result.add((IFile) resource);
151 | }
152 | }
153 | }
154 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scriptobjects/Runtime.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scriptobjects;
2 |
3 | import java.io.IOException;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | import org.eclipse.core.resources.IContainer;
8 | import org.eclipse.core.resources.IFile;
9 | import org.eclipse.core.resources.WorkspaceJob;
10 | import org.eclipse.core.runtime.IProgressMonitor;
11 | import org.eclipse.core.runtime.IStatus;
12 | import org.eclipse.core.runtime.Path;
13 | import org.eclipse.core.runtime.jobs.Job;
14 | import org.eclipse.osgi.util.NLS;
15 | import org.eclipse.swt.widgets.Shell;
16 | import org.eclipse.ui.IWorkbench;
17 | import org.eclipse.ui.PlatformUI;
18 | import org.eclipse.ui.progress.IJobRunnable;
19 | import org.eclipsescript.core.Activator;
20 | import org.eclipsescript.messages.Messages;
21 | import org.eclipsescript.scripts.IScriptRuntime;
22 | import org.eclipsescript.util.EclipseUtils;
23 |
24 | /**
25 | * Object which is put under eclipse.runtime
in the script scope containing methods for manipulating the
26 | * currently executing scripts runtime.
27 | */
28 | public class Runtime {
29 |
30 | private static final Map globals = new HashMap();
31 | private final IScriptRuntime scriptRuntime;
32 |
33 | public Runtime(IScriptRuntime scriptRuntime) {
34 | this.scriptRuntime = scriptRuntime;
35 | }
36 |
37 | public void asyncExec(Runnable runnable) {
38 | IWorkbench workbench = PlatformUI.getWorkbench();
39 | workbench.getDisplay().asyncExec(runnable);
40 | }
41 |
42 | public void die(String message) {
43 | scriptRuntime.abortRunningScript(message);
44 | }
45 |
46 | public void disableTimeout() {
47 | scriptRuntime.disableTimeout();
48 | }
49 |
50 | public void exec(String command) {
51 | try {
52 | java.lang.Runtime.getRuntime().exec(command);
53 | } catch (IOException e) {
54 | Activator.logError(e);
55 | }
56 | }
57 |
58 | public void exit() {
59 | scriptRuntime.exitRunningScript();
60 | }
61 |
62 | public synchronized Object getGlobal(String key) {
63 | return globals.get(key);
64 | }
65 |
66 | public Shell getShell() {
67 | return EclipseUtils.getWindowShell();
68 | }
69 |
70 | public void include(Object... includes) throws Exception {
71 | for (Object includeObject : includes) {
72 | IFile fileToInclude;
73 | if (includeObject instanceof IFile) {
74 | fileToInclude = (IFile) includeObject;
75 | } else {
76 | String includeStringPath = (String) includeObject;
77 | Path includePath = new Path(includeStringPath);
78 | IFile executingScriptFile = scriptRuntime.getExecutingFile();
79 | IContainer startingScriptContainer = executingScriptFile.getParent();
80 | if (includePath.isAbsolute()) {
81 | fileToInclude = startingScriptContainer.getWorkspace().getRoot().getFile(includePath);
82 | } else {
83 | fileToInclude = startingScriptContainer.getFile(includePath);
84 | }
85 | }
86 | if (!fileToInclude.exists())
87 | scriptRuntime.abortRunningScript(
88 | Messages.fileToIncludeDoesNotExist + fileToInclude.getFullPath().toOSString());
89 | scriptRuntime.evaluate(fileToInclude, true);
90 | }
91 | }
92 |
93 | public synchronized void putGlobal(String key, Object value) {
94 | globals.put(key, value);
95 | }
96 |
97 | public void schedule(final Object objectToSchedule) {
98 | final IJobRunnable runnable = scriptRuntime.adaptTo(objectToSchedule, IJobRunnable.class);
99 | if (runnable == null)
100 | throw new IllegalArgumentException(Messages.notPossibleToScheduleObject + objectToSchedule);
101 | String jobName = NLS.bind(Messages.scriptBackgroundJobName, scriptRuntime.getExecutingFile().getName());
102 | final IScriptRuntime runtime = scriptRuntime;
103 | final IFile executingFile = scriptRuntime.getExecutingFile();
104 | Job job = new WorkspaceJob(jobName) {
105 | @Override
106 | public IStatus runInWorkspace(IProgressMonitor monitor) {
107 | runtime.setExecutingFile(executingFile);
108 | return runnable.run(monitor);
109 | }
110 | };
111 | job.setSystem(false);
112 | job.setUser(true);
113 | job.schedule();
114 | }
115 |
116 | public void syncExec(Runnable runnable) {
117 | IWorkbench workbench = PlatformUI.getWorkbench();
118 | workbench.getDisplay().syncExec(runnable);
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scriptobjects/Window.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scriptobjects;
2 |
3 | import java.net.MalformedURLException;
4 | import java.net.URL;
5 |
6 |
7 | import org.eclipse.jface.action.IStatusLineManager;
8 | import org.eclipse.jface.dialogs.Dialog;
9 | import org.eclipse.jface.dialogs.MessageDialog;
10 | import org.eclipse.swt.SWT;
11 | import org.eclipse.swt.layout.GridData;
12 | import org.eclipse.swt.layout.GridLayout;
13 | import org.eclipse.swt.widgets.Composite;
14 | import org.eclipse.swt.widgets.Control;
15 | import org.eclipse.swt.widgets.Display;
16 | import org.eclipse.swt.widgets.Label;
17 | import org.eclipse.swt.widgets.Shell;
18 | import org.eclipse.swt.widgets.Text;
19 | import org.eclipse.ui.IActionBars;
20 | import org.eclipse.ui.IEditorSite;
21 | import org.eclipse.ui.IViewSite;
22 | import org.eclipse.ui.IWorkbench;
23 | import org.eclipse.ui.IWorkbenchPage;
24 | import org.eclipse.ui.IWorkbenchPart;
25 | import org.eclipse.ui.IWorkbenchPartSite;
26 | import org.eclipse.ui.PartInitException;
27 | import org.eclipse.ui.PlatformUI;
28 | import org.eclipse.ui.browser.IWebBrowser;
29 | import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
30 | import org.eclipsescript.messages.Messages;
31 | import org.eclipsescript.util.EclipseUtils;
32 | import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable;
33 | import org.eclipsescript.util.JavaUtils.MutableObject;
34 |
35 | public class Window {
36 |
37 | private static class PromptDialog extends Dialog {
38 |
39 | private final String promptText;
40 | Text promptField;
41 | String enteredText;
42 |
43 | public PromptDialog(Shell parentShell, String promptText) {
44 | super(parentShell);
45 | this.promptText = promptText;
46 | }
47 |
48 | @Override
49 | public boolean close() {
50 | enteredText = promptField.getText();
51 | return super.close();
52 | }
53 |
54 | @Override
55 | protected Control createDialogArea(Composite parent) {
56 | Composite container = (Composite) super.createDialogArea(parent);
57 | final GridLayout gridLayout = new GridLayout();
58 | gridLayout.numColumns = 1;
59 | container.setLayout(gridLayout);
60 |
61 | final Label nameLabel = new Label(container, SWT.NONE);
62 | nameLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
63 | nameLabel.setText(promptText + ":"); //$NON-NLS-1$
64 |
65 | promptField = new Text(container, SWT.BORDER);
66 | promptField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
67 | promptField.setText(""); //$NON-NLS-1$
68 |
69 | return container;
70 | }
71 |
72 | }
73 |
74 | public static void alert(final String message) throws Exception {
75 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
76 | @Override
77 | public void runWithDisplay(Display display) {
78 | MessageDialog.openInformation(EclipseUtils.activeWindow().getShell(), Messages.scriptAlertDialogTitle,
79 | message);
80 | }
81 | });
82 | }
83 |
84 | public static boolean confirm(final String message) throws Exception {
85 | final MutableObject enteredText = new MutableObject();
86 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
87 | @Override
88 | public void runWithDisplay(Display display) {
89 | enteredText.value = MessageDialog.openConfirm(EclipseUtils.getWindowShell(),
90 | Messages.scriptConfirmDialogTitle, message);
91 | }
92 | });
93 | return enteredText.value;
94 | }
95 |
96 | public static IWebBrowser open(String urlString) throws PartInitException, MalformedURLException {
97 | if (urlString == null)
98 | throw new IllegalArgumentException(Messages.windowOpenArgumentNull);
99 | URL url = new URL(urlString);
100 | IWorkbench workbench = PlatformUI.getWorkbench();
101 | IWorkbenchBrowserSupport browserSupport = workbench.getBrowserSupport();
102 | IWebBrowser browser = browserSupport.createBrowser(IWorkbenchBrowserSupport.AS_EXTERNAL, null, null, null);
103 | browser.openURL(url);
104 | return browser;
105 | }
106 |
107 | public static String prompt(final String message) throws Exception {
108 | return prompt(message, ""); //$NON-NLS-1$
109 | }
110 |
111 | public static String prompt(final String message, final String initialValue) throws Exception {
112 | final MutableObject enteredText = new MutableObject();
113 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
114 | @Override
115 | public void runWithDisplay(Display display) {
116 | final PromptDialog dialog = new PromptDialog(EclipseUtils.getWindowShell(), message);
117 |
118 | // create the window shell so the title can be set
119 | dialog.create();
120 | dialog.getShell().setText(Messages.scriptPromptDialogTitle);
121 | if (initialValue != null) {
122 | dialog.promptField.setText(initialValue);
123 | }
124 | // since the Window has the blockOnOpen property set to true, it
125 | // will dipose of the shell upon close
126 | if (dialog.open() == org.eclipse.jface.window.Window.OK) {
127 | enteredText.value = dialog.enteredText;
128 | }
129 | }
130 | });
131 | return enteredText.value;
132 | }
133 |
134 | public void setStatus(final String status) throws Exception {
135 | EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() {
136 | @Override
137 | public void runWithDisplay(Display display) {
138 | IWorkbenchPage page = EclipseUtils.activePage();
139 | IWorkbenchPart part = page.getActivePart();
140 | IWorkbenchPartSite site = part.getSite();
141 | IActionBars actionBars = null;
142 | if (site instanceof IEditorSite) {
143 | IEditorSite editorSite = (IEditorSite) site;
144 | actionBars = editorSite.getActionBars();
145 | } else if (site instanceof IViewSite) {
146 | IViewSite viewSite = (IViewSite) site;
147 | actionBars = viewSite.getActionBars();
148 | }
149 | if (actionBars == null)
150 | return;
151 | IStatusLineManager statusLineManager = actionBars.getStatusLineManager();
152 | if (statusLineManager == null)
153 | return;
154 | statusLineManager.setMessage(status);
155 | }
156 | });
157 | }
158 |
159 | }
160 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scriptobjects/Xml.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scriptobjects;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | import javax.xml.parsers.DocumentBuilder;
8 | import javax.xml.parsers.DocumentBuilderFactory;
9 | import javax.xml.xpath.XPath;
10 | import javax.xml.xpath.XPathConstants;
11 | import javax.xml.xpath.XPathFactory;
12 |
13 | import org.w3c.dom.Document;
14 | import org.w3c.dom.Element;
15 | import org.w3c.dom.NodeList;
16 |
17 | public class Xml {
18 |
19 | private final Resources resources;
20 |
21 | public Xml(Resources resources) {
22 | this.resources = resources;
23 | }
24 |
25 | public Document parse(Object sourceObject) throws Exception {
26 | String source;
27 | if (sourceObject instanceof String) {
28 | source = (String) sourceObject;
29 | } else {
30 | source = resources.read(sourceObject);
31 | }
32 | DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
33 | builderFactory.setValidating(false);
34 | builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); //$NON-NLS-1$
35 | DocumentBuilder builder = builderFactory.newDocumentBuilder();
36 | return builder.parse(new ByteArrayInputStream(source.getBytes("utf-8"))); //$NON-NLS-1$
37 | }
38 |
39 | public List xpath(Document doc, String expression) throws Exception {
40 | XPathFactory factory = XPathFactory.newInstance();
41 | XPath xpath = factory.newXPath();
42 | NodeList resultNodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
43 | List resultList = new ArrayList(resultNodeList.getLength());
44 | for (int i = 0; i < resultNodeList.getLength(); i++) {
45 | resultList.add((Element) resultNodeList.item(i));
46 | }
47 | return resultList;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scripts/IScriptLanguageSupport.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scripts;
2 |
3 | public interface IScriptLanguageSupport {
4 |
5 | /**
6 | * Execute all scripts in the same contexts.
7 | */
8 | public void executeScript(ScriptMetadata script);
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scripts/IScriptRuntime.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scripts;
2 |
3 | import java.io.IOException;
4 |
5 | import org.eclipse.core.resources.IFile;
6 |
7 | public interface IScriptRuntime {
8 |
9 | public void abortRunningScript(String errorMessage);
10 |
11 | public T adaptTo(Object object, Class clazz);
12 |
13 | public void disableTimeout();
14 |
15 | public void evaluate(IFile file, boolean nested) throws IOException;
16 |
17 | public void exitRunningScript();
18 |
19 | public IFile getExecutingFile();
20 |
21 | public ScriptClassLoader getScriptClassLoader();
22 |
23 | public void setExecutingFile(IFile file);
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scripts/MarkerManager.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scripts;
2 |
3 | import org.eclipse.core.resources.IFile;
4 | import org.eclipse.core.resources.IMarker;
5 | import org.eclipse.core.resources.IResource;
6 | import org.eclipse.core.runtime.CoreException;
7 | import org.eclipsescript.core.Activator;
8 |
9 | public class MarkerManager {
10 |
11 | private static final String SCRIPT_PROBLEM_MARKER_TYPE = "org.eclipsescript.scriptproblemmarker"; //$NON-NLS-1$
12 |
13 | public static void addMarker(IFile file, ScriptException error) {
14 | try {
15 | IMarker m = file.createMarker(SCRIPT_PROBLEM_MARKER_TYPE);
16 | if (error.getLineNumber() > 0) {
17 | m.setAttribute(IMarker.LINE_NUMBER, error.getLineNumber());
18 | }
19 | m.setAttribute(IMarker.MESSAGE, error.getMessage());
20 | m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
21 | m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
22 | // TODO: ? "If we indicated additional information in the marker for IMarker.CHAR_START and
23 | // IMarker.CHAR_END, the
24 | // editor will also draw a red squiggly line under the offending problem"
25 | } catch (CoreException e) {
26 | Activator.logError(e);
27 | }
28 | }
29 |
30 | public static void clearMarkers(IFile file) {
31 | try {
32 | file.deleteMarkers(SCRIPT_PROBLEM_MARKER_TYPE, true, IResource.DEPTH_INFINITE);
33 | } catch (CoreException e) {
34 | Activator.logError(e);
35 | }
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scripts/ScriptClassLoader.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scripts;
2 |
3 | import java.util.List;
4 | import java.util.concurrent.CopyOnWriteArrayList;
5 |
6 | import org.eclipsescript.core.Activator;
7 | import org.osgi.framework.Bundle;
8 |
9 | public class ScriptClassLoader extends ClassLoader {
10 |
11 | private final List bundles = new CopyOnWriteArrayList();
12 | private final ClassLoader loader;
13 | private final List loaders = new CopyOnWriteArrayList();
14 |
15 | public ScriptClassLoader(ClassLoader loader) {
16 | this.loader = loader;
17 | }
18 |
19 | public void addBundle(Bundle bundle) {
20 | // note that this requires script to load bundles in dependant order...
21 | bundles.add(0, bundle);
22 | }
23 |
24 | public void addLoader(ClassLoader classLoader) {
25 | // note that this requires script to load bundles in dependant order...
26 | loaders.add(0, classLoader);
27 | }
28 |
29 | @Override
30 | public Class> loadClass(String name) throws ClassNotFoundException {
31 | try {
32 | return loader.loadClass(name);
33 | } catch (ClassNotFoundException e) {
34 | // ignore
35 | }
36 |
37 | for (Bundle bundle : bundles) {
38 | try {
39 | return bundle.loadClass(name);
40 | } catch (ClassNotFoundException e) {
41 | // ignore
42 | }
43 | }
44 |
45 | for (ClassLoader classLoader : loaders) {
46 | try {
47 | return classLoader.loadClass(name);
48 | } catch (ClassNotFoundException e) {
49 | // ignore
50 | }
51 | }
52 |
53 | Bundle bundleContainingClass = Activator.getBundleExportingClass(name);
54 | if (bundleContainingClass != null) {
55 | try {
56 | Class> clazz = bundleContainingClass.loadClass(name);
57 | addBundle(bundleContainingClass);
58 | return clazz;
59 | } catch (ClassNotFoundException e) {
60 | // handle classes in "split-packages" see http://wiki.osgi.org/wiki/Split_Packages
61 | Bundle[] bundlesExportingPackage = Activator.getBundlesExportingPackage(name);
62 | for (Bundle bundle : bundlesExportingPackage) {
63 | try {
64 | Class> clazz = bundle.loadClass(name);
65 | addBundle(bundle);
66 | return clazz;
67 | } catch (ClassNotFoundException e1) {
68 | continue;
69 | }
70 | }
71 | }
72 | }
73 |
74 | return null;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scripts/ScriptException.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scripts;
2 |
3 | public class ScriptException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = 1L;
6 |
7 | private final int lineNumber;
8 | private final String scriptStackTrace;
9 | private final String sourceName;
10 |
11 | /**
12 | * @param scriptStackTrace
13 | * @param showStackTrace
14 | * not used at the moment, it could perhaps always be useful with stack trace?
15 | */
16 | public ScriptException(String message, Throwable cause, String sourceName, int lineNumber, String scriptStackTrace,
17 | boolean showStackTrace) {
18 | super(message, cause);
19 | this.lineNumber = lineNumber;
20 | this.sourceName = sourceName;
21 | this.scriptStackTrace = scriptStackTrace;
22 | }
23 |
24 | public int getLineNumber() {
25 | return lineNumber;
26 | }
27 |
28 | public String getScriptStackTrace() {
29 | return scriptStackTrace;
30 | }
31 |
32 | public String getSourceName() {
33 | return sourceName;
34 | }
35 |
36 | public boolean isShowStackTrace() {
37 | return true;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scripts/ScriptLanguageHandler.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scripts;
2 |
3 | import java.util.Collections;
4 | import java.util.Map;
5 |
6 | import org.eclipse.core.resources.IFile;
7 | import org.eclipsescript.javascript.JavaScriptLanguageSupport;
8 |
9 | public class ScriptLanguageHandler {
10 |
11 | public static Map getLanguageSupports() {
12 | return Collections.singletonMap("js", new JavaScriptLanguageSupport()); //$NON-NLS-1$
13 | }
14 |
15 | static IScriptLanguageSupport getScriptSupport(IFile file) {
16 | String fileName = file.getName();
17 | int index = -1;
18 | int len = 14;
19 | index = fileName.lastIndexOf(".eclipse.auto."); //$NON-NLS-1$
20 | if (index == -1) {
21 | len = 9;
22 | index = fileName.lastIndexOf(".eclipse."); //$NON-NLS-1$
23 | }
24 | if (index == -1)
25 | return null;
26 | String fileExtension = fileName.substring(index + len);
27 | return getLanguageSupports().get(fileExtension);
28 | }
29 |
30 | public static boolean isEclipseScriptFile(IFile file) {
31 | return getScriptSupport(file) != null;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scripts/ScriptMetadata.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scripts;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.InputStreamReader;
5 | import java.util.concurrent.atomic.AtomicInteger;
6 |
7 |
8 | import org.eclipse.core.resources.IFile;
9 | import org.eclipsescript.core.Activator;
10 |
11 | public class ScriptMetadata implements Comparable {
12 |
13 | private static final AtomicInteger counter = new AtomicInteger();
14 |
15 | private final IFile file;
16 | private final int instanceId;
17 | private final String label;
18 |
19 | public ScriptMetadata(IFile file) {
20 | this.instanceId = counter.getAndIncrement();
21 | this.file = file;
22 |
23 | String fileName = file.getName();
24 | int index = fileName.lastIndexOf(".eclipse."); //$NON-NLS-1$
25 | String scriptName = fileName.substring(0, index);
26 |
27 | String firstLine = null;
28 | try {
29 | BufferedReader reader = new BufferedReader(new InputStreamReader(file.getContents(true), file.getCharset()));
30 | try {
31 | firstLine = reader.readLine();
32 | } finally {
33 | reader.close();
34 | }
35 | } catch (Exception e) {
36 | Activator.logError(e);
37 | }
38 |
39 | if (firstLine == null) {
40 | label = scriptName;
41 | } else {
42 | firstLine = firstLine.trim();
43 | if (firstLine.startsWith("//") || firstLine.startsWith("/*")) { //$NON-NLS-1$ //$NON-NLS-2$
44 | this.label = scriptName + " - " + firstLine.substring(2).trim(); //$NON-NLS-1$
45 | } else {
46 | this.label = scriptName;
47 | }
48 | }
49 | }
50 |
51 | @Override
52 | public int compareTo(ScriptMetadata o) {
53 | return instanceId - o.instanceId;
54 | }
55 |
56 | @Override
57 | public boolean equals(Object other) {
58 | return (other instanceof ScriptMetadata) && ((ScriptMetadata) other).instanceId == instanceId;
59 | }
60 |
61 | public IFile getFile() {
62 | return file;
63 | }
64 |
65 | public String getFullPath() {
66 | return file.getFullPath().toString();
67 | }
68 |
69 | public String getLabel() {
70 | return label;
71 | }
72 |
73 | @Override
74 | public int hashCode() {
75 | return instanceId;
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/scripts/ScriptStore.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.scripts;
2 |
3 | import java.util.concurrent.Callable;
4 |
5 | import org.eclipse.core.resources.IFile;
6 | import org.eclipse.core.runtime.IPath;
7 | import org.eclipse.core.runtime.Path;
8 | import org.eclipse.jface.text.BadLocationException;
9 | import org.eclipse.jface.text.IDocument;
10 | import org.eclipse.osgi.util.NLS;
11 | import org.eclipse.swt.widgets.Display;
12 | import org.eclipse.ui.IEditorPart;
13 | import org.eclipse.ui.IWorkbenchPage;
14 | import org.eclipse.ui.texteditor.IDocumentProvider;
15 | import org.eclipse.ui.texteditor.ITextEditor;
16 | import org.eclipsescript.core.Activator;
17 | import org.eclipsescript.core.RunLastHandler;
18 | import org.eclipsescript.messages.Messages;
19 | import org.eclipsescript.ui.ErrorDetailsDialog;
20 | import org.eclipsescript.util.EclipseUtils;
21 | import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable;
22 |
23 | public class ScriptStore {
24 |
25 | public static T executeRunnableWhichMayThrowScriptException(final ScriptMetadata script, Callable r) {
26 | try {
27 | try {
28 | return r.call();
29 | } catch (final ScriptException error) {
30 | IFile file = getFile(script, error);
31 | MarkerManager.addMarker(file, error);
32 | EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() {
33 | @Override
34 | public void runWithDisplay(Display display) throws Exception {
35 | showMessageOfferJumpToScript(script, error);
36 | }
37 | });
38 | }
39 | } catch (Exception e) {
40 | Activator.logError(e);
41 | }
42 | return null;
43 | }
44 |
45 | public static void executeScript(final ScriptMetadata script) {
46 | // add this even if script execution fails
47 | RunLastHandler.lastRun = script;
48 | final IScriptLanguageSupport languageSupport = ScriptLanguageHandler.getScriptSupport(script.getFile());
49 |
50 | executeRunnableWhichMayThrowScriptException(script, new Callable() {
51 | @Override
52 | public Void call() throws Exception {
53 | languageSupport.executeScript(script);
54 | return null;
55 | }
56 | });
57 | }
58 |
59 | static IFile getFile(ScriptMetadata script, ScriptException scriptException) {
60 | IFile file = null;
61 | try {
62 | String sourceName = scriptException.getSourceName();
63 | int hashIdx = sourceName.indexOf('#');
64 | if (hashIdx != -1) {
65 | sourceName = sourceName.substring(0, hashIdx);
66 | }
67 | IPath path = new Path(sourceName);
68 | file = script.getFile().getWorkspace().getRoot().getFile(path);
69 | } catch (Throwable t) {
70 | file = script.getFile();
71 | }
72 | return file;
73 | }
74 |
75 | static void showMessageOfferJumpToScript(ScriptMetadata script, ScriptException e) {
76 | final String[] choices = new String[] { Messages.scriptErrorWhenRunningScriptOkButton,
77 | Messages.scriptErrorWhenRunningScriptJumpToScriptButton };
78 |
79 | int lineNumber = Math.max(e.getLineNumber(), 1);
80 | IFile file = getFile(script, e);
81 |
82 | String dialogTitle = Messages.scriptErrorWhenRunningScriptDialogTitle;
83 | String dialogText = NLS.bind(Messages.scriptErrorWhenRunningScriptDialogText, new Object[] {
84 | script.getFile().getName(), e.getCause().getMessage(), Integer.toString(lineNumber) });
85 |
86 | if (e.getScriptStackTrace() != null && !e.getScriptStackTrace().isEmpty()) {
87 | dialogText = dialogText + "\n\n" + e.getScriptStackTrace(); //$NON-NLS-1$
88 | }
89 |
90 | int result = ErrorDetailsDialog.openError(EclipseUtils.getWindowShell(), dialogTitle, dialogText, e.getCause(),
91 | choices, e.isShowStackTrace());
92 | if (result == 1) {
93 | IEditorPart editorPart = EclipseUtils.openEditor(file);
94 | if (editorPart instanceof ITextEditor) {
95 | ITextEditor textEditor = (ITextEditor) editorPart;
96 | IDocumentProvider provider = textEditor.getDocumentProvider();
97 | IDocument document = provider.getDocument(textEditor.getEditorInput());
98 | try {
99 | int start = document.getLineOffset(lineNumber - 1);
100 | textEditor.selectAndReveal(start, 0);
101 | IWorkbenchPage page = textEditor.getSite().getPage();
102 | page.activate(textEditor);
103 | } catch (BadLocationException e2) {
104 | throw new RuntimeException(e2);
105 | }
106 | }
107 | }
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/ui/CloseConsolePageParticipant.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.ui;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.eclipse.jface.action.Action;
7 | import org.eclipse.jface.action.IToolBarManager;
8 | import org.eclipse.ui.IActionBars;
9 | import org.eclipse.ui.console.ConsolePlugin;
10 | import org.eclipse.ui.console.IConsole;
11 | import org.eclipse.ui.console.IConsoleConstants;
12 | import org.eclipse.ui.console.IConsoleManager;
13 | import org.eclipse.ui.console.IConsolePageParticipant;
14 | import org.eclipse.ui.console.actions.CloseConsoleAction;
15 | import org.eclipse.ui.part.IPageBookViewPage;
16 | import org.eclipse.ui.part.IPageSite;
17 | import org.eclipsescript.core.Activator;
18 | import org.eclipsescript.messages.Messages;
19 | import org.eclipsescript.scriptobjects.Console;
20 |
21 | public class CloseConsolePageParticipant implements IConsolePageParticipant {
22 |
23 | public static class RemoveAllTerminatedAction extends Action {
24 |
25 | public RemoveAllTerminatedAction() {
26 | super(Messages.removeAllTerminatedConsoles, Activator.getImageDescriptor(Activator.IMG_REMOVE_ALL));
27 | setToolTipText(Messages.removeAllTerminatedConsoles);
28 | }
29 |
30 | @Override
31 | public void run() {
32 | // ConsolePlugin.getDefault().getConsoleManager().removeConsoles(new IConsole[] { fConsole });
33 | ConsolePlugin consolePlugin = ConsolePlugin.getDefault();
34 | IConsoleManager consoleManager = consolePlugin.getConsoleManager();
35 | List consolesToRemove = new ArrayList();
36 | for (IConsole console : consoleManager.getConsoles()) {
37 | if (console instanceof Console.ConsoleClass) {
38 | ((Console.ConsoleClass) console).isDisposed = true;
39 | consolesToRemove.add(console);
40 | }
41 | }
42 | consoleManager.removeConsoles(consolesToRemove.toArray(new IConsole[consolesToRemove.size()]));
43 | }
44 |
45 | }
46 |
47 | @Override
48 | public void activated() {
49 | // do nothing
50 | }
51 |
52 | @Override
53 | public void deactivated() {
54 | // do nothing
55 | }
56 |
57 | @Override
58 | public void dispose() {
59 | // do nothing
60 | }
61 |
62 | @Override
63 | public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
64 | return adapter.isInstance(this) ? this : null;
65 | }
66 |
67 | /** Method overridden to add close console action to the console toolbar. */
68 | @Override
69 | public void init(IPageBookViewPage page, IConsole console) {
70 | CloseConsoleAction action = new CloseConsoleAction(console);
71 | IPageSite site = page.getSite();
72 | IActionBars actionBars = site.getActionBars();
73 | IToolBarManager manager = actionBars.getToolBarManager();
74 | manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, action);
75 | manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, new RemoveAllTerminatedAction());
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/ui/ErrorDetailsDialog.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.ui;
2 |
3 | import java.io.PrintWriter;
4 | import java.io.StringWriter;
5 |
6 |
7 | import org.eclipse.jface.dialogs.IDialogConstants;
8 | import org.eclipse.jface.dialogs.IconAndMessageDialog;
9 | import org.eclipse.jface.resource.JFaceResources;
10 | import org.eclipse.osgi.util.NLS;
11 | import org.eclipse.swt.SWT;
12 | import org.eclipse.swt.dnd.Clipboard;
13 | import org.eclipse.swt.dnd.TextTransfer;
14 | import org.eclipse.swt.dnd.Transfer;
15 | import org.eclipse.swt.events.SelectionEvent;
16 | import org.eclipse.swt.events.SelectionListener;
17 | import org.eclipse.swt.graphics.Image;
18 | import org.eclipse.swt.graphics.Point;
19 | import org.eclipse.swt.layout.GridData;
20 | import org.eclipse.swt.layout.GridLayout;
21 | import org.eclipse.swt.widgets.Button;
22 | import org.eclipse.swt.widgets.Composite;
23 | import org.eclipse.swt.widgets.Control;
24 | import org.eclipse.swt.widgets.Label;
25 | import org.eclipse.swt.widgets.Menu;
26 | import org.eclipse.swt.widgets.MenuItem;
27 | import org.eclipse.swt.widgets.Shell;
28 | import org.eclipse.swt.widgets.Text;
29 | import org.eclipsescript.core.Activator;
30 | import org.eclipsescript.messages.Messages;
31 | import org.osgi.framework.Constants;
32 |
33 | /**
34 | * A dialog to display one or more errors to the user, as contained in an IStatus
object. If an error
35 | * contains additional detailed information then a Details button is automatically supplied, which shows or hides an
36 | * error details viewer when pressed by the user.
37 | *
38 | *
39 | * This dialog should be considered being a "local" way of error handling. It cannot be changed or replaced by "global"
40 | * error handling facility ( org.eclipse.ui.statushandler.StatusManager
). If product defines its own way of
41 | * handling errors, this error dialog may cause UI inconsistency, so until it is absolutely necessary,
42 | * StatusManager
should be used.
43 | *
44 | *
45 | * @see org.eclipse.core.runtime.IStatus
46 | */
47 | public class ErrorDetailsDialog extends IconAndMessageDialog {
48 |
49 | public static int openError(Shell parent, String dialogTitle, String message, Throwable exception) {
50 | return openError(parent, dialogTitle, message, exception, new String[] { IDialogConstants.OK_LABEL }, true);
51 | }
52 |
53 | /**
54 | * Opens an error dialog to display the given error. Use this method if the error object being displayed does not
55 | * contain child items, or if you wish to display all such items without filtering.
56 | *
57 | * @param parent
58 | * the parent shell of the dialog, or null
if none
59 | * @param dialogTitle
60 | * the title to use for this dialog, or null
to indicate that the default title should be
61 | * used
62 | * @param message
63 | * the message to show in this dialog, or null
to indicate that the error's message should
64 | * be shown as the primary message
65 | * @param choices
66 | * @param status
67 | * the error to show to the user
68 | * @return the code of the button that was pressed that resulted in this dialog closing. This will be
69 | * Dialog.OK
if the OK button was pressed, or Dialog.CANCEL
if this dialog's close
70 | * window decoration or the ESC key was used.
71 | */
72 | public static int openError(Shell parent, String dialogTitle, String message, Throwable exception2,
73 | String[] choices, boolean showDetails) {
74 | ErrorDetailsDialog dialog = new ErrorDetailsDialog(parent, dialogTitle, message, exception2, choices,
75 | showDetails);
76 | return dialog.open();
77 | }
78 |
79 | private final String[] choices;
80 | private Button detailsButton;
81 | private final String dialogTitle;
82 | private Text errorDetailsText;
83 | private final Throwable exception;
84 | private final boolean showDetails;
85 |
86 | /**
87 | * Creates an error dialog. Note that the dialog will have no visual representation (no widgets) until it is told to
88 | * open.
89 | *
90 | * Normally one should use openError
to create and open one of these. This constructor is useful only
91 | * if the error object being displayed contains child items and you need to specify a mask which will be
92 | * used to filter the displaying of these children. The error dialog will only be displayed if there is at least one
93 | * child status matching the mask.
94 | *
95 | *
96 | * @param parentShell
97 | * the shell under which to create this dialog
98 | * @param dialogTitle
99 | * the title to use for this dialog, or null
to indicate that the default title should be
100 | * used
101 | * @param message
102 | * the message to show in this dialog, or null
to indicate that the error's message should
103 | * be shown as the primary message
104 | * @param choices2
105 | */
106 | ErrorDetailsDialog(Shell parentShell, String dialogTitle, String message, Throwable exception, String[] choices,
107 | boolean showDetails) {
108 | super(parentShell);
109 | this.dialogTitle = dialogTitle == null ? JFaceResources.getString("Problem_Occurred") : //$NON-NLS-1$
110 | dialogTitle;
111 | this.message = message;
112 | this.exception = exception;
113 | this.choices = choices;
114 | this.showDetails = showDetails;
115 | }
116 |
117 | /*
118 | * (non-Javadoc) Method declared on Dialog. Handles the pressing of the Ok or Details button in this dialog. If the
119 | * Ok button was pressed then close this dialog. If the Details button was pressed then toggle the displaying of the
120 | * error details area. Note that the Details button will only be visible if the error being displayed specifies
121 | * child details.
122 | */
123 | @Override
124 | protected void buttonPressed(int id) {
125 | if (id == IDialogConstants.DETAILS_ID) {
126 | // was the details button pressed?
127 | toggleDetailsArea();
128 | } else {
129 | setReturnCode(id);
130 | close();
131 | }
132 | }
133 |
134 | @Override
135 | protected void configureShell(Shell shell) {
136 | super.configureShell(shell);
137 | shell.setText(dialogTitle);
138 | }
139 |
140 | /** Copy the contents of the statuses to the clipboard. */
141 | void copyToClipboard() {
142 | String textToCopy = errorDetailsText.getText();
143 | Clipboard clipboard = new Clipboard(errorDetailsText.getDisplay());
144 | try {
145 | clipboard.setContents(new Object[] { textToCopy }, new Transfer[] { TextTransfer.getInstance() });
146 | } finally {
147 | clipboard.dispose();
148 | }
149 | }
150 |
151 | @Override
152 | protected void createButtonsForButtonBar(Composite parent) {
153 | // create OK and Details buttons
154 | boolean defaultButton = true;
155 | int id = 0;
156 | for (String choice : choices) {
157 | createButton(parent, id++, choice, defaultButton);
158 | if (defaultButton)
159 | defaultButton = false;
160 | }
161 | if (showDetails) {
162 | detailsButton = createButton(parent, IDialogConstants.DETAILS_ID, IDialogConstants.SHOW_DETAILS_LABEL,
163 | false);
164 | }
165 | }
166 |
167 | @Override
168 | protected void createDialogAndButtonArea(Composite parent) {
169 | super.createDialogAndButtonArea(parent);
170 | if (this.dialogArea instanceof Composite) {
171 | // Create a label if there are no children to force a smaller layout
172 | Composite dialogComposite = (Composite) dialogArea;
173 | if (dialogComposite.getChildren().length == 0) {
174 | new Label(dialogComposite, SWT.NULL);
175 | }
176 | }
177 | }
178 |
179 | /**
180 | * This implementation of the Dialog
framework method creates and lays out a composite. Subclasses that
181 | * require a different dialog area may either override this method, or call the super
implementation
182 | * and add controls to the created composite.
183 | *
184 | * Note: Since 3.4, the created composite no longer grabs excess vertical space. See
185 | * https://bugs.eclipse.org/bugs/show_bug.cgi?id=72489. If the old behavior is desired by subclasses, get the
186 | * returned composite's layout data and set grabExcessVerticalSpace to true.
187 | */
188 | @Override
189 | protected Control createDialogArea(Composite parent) {
190 | // Create a composite with standard margins and spacing
191 | // Add the messageArea to this composite so that as subclasses add widgets to the messageArea
192 | // and dialogArea, the number of children of parent remains fixed and with consistent layout.
193 | // Fixes bug #240135
194 | Composite composite = new Composite(parent, SWT.NONE);
195 | createMessageArea(composite);
196 | GridLayout layout = new GridLayout();
197 | layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
198 | layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
199 | layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
200 | layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
201 | layout.numColumns = 2;
202 | composite.setLayout(layout);
203 | GridData childData = new GridData(GridData.FILL_BOTH);
204 | childData.horizontalSpan = 2;
205 | childData.grabExcessVerticalSpace = false;
206 | composite.setLayoutData(childData);
207 | composite.setFont(parent.getFont());
208 |
209 | return composite;
210 | }
211 |
212 | /**
213 | * Create this dialog's drop-down list component.
214 | *
215 | * @param parent
216 | * the parent composite
217 | * @return the drop-down list component
218 | */
219 | protected Text createDropDownList(Composite parent) {
220 | // create the list
221 | errorDetailsText = new Text(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY | SWT.WRAP);
222 |
223 | StringWriter writer = new StringWriter();
224 | exception.printStackTrace(new PrintWriter(writer));
225 | String stackTraceText = writer.getBuffer().toString();
226 |
227 | String detailsText = NLS.bind(Messages.internalErrorDialogDetails, new Object[] {
228 | Activator.getDefault().getBundle().getHeaders().get(Constants.BUNDLE_NAME),
229 | Activator.getDefault().getBundle().getSymbolicName(),
230 | Activator.getDefault().getBundle().getHeaders().get(Constants.BUNDLE_VERSION), stackTraceText });
231 | errorDetailsText.setText(detailsText);
232 |
233 | GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL
234 | | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_VERTICAL);
235 | data.heightHint = 300;
236 | data.horizontalSpan = 2;
237 | errorDetailsText.setLayoutData(data);
238 | errorDetailsText.setFont(parent.getFont());
239 | Menu copyMenu = new Menu(errorDetailsText);
240 | MenuItem copyItem = new MenuItem(copyMenu, SWT.NONE);
241 | copyItem.addSelectionListener(new SelectionListener() {
242 | /** @see SelectionListener.widgetDefaultSelected(SelectionEvent) */
243 | @Override
244 | public void widgetDefaultSelected(SelectionEvent e) {
245 | copyToClipboard();
246 | }
247 |
248 | /** @see SelectionListener.widgetSelected (SelectionEvent) */
249 | @Override
250 | public void widgetSelected(SelectionEvent e) {
251 | copyToClipboard();
252 | }
253 | });
254 | copyItem.setText(JFaceResources.getString("copy")); //$NON-NLS-1$
255 | errorDetailsText.setMenu(copyMenu);
256 | return errorDetailsText;
257 | }
258 |
259 | @Override
260 | protected Image getImage() {
261 | // If it was not a warning or an error then return the error image
262 | return getErrorImage();
263 | }
264 |
265 | @Override
266 | protected boolean isResizable() {
267 | return true;
268 | }
269 |
270 | /**
271 | * Toggles the unfolding of the details area. This is triggered by the user pressing the details button.
272 | */
273 | private void toggleDetailsArea() {
274 | Point windowSize = getShell().getSize();
275 | Point oldSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
276 | if (errorDetailsText != null && !errorDetailsText.isDisposed()) {
277 | errorDetailsText.dispose();
278 | detailsButton.setText(IDialogConstants.SHOW_DETAILS_LABEL);
279 | } else {
280 | errorDetailsText = createDropDownList((Composite) getContents());
281 | detailsButton.setText(IDialogConstants.HIDE_DETAILS_LABEL);
282 | getContents().getShell().layout();
283 | }
284 | Point newSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
285 | getShell().setSize(new Point(windowSize.x, windowSize.y + (newSize.y - oldSize.y)));
286 | }
287 |
288 | }
289 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/ui/ErrorHandlingHandler.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.ui;
2 |
3 |
4 | import org.eclipse.core.commands.AbstractHandler;
5 | import org.eclipse.core.commands.ExecutionEvent;
6 | import org.eclipse.core.commands.ExecutionException;
7 | import org.eclipsescript.core.Activator;
8 |
9 | public abstract class ErrorHandlingHandler extends AbstractHandler {
10 |
11 | protected abstract void doExecute(ExecutionEvent event) throws Exception;
12 |
13 | @Override
14 | public final Object execute(ExecutionEvent event) throws ExecutionException {
15 | try {
16 | doExecute(event);
17 | } catch (LinkageError e) {
18 | Activator.logError(e);
19 | } catch (Exception e) {
20 | Activator.logError(e);
21 | }
22 | return null;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/ui/QuickAccessElement.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.ui;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.eclipse.jface.resource.ImageDescriptor;
7 |
8 | public abstract class QuickAccessElement {
9 |
10 | /** Copied from internal class org.eclipse.ui.internal.quickaccess.CamelUtil. */
11 | private static class CamelUtil {
12 |
13 | /**
14 | * Returns a lowercase string consisting of all initials of the words in the given String. Words are separated
15 | * by whitespace and other special characters, or by uppercase letters in a word like CamelCase.
16 | *
17 | * @param s
18 | * the string
19 | * @return a lowercase string containing the first character of every wordin the given string.
20 | */
21 | public static String getCamelCase(String s) {
22 | StringBuffer result = new StringBuffer();
23 | if (s.length() > 0) {
24 | int index = 0;
25 | while (index != -1) {
26 | result.append(s.charAt(index));
27 | index = getNextCamelIndex(s, index + 1);
28 | }
29 | }
30 | return result.toString().toLowerCase();
31 | }
32 |
33 | /**
34 | * Return an array with start/end indices for the characters used for camel case matching, ignoring the first
35 | * (start) many camel case characters. For example, getCamelCaseIndices("some CamelCase", 1, 2) will return
36 | * {{5,5},{10,10}}.
37 | *
38 | * @param s
39 | * the source string
40 | * @param start
41 | * how many characters of getCamelCase(s) should be ignored
42 | * @param length
43 | * for how many characters should indices be returned
44 | * @return an array of length start
45 | */
46 | public static int[][] getCamelCaseIndices(String s, int startParameter, int lengthParameter) {
47 | int start = startParameter;
48 | int length = lengthParameter;
49 | List result = new ArrayList();
50 | int index = 0;
51 | while (start > 0) {
52 | index = getNextCamelIndex(s, index + 1);
53 | start--;
54 | }
55 | while (length > 0) {
56 | result.add(new int[] { index, index });
57 | index = getNextCamelIndex(s, index + 1);
58 | length--;
59 | }
60 | return result.toArray(new int[result.size()][]);
61 | }
62 |
63 | /**
64 | * Returns the next index to be used for camel case matching.
65 | *
66 | * @param s
67 | * the string
68 | * @param index
69 | * the index
70 | * @return the next index, or -1 if not found
71 | */
72 | public static int getNextCamelIndex(String s, int indexParameter) {
73 | int index = indexParameter;
74 | char c;
75 | while (index < s.length() && !(isSeparatorForCamelCase(c = s.charAt(index))) && Character.isLowerCase(c)) {
76 | index++;
77 | }
78 | while (index < s.length() && isSeparatorForCamelCase(c = s.charAt(index))) {
79 | index++;
80 | }
81 | if (index >= s.length()) {
82 | index = -1;
83 | }
84 | return index;
85 | }
86 |
87 | /**
88 | * Returns true if the given character is to be considered a separator for camel case matching purposes.
89 | *
90 | * @param c
91 | * the character
92 | * @return true if the character is a separator
93 | */
94 | public static boolean isSeparatorForCamelCase(char c) {
95 | return !Character.isLetterOrDigit(c);
96 | }
97 |
98 | }
99 |
100 | /** Executes the associated action for this element. */
101 | public abstract void execute();
102 |
103 | /** The image descriptor for this element, or null if no image is available */
104 | public abstract ImageDescriptor getImageDescriptor();
105 |
106 | /** The label to be displayed to the user. */
107 | public abstract String getLabel();
108 |
109 | /** The label to be used for sorting and matching elements. */
110 | public String getSortLabel() {
111 | return getLabel();
112 | }
113 |
114 | public QuickAccessEntry match(String filter) {
115 | String sortLabel = getLabel();
116 | int index = sortLabel.toLowerCase().indexOf(filter);
117 | if (index != -1) {
118 | return new QuickAccessEntry(this, new int[][] { { index, index + filter.length() - 1 } });
119 | }
120 | String camelCase = CamelUtil.getCamelCase(sortLabel);
121 | index = camelCase.indexOf(filter);
122 | if (index != -1) {
123 | int[][] indices = CamelUtil.getCamelCaseIndices(sortLabel, index, filter.length());
124 | return new QuickAccessEntry(this, indices);
125 | }
126 | return null;
127 | }
128 |
129 | }
130 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/ui/QuickAccessEntry.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.ui;
2 |
3 | import org.eclipse.jface.resource.DeviceResourceException;
4 | import org.eclipse.jface.resource.ImageDescriptor;
5 | import org.eclipse.jface.resource.ResourceManager;
6 | import org.eclipse.swt.SWT;
7 | import org.eclipse.swt.graphics.Image;
8 | import org.eclipse.swt.graphics.Rectangle;
9 | import org.eclipse.swt.graphics.TextLayout;
10 | import org.eclipse.swt.graphics.TextStyle;
11 | import org.eclipse.swt.widgets.Event;
12 | import org.eclipse.swt.widgets.Table;
13 | import org.eclipse.swt.widgets.TableItem;
14 | import org.eclipsescript.core.Activator;
15 |
16 | final class QuickAccessEntry {
17 | public static void erase(Event event) {
18 | // We are only custom drawing the foreground.
19 | event.detail &= ~SWT.FOREGROUND;
20 | }
21 |
22 | private static Image findOrCreateImage(ImageDescriptor imageDescriptor, ResourceManager resourceManager) {
23 | if (imageDescriptor == null) {
24 | return null;
25 | }
26 | Image image = (Image) resourceManager.find(imageDescriptor);
27 | if (image == null) {
28 | try {
29 | image = resourceManager.createImage(imageDescriptor);
30 | } catch (DeviceResourceException e) {
31 | Activator.logError(e);
32 | }
33 | }
34 | return image;
35 | }
36 |
37 | QuickAccessElement element;
38 |
39 | private final int[][] elementMatchRegions;
40 |
41 | QuickAccessEntry(QuickAccessElement element, int[][] elementMatchRegions) {
42 | this.element = element;
43 | this.elementMatchRegions = elementMatchRegions;
44 | }
45 |
46 | Image getImage(ResourceManager resourceManager) {
47 | Image image = findOrCreateImage(element.getImageDescriptor(), resourceManager);
48 | if (image == null) {
49 | throw new IllegalArgumentException("Null image for element: " + element); //$NON-NLS-1$
50 | }
51 | return image;
52 | }
53 |
54 | public void measure(Event event, TextLayout textLayout, ResourceManager resourceManager, TextStyle boldStyle) {
55 | Table table = ((TableItem) event.item).getParent();
56 | textLayout.setFont(table.getFont());
57 | event.width = 0;
58 | switch (event.index) {
59 | case 0:
60 | Image image = getImage(resourceManager);
61 | Rectangle imageRect = image.getBounds();
62 | event.width += imageRect.width + 4;
63 | event.height = Math.max(event.height, imageRect.height + 2);
64 | textLayout.setText(element.getLabel());
65 | for (int i = 0; i < elementMatchRegions.length; i++) {
66 | int[] matchRegion = elementMatchRegions[i];
67 | textLayout.setStyle(boldStyle, matchRegion[0], matchRegion[1]);
68 | }
69 | break;
70 | default:
71 | throw new IllegalArgumentException("Invalid event.index: " + event.index); //$NON-NLS-1$
72 | }
73 | Rectangle rect = textLayout.getBounds();
74 | event.width += rect.width + 4;
75 | event.height = Math.max(event.height, rect.height + 2);
76 | }
77 |
78 | public void paint(Event event, TextLayout textLayout, ResourceManager resourceManager, TextStyle boldStyle) {
79 | final Table table = ((TableItem) event.item).getParent();
80 | textLayout.setFont(table.getFont());
81 | switch (event.index) {
82 | case 0:
83 | Image image = getImage(resourceManager);
84 | event.gc.drawImage(image, event.x + 1, event.y + 1);
85 | textLayout.setText(element.getLabel());
86 | for (int i = 0; i < elementMatchRegions.length; i++) {
87 | int[] matchRegion = elementMatchRegions[i];
88 | textLayout.setStyle(boldStyle, matchRegion[0], matchRegion[1]);
89 | }
90 | Rectangle availableBounds = ((TableItem) event.item).getTextBounds(event.index);
91 | Rectangle requiredBounds = textLayout.getBounds();
92 | textLayout.draw(event.gc, availableBounds.x + 1 + image.getBounds().width, availableBounds.y
93 | + (availableBounds.height - requiredBounds.height) / 2);
94 | break;
95 | default:
96 | throw new IllegalArgumentException("Invalid event.index: " + event.index); //$NON-NLS-1$
97 | }
98 | }
99 | }
--------------------------------------------------------------------------------
/src/org/eclipsescript/ui/QuickAccessProvider.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.ui;
2 |
3 | import java.util.Arrays;
4 | import java.util.Comparator;
5 |
6 | public abstract class QuickAccessProvider {
7 |
8 | private QuickAccessElement[] sortedElements;
9 |
10 | /**
11 | * Returns the elements provided by this provider.
12 | *
13 | * @return this provider's elements
14 | */
15 | public abstract QuickAccessElement[] getElements();
16 |
17 | public QuickAccessElement[] getElementsSorted() {
18 | if (sortedElements == null) {
19 | sortedElements = getElements();
20 | Arrays.sort(sortedElements, new Comparator() {
21 | @Override
22 | public int compare(QuickAccessElement e1, QuickAccessElement e2) {
23 | return e1.getLabel().compareToIgnoreCase(e2.getLabel());
24 | }
25 | });
26 | }
27 | return sortedElements;
28 | }
29 |
30 | }
--------------------------------------------------------------------------------
/src/org/eclipsescript/ui/QuickScriptDialog.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.ui;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.Iterator;
6 | import java.util.List;
7 |
8 | import org.eclipse.jface.dialogs.IDialogSettings;
9 | import org.eclipse.jface.dialogs.PopupDialog;
10 | import org.eclipse.jface.layout.GridDataFactory;
11 | import org.eclipse.jface.layout.GridLayoutFactory;
12 | import org.eclipse.jface.layout.TableColumnLayout;
13 | import org.eclipse.jface.resource.FontDescriptor;
14 | import org.eclipse.jface.resource.JFaceResources;
15 | import org.eclipse.jface.resource.LocalResourceManager;
16 | import org.eclipse.jface.viewers.ColumnWeightData;
17 | import org.eclipse.swt.SWT;
18 | import org.eclipse.swt.events.KeyAdapter;
19 | import org.eclipse.swt.events.KeyEvent;
20 | import org.eclipse.swt.events.ModifyEvent;
21 | import org.eclipse.swt.events.ModifyListener;
22 | import org.eclipse.swt.events.MouseAdapter;
23 | import org.eclipse.swt.events.MouseEvent;
24 | import org.eclipse.swt.events.SelectionAdapter;
25 | import org.eclipse.swt.events.SelectionEvent;
26 | import org.eclipse.swt.graphics.Font;
27 | import org.eclipse.swt.graphics.Point;
28 | import org.eclipse.swt.graphics.TextLayout;
29 | import org.eclipse.swt.graphics.TextStyle;
30 | import org.eclipse.swt.widgets.Composite;
31 | import org.eclipse.swt.widgets.Control;
32 | import org.eclipse.swt.widgets.Event;
33 | import org.eclipse.swt.widgets.Listener;
34 | import org.eclipse.swt.widgets.Table;
35 | import org.eclipse.swt.widgets.TableColumn;
36 | import org.eclipse.swt.widgets.TableItem;
37 | import org.eclipse.swt.widgets.Text;
38 | import org.eclipse.ui.IWorkbenchWindow;
39 | import org.eclipsescript.core.Activator;
40 |
41 | /**
42 | * Derived from org.eclipse.ui.internal.QuickAccessDialog.
43 | */
44 | public final class QuickScriptDialog extends PopupDialog {
45 |
46 | Text filterText;
47 | final QuickAccessProvider provider = new QuickScriptProvider();
48 | LocalResourceManager resourceManager = new LocalResourceManager(JFaceResources.getResources());
49 | Table table;
50 | TextLayout textLayout;
51 |
52 | public QuickScriptDialog(IWorkbenchWindow window) {
53 | super(/* parent: */window.getShell(), /* shellStyle: */SWT.RESIZE, /* takeFocusOnOpen: */true, /* persistSize: */
54 | true, /* persistLocation: */false,
55 | /* showDialogMenu: */false, /* showPersistActions: */false, /* titleText: */"", //$NON-NLS-1$
56 | /* infoText: */null);
57 | }
58 |
59 | @Override
60 | public boolean close() {
61 | if (textLayout != null && !textLayout.isDisposed()) {
62 | textLayout.dispose();
63 | }
64 | if (resourceManager != null) {
65 | resourceManager.dispose();
66 | resourceManager = null;
67 | }
68 | return super.close();
69 | }
70 |
71 | /**
72 | * @see org.eclipse.jface.dialogs.PopupDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
73 | */
74 | @Override
75 | protected Control createDialogArea(Composite parent) {
76 | Composite composite = (Composite) super.createDialogArea(parent);
77 | boolean isWin32 = "win32".equals(SWT.getPlatform()); //$NON-NLS-1$
78 | GridLayoutFactory.fillDefaults().extendedMargins(isWin32 ? 0 : 3, 3, 2, 2).applyTo(composite);
79 | Composite tableComposite = new Composite(composite, SWT.NONE);
80 | GridDataFactory.fillDefaults().grab(true, true).applyTo(tableComposite);
81 | TableColumnLayout tableColumnLayout = new TableColumnLayout();
82 | tableComposite.setLayout(tableColumnLayout);
83 | table = new Table(tableComposite, SWT.SINGLE | SWT.FULL_SELECTION);
84 | textLayout = new TextLayout(table.getDisplay());
85 | textLayout.setOrientation(getDefaultOrientation());
86 | Font boldFont = resourceManager.createFont(FontDescriptor.createFrom(JFaceResources.getDialogFont()).setStyle(
87 | SWT.BOLD));
88 | textLayout.setFont(table.getFont());
89 |
90 | // tableColumnLayout.setColumnData(new TableColumn(table, SWT.NONE), new ColumnWeightData(0, maxProviderWidth));
91 | tableColumnLayout.setColumnData(new TableColumn(table, SWT.NONE), new ColumnWeightData(100, 100));
92 |
93 | table.addKeyListener(new KeyAdapter() {
94 | @Override
95 | public void keyPressed(KeyEvent e) {
96 | if (e.keyCode == SWT.ARROW_UP && table.getSelectionIndex() == 0) {
97 | filterText.setFocus();
98 | } else if (e.character == SWT.ESC) {
99 | close();
100 | }
101 | }
102 | });
103 |
104 | table.addMouseListener(new MouseAdapter() {
105 | @Override
106 | public void mouseUp(MouseEvent e) {
107 | if (table.getSelectionCount() < 1)
108 | return;
109 | if (e.button != 1)
110 | return;
111 | if (table.equals(e.getSource())) {
112 | Object o = table.getItem(new Point(e.x, e.y));
113 | TableItem selection = table.getSelection()[0];
114 | if (selection.equals(o))
115 | handleSelection();
116 | }
117 | }
118 | });
119 |
120 | table.addSelectionListener(new SelectionAdapter() {
121 | @Override
122 | public void widgetDefaultSelected(SelectionEvent e) {
123 | handleSelection();
124 | }
125 | });
126 |
127 | // italicsFont = resourceManager.createFont(FontDescriptor.createFrom(
128 | // table.getFont()).setStyle(SWT.ITALIC));
129 | final TextStyle boldStyle = new TextStyle(boldFont, null, null);
130 | Listener listener = new Listener() {
131 | @Override
132 | public void handleEvent(Event event) {
133 | QuickAccessEntry entry = (QuickAccessEntry) event.item.getData();
134 | if (entry != null) {
135 | switch (event.type) {
136 | case SWT.MeasureItem:
137 | entry.measure(event, textLayout, resourceManager, boldStyle);
138 | break;
139 | case SWT.PaintItem:
140 | entry.paint(event, textLayout, resourceManager, boldStyle);
141 | break;
142 | case SWT.EraseItem:
143 | QuickAccessEntry.erase(event);
144 | break;
145 | default:
146 | break;
147 | }
148 | }
149 | }
150 | };
151 | table.addListener(SWT.MeasureItem, listener);
152 | table.addListener(SWT.EraseItem, listener);
153 | table.addListener(SWT.PaintItem, listener);
154 |
155 | return composite;
156 | }
157 |
158 | @Override
159 | protected Control createTitleControl(Composite parent) {
160 | filterText = new Text(parent, SWT.NONE);
161 |
162 | GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(filterText);
163 |
164 | filterText.addKeyListener(new KeyAdapter() {
165 | @Override
166 | public void keyPressed(KeyEvent e) {
167 | if (e.keyCode == 0x0D) {
168 | handleSelection();
169 | return;
170 | } else if (e.keyCode == SWT.ARROW_DOWN) {
171 | int index = table.getSelectionIndex();
172 | if (index != -1 && table.getItemCount() > index + 1) {
173 | table.setSelection(index + 1);
174 | }
175 | table.setFocus();
176 | } else if (e.keyCode == SWT.ARROW_UP) {
177 | int index = table.getSelectionIndex();
178 | if (index != -1 && index >= 1) {
179 | table.setSelection(index - 1);
180 | table.setFocus();
181 | }
182 | } else if (e.character == 0x1B) // ESC
183 | close();
184 | }
185 | });
186 | filterText.addModifyListener(new ModifyListener() {
187 | @Override
188 | public void modifyText(ModifyEvent e) {
189 | String text = ((Text) e.widget).getText().toLowerCase();
190 | refresh(text);
191 | }
192 | });
193 |
194 | return filterText;
195 | }
196 |
197 | // eclipse 3.4:
198 | // @Override
199 | // protected Point getDefaultLocation(Point initialSize) {
200 | // Point size = new Point(400, 400);
201 | // Rectangle parentBounds = getParentShell().getBounds();
202 | // int x = parentBounds.x + parentBounds.width / 2 - size.x / 2;
203 | // int y = parentBounds.y + parentBounds.height / 2 - size.y / 2;
204 | // return new Point(x, y);
205 | // }
206 |
207 | @Override
208 | protected Point getDefaultSize() {
209 | return new Point(600, 600);
210 | }
211 |
212 | @Override
213 | protected IDialogSettings getDialogSettings() {
214 | return Activator.getDefault().getDialogSettings();
215 | }
216 |
217 | @Override
218 | protected Control getFocusControl() {
219 | return filterText;
220 | }
221 |
222 | void handleSelection() {
223 | QuickAccessElement selectedElement = null;
224 | if (table.getSelectionCount() == 1) {
225 | QuickAccessEntry entry = (QuickAccessEntry) table.getSelection()[0].getData();
226 | selectedElement = entry == null ? null : entry.element;
227 | }
228 | close();
229 | if (selectedElement != null) {
230 | selectedElement.execute();
231 | }
232 | }
233 |
234 | void refresh(String filter) {
235 | List entries;
236 | if (filter.isEmpty()) {
237 | entries = Collections.emptyList();
238 | } else {
239 | entries = new ArrayList();
240 | QuickAccessElement[] elements = provider.getElementsSorted();
241 | for (QuickAccessElement element : elements) {
242 | QuickAccessEntry entry = element.match(filter);
243 | if (entry != null)
244 | entries.add(entry);
245 | }
246 | }
247 |
248 | TableItem[] items = table.getItems();
249 | int index = 0;
250 | for (Iterator it = entries.iterator(); it.hasNext();) {
251 | QuickAccessEntry entry = it.next();
252 | TableItem item;
253 | if (index < items.length) {
254 | item = items[index];
255 | table.clear(index);
256 | } else {
257 | item = new TableItem(table, SWT.NONE);
258 | }
259 | item.setData(entry);
260 | item.setText(0, entry.element.getLabel());
261 | if (SWT.getPlatform().equals("wpf")) { //$NON-NLS-1$
262 | item.setImage(0, entry.getImage(resourceManager));
263 | }
264 | index++;
265 | }
266 | if (index < items.length) {
267 | table.remove(index, items.length - 1);
268 | }
269 | if (table.getItems().length > 0)
270 | table.setSelection(0);
271 | }
272 |
273 | }
--------------------------------------------------------------------------------
/src/org/eclipsescript/ui/QuickScriptProvider.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.ui;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 |
7 | import org.eclipse.core.resources.IFile;
8 | import org.eclipse.core.resources.IResource;
9 | import org.eclipse.core.resources.IResourceProxy;
10 | import org.eclipse.core.resources.IResourceProxyVisitor;
11 | import org.eclipse.core.resources.IWorkspaceRoot;
12 | import org.eclipse.core.resources.ResourcesPlugin;
13 | import org.eclipse.core.runtime.CoreException;
14 | import org.eclipse.jface.resource.ImageDescriptor;
15 | import org.eclipsescript.core.Activator;
16 | import org.eclipsescript.scripts.ScriptMetadata;
17 | import org.eclipsescript.scripts.ScriptStore;
18 |
19 | public class QuickScriptProvider extends QuickAccessProvider {
20 |
21 | static final ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle()
22 | .getEntry("icons/run_script.gif")); //$NON-NLS-1$
23 |
24 | @Override
25 | public QuickAccessElement[] getElements() {
26 | final List allScripts = new ArrayList();
27 | IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
28 | try {
29 | root.accept(new IResourceProxyVisitor() {
30 | @Override
31 | public boolean visit(IResourceProxy proxy) throws CoreException {
32 | if (proxy.getName().endsWith(".eclipse.js")) { //$NON-NLS-1$
33 | IResource resource = proxy.requestResource();
34 | if (resource instanceof IFile && !resource.isDerived()) {
35 | IFile file = (IFile) resource;
36 | allScripts.add(new ScriptMetadata(file));
37 | }
38 | }
39 | return true;
40 | }
41 | }, 0);
42 | } catch (CoreException e) {
43 | e.printStackTrace();
44 | }
45 |
46 | QuickAccessElement[] elements = new QuickAccessElement[allScripts.size()];
47 | for (int i = 0; i < elements.length; i++) {
48 | final ScriptMetadata script = allScripts.get(i);
49 | elements[i] = new QuickAccessElement() {
50 |
51 | @Override
52 | public void execute() {
53 | ScriptStore.executeScript(script);
54 | }
55 |
56 | @Override
57 | public ImageDescriptor getImageDescriptor() {
58 | return imageDescriptor;
59 | }
60 |
61 | @Override
62 | public String getLabel() {
63 | return script.getLabel();
64 | }
65 | };
66 | }
67 | return elements;
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/util/EclipseUtils.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.util;
2 |
3 | import org.eclipse.core.resources.IFile;
4 | import org.eclipse.jface.text.IDocument;
5 | import org.eclipse.jface.text.TextSelection;
6 | import org.eclipse.jface.viewers.ISelection;
7 | import org.eclipse.jface.viewers.ISelectionProvider;
8 | import org.eclipse.swt.widgets.Display;
9 | import org.eclipse.swt.widgets.Shell;
10 | import org.eclipse.ui.IEditorDescriptor;
11 | import org.eclipse.ui.IEditorInput;
12 | import org.eclipse.ui.IEditorPart;
13 | import org.eclipse.ui.IEditorRegistry;
14 | import org.eclipse.ui.IWorkbench;
15 | import org.eclipse.ui.IWorkbenchPage;
16 | import org.eclipse.ui.IWorkbenchWindow;
17 | import org.eclipse.ui.PartInitException;
18 | import org.eclipse.ui.PlatformUI;
19 | import org.eclipse.ui.part.FileEditorInput;
20 | import org.eclipse.ui.texteditor.IDocumentProvider;
21 | import org.eclipse.ui.texteditor.ITextEditor;
22 | import org.eclipsescript.core.Activator;
23 | import org.eclipsescript.util.JavaUtils.MutableObject;
24 |
25 | public class EclipseUtils {
26 |
27 | public static interface DisplayThreadCallable {
28 | public T callWithDisplay(Display display) throws Exception;
29 | }
30 |
31 | /** A runnable to run in the display thread. */
32 | public static interface DisplayThreadRunnable {
33 | public void runWithDisplay(Display display) throws Exception;
34 | }
35 |
36 | public static IWorkbenchPage activePage() {
37 | return activeWindow().getActivePage();
38 | }
39 |
40 | public static IWorkbenchWindow activeWindow() {
41 | return PlatformUI.getWorkbench().getActiveWorkbenchWindow();
42 | }
43 |
44 | public static IDocument getCurrentDocument() {
45 | ITextEditor editor = getCurrentTextEditor();
46 | if (editor == null)
47 | return null;
48 | IDocumentProvider documentProvider = editor.getDocumentProvider();
49 | IDocument document = documentProvider.getDocument(editor.getEditorInput());
50 | return document;
51 | }
52 |
53 | public static IEditorInput getCurrentEditorInput() {
54 | ITextEditor editor = getCurrentTextEditor();
55 | if (editor == null)
56 | return null;
57 | return editor.getEditorInput();
58 | }
59 |
60 | public static TextSelection getCurrentEditorSelection() {
61 | ITextEditor editor = getCurrentTextEditor();
62 | if (editor == null)
63 | return null;
64 | ISelectionProvider selectionProvider = editor.getSelectionProvider();
65 | ISelection selection = selectionProvider.getSelection();
66 | if (selection instanceof TextSelection) {
67 | TextSelection textSelection = (TextSelection) selection;
68 | return textSelection;
69 | }
70 | return null;
71 | }
72 |
73 | public static ITextEditor getCurrentTextEditor() {
74 | IWorkbench workbench = PlatformUI.getWorkbench();
75 | IWorkbenchWindow activeWindow = workbench.getActiveWorkbenchWindow();
76 | IWorkbenchPage activePage = activeWindow.getActivePage();
77 | if (activePage == null)
78 | return null;
79 | IEditorPart activeEditor = activePage.getActiveEditor();
80 | if (activeEditor == null)
81 | return null;
82 | ITextEditor textEditor = (ITextEditor) activeEditor.getAdapter(ITextEditor.class);
83 | return textEditor;
84 | }
85 |
86 | public static IEditorDescriptor getDefaultEditor(final IFile file) {
87 | if (file == null)
88 | return null;
89 | IWorkbench workbench = PlatformUI.getWorkbench();
90 | IEditorDescriptor descriptor = workbench.getEditorRegistry().getDefaultEditor(file.getName());
91 | if (descriptor != null)
92 | return descriptor;
93 | descriptor = workbench.getEditorRegistry().getDefaultEditor("simple_text_file.txt"); //$NON-NLS-1$
94 | if (descriptor != null)
95 | return descriptor;
96 | descriptor = workbench.getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID);
97 | if (descriptor != null)
98 | return descriptor;
99 | return workbench.getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
100 | }
101 |
102 | public static Shell getWindowShell() {
103 | return activeWindow().getShell();
104 | }
105 |
106 | public static IEditorPart openEditor(final IFile file) {
107 | final IEditorDescriptor descriptor = getDefaultEditor(file);
108 | try {
109 | return activePage().openEditor(new FileEditorInput(file), descriptor.getId());
110 | } catch (PartInitException e) {
111 | Activator.logError(e);
112 | return null;
113 | }
114 | }
115 |
116 | private static T runInDisplayThread(final DisplayThreadCallable runnable, final boolean sync)
117 | throws Exception {
118 | final Display display = PlatformUI.getWorkbench().getDisplay();
119 |
120 | if (Thread.currentThread().equals(display.getThread())) {
121 | return runnable.callWithDisplay(display);
122 | } else {
123 | final MutableObject exceptionThrownInUIThread = new MutableObject();
124 | final MutableObject result = new MutableObject();
125 |
126 | Runnable showExceptionWrapper = new Runnable() {
127 | @Override
128 | public void run() {
129 | try {
130 | result.value = runnable.callWithDisplay(display);
131 | } catch (Exception e) {
132 | if (sync) {
133 | exceptionThrownInUIThread.value = e;
134 | } else {
135 | Activator.logError(e);
136 | }
137 | }
138 | }
139 | };
140 |
141 | if (sync) {
142 | display.syncExec(showExceptionWrapper);
143 | } else {
144 | display.asyncExec(showExceptionWrapper);
145 | }
146 | if (exceptionThrownInUIThread.value != null) {
147 | throw exceptionThrownInUIThread.value;
148 | }
149 |
150 | return result.value;
151 | }
152 | }
153 |
154 | public static void runInDisplayThreadAsync(final DisplayThreadRunnable runnable) throws Exception {
155 | runInDisplayThread(new DisplayThreadCallable() {
156 |
157 | @Override
158 | public Void callWithDisplay(Display display) throws Exception {
159 | runnable.runWithDisplay(display);
160 | return null;
161 | }
162 | }, false);
163 | }
164 |
165 | public static T runInDisplayThreadSync(final DisplayThreadCallable runnable) throws Exception {
166 | return runInDisplayThread(runnable, true);
167 | }
168 |
169 | public static void runInDisplayThreadSync(final DisplayThreadRunnable runnable) throws Exception {
170 | runInDisplayThread(new DisplayThreadCallable() {
171 |
172 | @Override
173 | public Void callWithDisplay(Display display) throws Exception {
174 | runnable.runWithDisplay(display);
175 | return null;
176 | }
177 | }, false);
178 | }
179 | }
180 |
--------------------------------------------------------------------------------
/src/org/eclipsescript/util/JavaUtils.java:
--------------------------------------------------------------------------------
1 | package org.eclipsescript.util;
2 |
3 | import java.io.ByteArrayOutputStream;
4 | import java.io.Closeable;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.Reader;
8 | import java.net.URL;
9 | import java.net.URLConnection;
10 |
11 | public class JavaUtils {
12 |
13 | public static abstract class BaseRunnable implements Runnable {
14 | public abstract void doRun() throws Exception;
15 |
16 | @Override
17 | public final void run() {
18 | try {
19 | doRun();
20 | } catch (Exception e) {
21 | throw asRuntime(e);
22 | }
23 | }
24 | }
25 |
26 | public static class MutableObject {
27 | public T value;
28 | }
29 |
30 | private static final String UTF8_CHARSET_NAME = "utf-8"; //$NON-NLS-1$
31 |
32 | public static RuntimeException asRuntime(Throwable e) {
33 | return (e instanceof RuntimeException) ? ((RuntimeException) e) : new RuntimeException(e);
34 | }
35 |
36 | public static void close(Closeable c) {
37 | if (c == null)
38 | return;
39 | try {
40 | c.close();
41 | } catch (IOException e) {
42 | throw new RuntimeException(e);
43 | }
44 | }
45 |
46 | public static boolean isNotBlank(String s) {
47 | return s != null && s.length() != 0;
48 | }
49 |
50 | public static byte[] readAll(InputStream in) throws IOException {
51 | try {
52 | byte[] buffer = new byte[512];
53 | int n;
54 | ByteArrayOutputStream baous = new ByteArrayOutputStream();
55 | while ((n = in.read(buffer)) != -1) {
56 | baous.write(buffer, 0, n);
57 | }
58 | return baous.toByteArray();
59 | } finally {
60 | close(in);
61 | }
62 | }
63 |
64 | public static String readAllToStringAndClose(InputStream in) {
65 | return readAllToStringAndClose(in, UTF8_CHARSET_NAME);
66 | }
67 |
68 | public static String readAllToStringAndClose(InputStream in, String charSetName) {
69 | try {
70 | String charSetNameToUse = charSetName;
71 | if (charSetName == null || charSetName.isEmpty())
72 | charSetNameToUse = UTF8_CHARSET_NAME;
73 | return new String(readAll(in), charSetNameToUse);
74 | } catch (IOException e) {
75 | throw new RuntimeException(e);
76 | } finally {
77 | close(in);
78 | }
79 | }
80 |
81 | public static String readAllToStringAndClose(Reader in) {
82 | StringBuilder result = new StringBuilder();
83 | try {
84 | char[] buffer = new char[4096];
85 | int n;
86 | while ((n = in.read(buffer)) != -1) {
87 | result.append(buffer, 0, n);
88 | }
89 | return result.toString();
90 | } catch (IOException e) {
91 | throw new RuntimeException(e);
92 | } finally {
93 | close(in);
94 | }
95 | }
96 |
97 | public static String readURL(URL url) throws Exception {
98 | URLConnection uc = url.openConnection();
99 | return readURLConnection(uc);
100 | }
101 |
102 | public static String readURLConnection(URLConnection uc) throws Exception {
103 | String contentType = uc.getContentType();
104 | int charSetNameIndex = contentType.indexOf("charset="); //$NON-NLS-1$
105 | String charSet;
106 | if (charSetNameIndex == -1) {
107 | charSet = UTF8_CHARSET_NAME;
108 | } else {
109 | charSet = contentType.substring(charSetNameIndex + 8);
110 | }
111 | InputStream in = uc.getInputStream();
112 | try {
113 | return readAllToStringAndClose(in, charSet);
114 | } finally {
115 | in.close();
116 | }
117 | }
118 |
119 | }
120 |
--------------------------------------------------------------------------------