diff --git a/plugin.properties b/plugin.properties index 03fecba..583ffa1 100644 --- a/plugin.properties +++ b/plugin.properties @@ -1,16 +1,16 @@ -commandCategoryName = EclipseScript -commandCategoryDescription = Commands for using the EclipseScript plug-in -commandRunLastName = EclipseScript: Run Last -commandRunLastDescription = Run the last EclipseScript that has been executed -commandRunCurrentName = EclipseScript: Run Current -commandRunCurrentDescription = Run the currently edited EclipseScript -commandRunScriptParameterName = Script -commandOpenScriptDialogName = EclipseScript: Open Script Dialog -commandOpenScriptDialogDescription = Search and select available scripts - -markerName=EclipseScript Problem -pluginName=EclipseScript -bundleVendor=eclipsescript.org -commandRunLastSequence = Ctrl+R -commandRunCurrentSequence = Alt+R -commandOpenScriptDialogSequence = M1+4 +commandCategoryName = EclipseScript +commandCategoryDescription = Commands for using the EclipseScript plug-in +commandRunLastName = EclipseScript: Run Last +commandRunLastDescription = Run the last EclipseScript that has been executed +commandRunCurrentName = EclipseScript: Run Current +commandRunCurrentDescription = Run the currently edited EclipseScript +commandRunScriptParameterName = Script +commandOpenScriptDialogName = EclipseScript: Open Script Dialog +commandOpenScriptDialogDescription = Search and select available scripts + +markerName=EclipseScript Problem +pluginName=EclipseScript +bundleVendor=eclipsescript.org +commandRunLastSequence = Ctrl+R +commandRunCurrentSequence = Alt+R +commandOpenScriptDialogSequence = M1+4 diff --git a/src/org/eclipsescript/core/Activator.java b/src/org/eclipsescript/core/Activator.java index 4ad478f..920d7aa 100644 --- a/src/org/eclipsescript/core/Activator.java +++ b/src/org/eclipsescript/core/Activator.java @@ -113,7 +113,7 @@ public void start(BundleContext bundleContext) throws Exception { // ServiceReference platformAdminServiceRef = context.getServiceReference(PlatformAdmin.class); // PlatformAdmin platformAdminService = context.getService(platformAdminServiceRef); // Eclipse 3.6 api: - ServiceReference platformAdminServiceRef = context.getServiceReference(PlatformAdmin.class.getName()); + ServiceReference platformAdminServiceRef = context.getServiceReference(PlatformAdmin.class.getName()); PlatformAdmin platformAdminService = (PlatformAdmin) context.getService(platformAdminServiceRef); resolver = platformAdminService.createResolver(); diff --git a/src/org/eclipsescript/core/RunCurrentHandler.java b/src/org/eclipsescript/core/RunCurrentHandler.java index 8dc4753..efd5e14 100644 --- a/src/org/eclipsescript/core/RunCurrentHandler.java +++ b/src/org/eclipsescript/core/RunCurrentHandler.java @@ -1,35 +1,35 @@ -package org.eclipsescript.core; - - -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.part.FileEditorInput; -import org.eclipsescript.messages.Messages; -import org.eclipsescript.scripts.ScriptLanguageHandler; -import org.eclipsescript.scripts.ScriptMetadata; -import org.eclipsescript.scripts.ScriptStore; -import org.eclipsescript.ui.ErrorHandlingHandler; -import org.eclipsescript.util.EclipseUtils; - -public class RunCurrentHandler extends ErrorHandlingHandler { - - @Override - protected void doExecute(ExecutionEvent event) throws Exception { - IEditorInput editorInput = EclipseUtils.getCurrentEditorInput(); - if (editorInput instanceof FileEditorInput) { - FileEditorInput fileInput = (FileEditorInput) editorInput; - IFile editedFile = fileInput.getFile(); - boolean isScriptFile = ScriptLanguageHandler.isEclipseScriptFile(editedFile); - if (isScriptFile) { - ScriptMetadata m = new ScriptMetadata(fileInput.getFile()); - ScriptStore.executeScript(m); - return; - } - } - MessageDialog.openInformation(EclipseUtils.getWindowShell(), Messages.cannotRunCurrentScriptTitle, - Messages.cannotRunCurrentScriptText); - } - -} +package org.eclipsescript.core; + + +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipsescript.messages.Messages; +import org.eclipsescript.scripts.ScriptLanguageHandler; +import org.eclipsescript.scripts.ScriptMetadata; +import org.eclipsescript.scripts.ScriptStore; +import org.eclipsescript.ui.ErrorHandlingHandler; +import org.eclipsescript.util.EclipseUtils; + +public class RunCurrentHandler extends ErrorHandlingHandler { + + @Override + protected void doExecute(ExecutionEvent event) throws Exception { + IEditorInput editorInput = EclipseUtils.getCurrentEditorInput(); + if (editorInput instanceof FileEditorInput) { + FileEditorInput fileInput = (FileEditorInput) editorInput; + IFile editedFile = fileInput.getFile(); + boolean isScriptFile = ScriptLanguageHandler.isEclipseScriptFile(editedFile); + if (isScriptFile) { + ScriptMetadata m = new ScriptMetadata(fileInput.getFile()); + ScriptStore.executeScript(m); + return; + } + } + MessageDialog.openInformation(EclipseUtils.getWindowShell(), Messages.cannotRunCurrentScriptTitle, + Messages.cannotRunCurrentScriptText); + } + +} diff --git a/src/org/eclipsescript/core/RunLastHandler.java b/src/org/eclipsescript/core/RunLastHandler.java index eb17f73..4d1101a 100644 --- a/src/org/eclipsescript/core/RunLastHandler.java +++ b/src/org/eclipsescript/core/RunLastHandler.java @@ -1,26 +1,26 @@ -package org.eclipsescript.core; - - -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipsescript.messages.Messages; -import org.eclipsescript.scripts.ScriptMetadata; -import org.eclipsescript.scripts.ScriptStore; -import org.eclipsescript.ui.ErrorHandlingHandler; -import org.eclipsescript.util.EclipseUtils; - -public class RunLastHandler extends ErrorHandlingHandler { - - public static ScriptMetadata lastRun = null; - - @Override - public void doExecute(ExecutionEvent event) throws ExecutionException { - if (lastRun == null) { - MessageDialog.openWarning(EclipseUtils.activeWindow().getShell(), "No script to run", //$NON-NLS-1$ - Messages.runScriptBeforeRunningLast); - } else { - ScriptStore.executeScript(lastRun); - } - } -} +package org.eclipsescript.core; + + +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipsescript.messages.Messages; +import org.eclipsescript.scripts.ScriptMetadata; +import org.eclipsescript.scripts.ScriptStore; +import org.eclipsescript.ui.ErrorHandlingHandler; +import org.eclipsescript.util.EclipseUtils; + +public class RunLastHandler extends ErrorHandlingHandler { + + public static ScriptMetadata lastRun = null; + + @Override + public void doExecute(ExecutionEvent event) throws ExecutionException { + if (lastRun == null) { + MessageDialog.openWarning(EclipseUtils.activeWindow().getShell(), "No script to run", //$NON-NLS-1$ + Messages.runScriptBeforeRunningLast); + } else { + ScriptStore.executeScript(lastRun); + } + } +} diff --git a/src/org/eclipsescript/javascript/JavaScriptLanguageSupport.java b/src/org/eclipsescript/javascript/JavaScriptLanguageSupport.java index 38fe8d0..75d0336 100644 --- a/src/org/eclipsescript/javascript/JavaScriptLanguageSupport.java +++ b/src/org/eclipsescript/javascript/JavaScriptLanguageSupport.java @@ -1,40 +1,40 @@ -package org.eclipsescript.javascript; - -import org.eclipsescript.javascript.CustomContextFactory.CustomContext; -import org.eclipsescript.rhino.javascript.Context; -import org.eclipsescript.rhino.javascript.ContextAction; -import org.eclipsescript.rhino.javascript.ImporterTopLevel; -import org.eclipsescript.rhino.javascript.ScriptableObject; -import org.eclipsescript.scriptobjects.Eclipse; -import org.eclipsescript.scripts.IScriptLanguageSupport; -import org.eclipsescript.scripts.ScriptMetadata; - -public class JavaScriptLanguageSupport implements IScriptLanguageSupport { - - private final CustomContextFactory contextFactory = new CustomContextFactory(); - - @Override - public void executeScript(final ScriptMetadata script) { - contextFactory.call(new ContextAction() { - @Override - public Object run(Context _context) { - if (!(_context instanceof CustomContext)) - throw new IllegalArgumentException("Wrong context class: " + _context.getClass()); //$NON-NLS-1$ - CustomContext context = (CustomContext) _context; - ScriptableObject scope = new ImporterTopLevel(context); - JavascriptRuntime jsRuntime = new JavascriptRuntime(context, scope, script); - - Eclipse eclipseJavaObject = new Eclipse(jsRuntime); - Object eclipseJsObject = Context.javaToJS(eclipseJavaObject, scope); - ScriptableObject.putConstProperty(scope, Eclipse.VARIABLE_NAME, eclipseJsObject); - - try { - jsRuntime.evaluate(script.getFile(), false); - } catch (Throwable e) { - jsRuntime.handleExceptionFromScriptRuntime(e); - } - return null; - } - }); - } -} +package org.eclipsescript.javascript; + +import org.eclipsescript.javascript.CustomContextFactory.CustomContext; +import org.eclipsescript.rhino.javascript.Context; +import org.eclipsescript.rhino.javascript.ContextAction; +import org.eclipsescript.rhino.javascript.ImporterTopLevel; +import org.eclipsescript.rhino.javascript.ScriptableObject; +import org.eclipsescript.scriptobjects.Eclipse; +import org.eclipsescript.scripts.IScriptLanguageSupport; +import org.eclipsescript.scripts.ScriptMetadata; + +public class JavaScriptLanguageSupport implements IScriptLanguageSupport { + + private final CustomContextFactory contextFactory = new CustomContextFactory(); + + @Override + public void executeScript(final ScriptMetadata script) { + contextFactory.call(new ContextAction() { + @Override + public Object run(Context _context) { + if (!(_context instanceof CustomContext)) + throw new IllegalArgumentException("Wrong context class: " + _context.getClass()); //$NON-NLS-1$ + CustomContext context = (CustomContext) _context; + ScriptableObject scope = new ImporterTopLevel(context); + JavascriptRuntime jsRuntime = new JavascriptRuntime(context, scope, script); + + Eclipse eclipseJavaObject = new Eclipse(jsRuntime); + Object eclipseJsObject = Context.javaToJS(eclipseJavaObject, scope); + ScriptableObject.putConstProperty(scope, Eclipse.VARIABLE_NAME, eclipseJsObject); + + try { + jsRuntime.evaluate(script.getFile(), false); + } catch (Throwable e) { + jsRuntime.handleExceptionFromScriptRuntime(e); + } + return null; + } + }); + } +} diff --git a/src/org/eclipsescript/messages/Messages.java b/src/org/eclipsescript/messages/Messages.java index 8b0c648..06d78d1 100644 --- a/src/org/eclipsescript/messages/Messages.java +++ b/src/org/eclipsescript/messages/Messages.java @@ -1,44 +1,44 @@ -package org.eclipsescript.messages; - -import org.eclipse.osgi.util.NLS; - -/** - * Localization messages using the {@link NLS} system. The static initializer block will initialize the fields of this - * class with values loaded from the messages properties file. - */ -public class Messages extends NLS { - - private static final String BUNDLE_NAME = Messages.class.getPackage().getName() + ".messages"; //$NON-NLS-1$ - - public static String cannotRunCurrentScriptText; - public static String cannotRunCurrentScriptTitle; - public static String clearMarkersJobName; - public static String fileToIncludeDoesNotExist; - public static String fileToReadDoesNotExist; - public static String internalErrorDialogDetails; - public static String internalErrorDialogText; - public static String internalErrorDialogTitle; - public static String noDocumentSelected; - public static String noSelectionSelected; - public static String noTextEditorSelected; - public static String notPossibleToScheduleObject; - public static String removeAllTerminatedConsoles; - public static String Resources_cannotReadFromObject; - public static String runScriptBeforeRunningLast; - public static String scriptAlertDialogTitle; - public static String scriptBackgroundJobName; - public static String scriptConfirmDialogTitle; - public static String scriptConsoleName; - public static String scriptErrorWhenRunningScriptDialogText; - public static String scriptErrorWhenRunningScriptDialogTitle; - public static String scriptErrorWhenRunningScriptJumpToScriptButton; - public static String scriptErrorWhenRunningScriptOkButton; - public static String scriptPromptDialogTitle; - public static String scriptTimeout; - public static String windowOpenArgumentNull; - - static { - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - -} +package org.eclipsescript.messages; + +import org.eclipse.osgi.util.NLS; + +/** + * Localization messages using the {@link NLS} system. The static initializer block will initialize the fields of this + * class with values loaded from the messages properties file. + */ +public class Messages extends NLS { + + private static final String BUNDLE_NAME = Messages.class.getPackage().getName() + ".messages"; //$NON-NLS-1$ + + public static String cannotRunCurrentScriptText; + public static String cannotRunCurrentScriptTitle; + public static String clearMarkersJobName; + public static String fileToIncludeDoesNotExist; + public static String fileToReadDoesNotExist; + public static String internalErrorDialogDetails; + public static String internalErrorDialogText; + public static String internalErrorDialogTitle; + public static String noDocumentSelected; + public static String noSelectionSelected; + public static String noTextEditorSelected; + public static String notPossibleToScheduleObject; + public static String removeAllTerminatedConsoles; + public static String Resources_cannotReadFromObject; + public static String runScriptBeforeRunningLast; + public static String scriptAlertDialogTitle; + public static String scriptBackgroundJobName; + public static String scriptConfirmDialogTitle; + public static String scriptConsoleName; + public static String scriptErrorWhenRunningScriptDialogText; + public static String scriptErrorWhenRunningScriptDialogTitle; + public static String scriptErrorWhenRunningScriptJumpToScriptButton; + public static String scriptErrorWhenRunningScriptOkButton; + public static String scriptPromptDialogTitle; + public static String scriptTimeout; + public static String windowOpenArgumentNull; + + static { + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } + +} diff --git a/src/org/eclipsescript/messages/messages.properties b/src/org/eclipsescript/messages/messages.properties index fe6cac4..48a6623 100644 --- a/src/org/eclipsescript/messages/messages.properties +++ b/src/org/eclipsescript/messages/messages.properties @@ -1,26 +1,26 @@ -internalErrorDialogTitle=EclipseScript Internal Error -internalErrorDialogText=The error has been logged. See below for details. -internalErrorDialogDetails=Plug-in name: {0}\nPlug-in ID: {1}\nVersion: {2}\n\n{3} -runScriptBeforeRunningLast=No EclipseScript script has been run\! -scriptAlertDialogTitle=EclipseScript Alert -scriptConfirmDialogTitle=EclipseScript Prompt -scriptConsoleName=EclipseScript: {0} -scriptErrorWhenRunningScriptDialogTitle=EclipseScript Error -scriptErrorWhenRunningScriptDialogText=Execution of the script "{0}" failed at line {2} with the following message:\n\n{1} -scriptErrorWhenRunningScriptJumpToScriptButton=&Go to script -scriptErrorWhenRunningScriptOkButton=&Ok -scriptTimeout = Script timeout after {0} seconds.\n\nTry using the eclipse.runtime.schedule(runnable) function for long-running background tasks. -scriptBackgroundJobName=EclipseScript: {0} -scriptPromptDialogTitle=EclipseScript Prompt -cannotRunCurrentScriptText=Cannot run the currently edited script -cannotRunCurrentScriptTitle=Cannot run -clearMarkersJobName=Clear script markers -fileToIncludeDoesNotExist=File does not exist: -fileToReadDoesNotExist=File to read does not exist: -noDocumentSelected=No document selected\! -noSelectionSelected=No selection selected\! -noTextEditorSelected=No text editor selected\! -notPossibleToScheduleObject=Not possible to schedule object: -Resources_cannotReadFromObject=Cannot read from object: -windowOpenArgumentNull=The urlString argument to open(urlString) was null +internalErrorDialogTitle=EclipseScript Internal Error +internalErrorDialogText=The error has been logged. See below for details. +internalErrorDialogDetails=Plug-in name: {0}\nPlug-in ID: {1}\nVersion: {2}\n\n{3} +runScriptBeforeRunningLast=No EclipseScript script has been run\! +scriptAlertDialogTitle=EclipseScript Alert +scriptConfirmDialogTitle=EclipseScript Prompt +scriptConsoleName=EclipseScript: {0} +scriptErrorWhenRunningScriptDialogTitle=EclipseScript Error +scriptErrorWhenRunningScriptDialogText=Execution of the script "{0}" failed at line {2} with the following message:\n\n{1} +scriptErrorWhenRunningScriptJumpToScriptButton=&Go to script +scriptErrorWhenRunningScriptOkButton=&Ok +scriptTimeout = Script timeout after {0} seconds.\n\nTry using the eclipse.runtime.schedule(runnable) function for long-running background tasks. +scriptBackgroundJobName=EclipseScript: {0} +scriptPromptDialogTitle=EclipseScript Prompt +cannotRunCurrentScriptText=Cannot run the currently edited script +cannotRunCurrentScriptTitle=Cannot run +clearMarkersJobName=Clear script markers +fileToIncludeDoesNotExist=File does not exist: +fileToReadDoesNotExist=File to read does not exist: +noDocumentSelected=No document selected\! +noSelectionSelected=No selection selected\! +noTextEditorSelected=No text editor selected\! +notPossibleToScheduleObject=Not possible to schedule object: +Resources_cannotReadFromObject=Cannot read from object: +windowOpenArgumentNull=The urlString argument to open(urlString) was null removeAllTerminatedConsoles=Remove All EclipseScript Consoles \ No newline at end of file diff --git a/src/org/eclipsescript/scriptobjects/Console.java b/src/org/eclipsescript/scriptobjects/Console.java index c0bd144..d6b5736 100644 --- a/src/org/eclipsescript/scriptobjects/Console.java +++ b/src/org/eclipsescript/scriptobjects/Console.java @@ -1,93 +1,93 @@ -package org.eclipsescript.scriptobjects; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.console.ConsolePlugin; -import org.eclipse.ui.console.IConsole; -import org.eclipse.ui.console.IConsoleManager; -import org.eclipse.ui.console.MessageConsole; -import org.eclipse.ui.console.MessageConsoleStream; -import org.eclipsescript.messages.Messages; -import org.eclipsescript.scripts.IScriptRuntime; -import org.eclipsescript.util.EclipseUtils; -import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable; - -public class Console { - - // just a marker superclass for enablement in console closer, see plugin.xml - public static class ConsoleClass extends MessageConsole { - public boolean isDisposed = false; - - public ConsoleClass(String name, ImageDescriptor imageDescriptor) { - super(name, imageDescriptor); - } - - @Override - protected void dispose() { - isDisposed = true; - super.dispose(); - } - - } - - private ConsoleClass console; - private final String name; - MessageConsoleStream out; - - public Console(IScriptRuntime runtime) { - this.name = NLS.bind(Messages.scriptConsoleName, runtime.getExecutingFile().getName()); - } - - void init() { - // Open a console for the first time or re-open - if (console == null || console.isDisposed) { - console = new ConsoleClass(name, null); - out = console.newMessageStream(); - ConsolePlugin consolePlugin = ConsolePlugin.getDefault(); - IConsoleManager consoleManager = consolePlugin.getConsoleManager(); - consoleManager.addConsoles(new IConsole[] { console }); - consoleManager.showConsoleView(console); - } - } - - public void print(final String msg) throws Exception { - EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() { - - @Override - public void runWithDisplay(Display display) throws Exception { - init(); - out.print(msg); - } - - }); - } - - public void println(final String msg) throws Exception { - EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() { - - @Override - public void runWithDisplay(Display display) throws Exception { - init(); - out.println(msg); - } - - }); - } - - public void printStackTrace(final Throwable t) throws Exception { - EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() { - - @Override - public void runWithDisplay(Display display) throws Exception { - init(); - out.println(t.getClass().getName()); - for (StackTraceElement stack : t.getStackTrace()) { - out.println("\t at " + stack.toString()); //$NON-NLS-1$ - } - } - - }); - } - -} +package org.eclipsescript.scriptobjects; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.console.ConsolePlugin; +import org.eclipse.ui.console.IConsole; +import org.eclipse.ui.console.IConsoleManager; +import org.eclipse.ui.console.MessageConsole; +import org.eclipse.ui.console.MessageConsoleStream; +import org.eclipsescript.messages.Messages; +import org.eclipsescript.scripts.IScriptRuntime; +import org.eclipsescript.util.EclipseUtils; +import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable; + +public class Console { + + // just a marker superclass for enablement in console closer, see plugin.xml + public static class ConsoleClass extends MessageConsole { + public boolean isDisposed = false; + + public ConsoleClass(String name, ImageDescriptor imageDescriptor) { + super(name, imageDescriptor); + } + + @Override + protected void dispose() { + isDisposed = true; + super.dispose(); + } + + } + + private ConsoleClass console; + private final String name; + MessageConsoleStream out; + + public Console(IScriptRuntime runtime) { + this.name = NLS.bind(Messages.scriptConsoleName, runtime.getExecutingFile().getName()); + } + + void init() { + // Open a console for the first time or re-open + if (console == null || console.isDisposed) { + console = new ConsoleClass(name, null); + out = console.newMessageStream(); + ConsolePlugin consolePlugin = ConsolePlugin.getDefault(); + IConsoleManager consoleManager = consolePlugin.getConsoleManager(); + consoleManager.addConsoles(new IConsole[] { console }); + consoleManager.showConsoleView(console); + } + } + + public void print(final String msg) throws Exception { + EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() { + + @Override + public void runWithDisplay(Display display) throws Exception { + init(); + out.print(msg); + } + + }); + } + + public void println(final String msg) throws Exception { + EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() { + + @Override + public void runWithDisplay(Display display) throws Exception { + init(); + out.println(msg); + } + + }); + } + + public void printStackTrace(final Throwable t) throws Exception { + EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() { + + @Override + public void runWithDisplay(Display display) throws Exception { + init(); + out.println(t.getClass().getName()); + for (StackTraceElement stack : t.getStackTrace()) { + out.println("\t at " + stack.toString()); //$NON-NLS-1$ + } + } + + }); + } + +} diff --git a/src/org/eclipsescript/scriptobjects/Resources.java b/src/org/eclipsescript/scriptobjects/Resources.java index 0aafbf9..9034361 100644 --- a/src/org/eclipsescript/scriptobjects/Resources.java +++ b/src/org/eclipsescript/scriptobjects/Resources.java @@ -1,153 +1,153 @@ -package org.eclipsescript.scriptobjects; - -import static java.util.regex.Pattern.compile; - -import java.io.InputStream; -import java.io.Reader; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Path; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipsescript.messages.Messages; -import org.eclipsescript.scripts.IScriptRuntime; -import org.eclipsescript.util.JavaUtils; - -public class Resources { - - private final IScriptRuntime scriptRuntime; - - public Resources(IScriptRuntime scriptRuntime) { - this.scriptRuntime = scriptRuntime; - } - - public IFile[] filesMatching(final String patternString, IResource startingPoint) { - final Pattern pattern = compile(patternString); - final List result = new ArrayList(); - try { - walk(startingPoint, pattern, result); - } catch (final CoreException x) { - // ignore Eclipse internal errors - } - return result.toArray(new IFile[result.size()]); - } - - /** Get the currently selected project. */ - public IProject getCurrentProject() { - IWorkbench workbench = PlatformUI.getWorkbench(); - IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - if (window == null) { - IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); - if (windows != null) { - window = windows[0]; - } - } - if (window == null) - return null; - IWorkbenchPage activePage = window.getActivePage(); - if (activePage == null) - return null; - IEditorPart activeEditor = activePage.getActiveEditor(); - if (activeEditor == null) - return null; - IEditorInput editorInput = activeEditor.getEditorInput(); - if (editorInput == null) - return null; - IResource resource = (IResource) editorInput.getAdapter(IResource.class); - if (resource == null) - return null; - return resource.getProject(); - } - - // note that exists() should be called to determine existence - public IProject getProject(String projectName) { - return ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); - } - - /** Get the project of the currently executing script. */ - public IProject getScriptProject() { - if (scriptRuntime == null) - return null; - if (scriptRuntime.getExecutingFile() == null) - return null; - return scriptRuntime.getExecutingFile().getProject(); - } - - public IWorkspace getWorkspace() { - return ResourcesPlugin.getWorkspace(); - } - - public String read(Object objectToRead) throws Exception { - if (objectToRead instanceof IFile) { - IFile file = (IFile) objectToRead; - return JavaUtils.readAllToStringAndClose(file.getContents(true), file.getCharset()); - } else if (objectToRead instanceof URLConnection) { - URLConnection uc = (URLConnection) objectToRead; - return JavaUtils.readURLConnection(uc); - } else if (objectToRead instanceof URL) { - URL url = (URL) objectToRead; - return JavaUtils.readURL(url); - } else if (objectToRead instanceof String) { - String string = (String) objectToRead; - if (string.contains("://")) { //$NON-NLS-1$ - URL url = new URL(string); - return JavaUtils.readURL(url); - } else { - Path includePath = new Path(string); - IContainer parent = string.startsWith("/") ? scriptRuntime.getExecutingFile().getProject() //$NON-NLS-1$ - : scriptRuntime.getExecutingFile().getParent(); - IFile fileToRead = parent.getFile(includePath); - if (!fileToRead.exists()) - scriptRuntime.abortRunningScript(Messages.fileToReadDoesNotExist - + fileToRead.getFullPath().toOSString()); - return JavaUtils.readAllToStringAndClose(fileToRead.getContents(true), fileToRead.getCharset()); - } - } else if (objectToRead instanceof Reader) { - Reader in = (Reader) objectToRead; - return JavaUtils.readAllToStringAndClose(in); - } else if (objectToRead instanceof InputStream) { - InputStream in = (InputStream) objectToRead; - return JavaUtils.readAllToStringAndClose(in); - } - throw new IllegalArgumentException(Messages.Resources_cannotReadFromObject + objectToRead); - } - - private void walk(final IResource resource, final Pattern pattern, final Collection result) - throws CoreException { - if (resource instanceof IProject) { - final IProject project = (IProject) resource; - if (!project.isOpen()) - return; - final IResource[] children = project.members(); - for (final IResource resource2 : children) - walk(resource2, pattern, result); - } else if (resource instanceof IContainer) { - final IResource[] children = ((IContainer) resource).members(); - for (final IResource resource2 : children) { - walk(resource2, pattern, result); - } - } else if (resource instanceof IFile) { - final String path = resource.getFullPath().toString(); - final Matcher match = pattern.matcher(path); - if (match.matches()) - result.add((IFile) resource); - } - } -} +package org.eclipsescript.scriptobjects; + +import static java.util.regex.Pattern.compile; + +import java.io.InputStream; +import java.io.Reader; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.Path; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; +import org.eclipsescript.messages.Messages; +import org.eclipsescript.scripts.IScriptRuntime; +import org.eclipsescript.util.JavaUtils; + +public class Resources { + + private final IScriptRuntime scriptRuntime; + + public Resources(IScriptRuntime scriptRuntime) { + this.scriptRuntime = scriptRuntime; + } + + public IFile[] filesMatching(final String patternString, IResource startingPoint) { + final Pattern pattern = compile(patternString); + final List result = new ArrayList(); + try { + walk(startingPoint, pattern, result); + } catch (final CoreException x) { + // ignore Eclipse internal errors + } + return result.toArray(new IFile[result.size()]); + } + + /** Get the currently selected project. */ + public IProject getCurrentProject() { + IWorkbench workbench = PlatformUI.getWorkbench(); + IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + if (window == null) { + IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); + if (windows != null) { + window = windows[0]; + } + } + if (window == null) + return null; + IWorkbenchPage activePage = window.getActivePage(); + if (activePage == null) + return null; + IEditorPart activeEditor = activePage.getActiveEditor(); + if (activeEditor == null) + return null; + IEditorInput editorInput = activeEditor.getEditorInput(); + if (editorInput == null) + return null; + IResource resource = (IResource) editorInput.getAdapter(IResource.class); + if (resource == null) + return null; + return resource.getProject(); + } + + // note that exists() should be called to determine existence + public IProject getProject(String projectName) { + return ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); + } + + /** Get the project of the currently executing script. */ + public IProject getScriptProject() { + if (scriptRuntime == null) + return null; + if (scriptRuntime.getExecutingFile() == null) + return null; + return scriptRuntime.getExecutingFile().getProject(); + } + + public IWorkspace getWorkspace() { + return ResourcesPlugin.getWorkspace(); + } + + public String read(Object objectToRead) throws Exception { + if (objectToRead instanceof IFile) { + IFile file = (IFile) objectToRead; + return JavaUtils.readAllToStringAndClose(file.getContents(true), file.getCharset()); + } else if (objectToRead instanceof URLConnection) { + URLConnection uc = (URLConnection) objectToRead; + return JavaUtils.readURLConnection(uc); + } else if (objectToRead instanceof URL) { + URL url = (URL) objectToRead; + return JavaUtils.readURL(url); + } else if (objectToRead instanceof String) { + String string = (String) objectToRead; + if (string.contains("://")) { //$NON-NLS-1$ + URL url = new URL(string); + return JavaUtils.readURL(url); + } else { + Path includePath = new Path(string); + IContainer parent = string.startsWith("/") ? scriptRuntime.getExecutingFile().getProject() //$NON-NLS-1$ + : scriptRuntime.getExecutingFile().getParent(); + IFile fileToRead = parent.getFile(includePath); + if (!fileToRead.exists()) + scriptRuntime.abortRunningScript(Messages.fileToReadDoesNotExist + + fileToRead.getFullPath().toOSString()); + return JavaUtils.readAllToStringAndClose(fileToRead.getContents(true), fileToRead.getCharset()); + } + } else if (objectToRead instanceof Reader) { + Reader in = (Reader) objectToRead; + return JavaUtils.readAllToStringAndClose(in); + } else if (objectToRead instanceof InputStream) { + InputStream in = (InputStream) objectToRead; + return JavaUtils.readAllToStringAndClose(in); + } + throw new IllegalArgumentException(Messages.Resources_cannotReadFromObject + objectToRead); + } + + private void walk(final IResource resource, final Pattern pattern, final Collection result) + throws CoreException { + if (resource instanceof IProject) { + final IProject project = (IProject) resource; + if (!project.isOpen()) + return; + final IResource[] children = project.members(); + for (final IResource resource2 : children) + walk(resource2, pattern, result); + } else if (resource instanceof IContainer) { + final IResource[] children = ((IContainer) resource).members(); + for (final IResource resource2 : children) { + walk(resource2, pattern, result); + } + } else if (resource instanceof IFile) { + final String path = resource.getFullPath().toString(); + final Matcher match = pattern.matcher(path); + if (match.matches()) + result.add((IFile) resource); + } + } +} diff --git a/src/org/eclipsescript/scriptobjects/Runtime.java b/src/org/eclipsescript/scriptobjects/Runtime.java index 54543bc..85d42c9 100644 --- a/src/org/eclipsescript/scriptobjects/Runtime.java +++ b/src/org/eclipsescript/scriptobjects/Runtime.java @@ -1,110 +1,110 @@ -package org.eclipsescript.scriptobjects; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.WorkspaceJob; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.progress.IJobRunnable; -import org.eclipsescript.messages.Messages; -import org.eclipsescript.scripts.IScriptRuntime; -import org.eclipsescript.util.EclipseUtils; - -/** - * Object which is put under eclipse.runtime in the script scope containing methods for manipulating the - * currently executing scripts runtime. - */ -public class Runtime { - - private static final Map globals = new HashMap(); - private final IScriptRuntime scriptRuntime; - - public Runtime(IScriptRuntime scriptRuntime) { - this.scriptRuntime = scriptRuntime; - } - - public void asyncExec(Runnable runnable) { - IWorkbench workbench = PlatformUI.getWorkbench(); - workbench.getDisplay().asyncExec(runnable); - } - - public void die(String message) { - scriptRuntime.abortRunningScript(message); - } - - public void disableTimeout() { - scriptRuntime.disableTimeout(); - } - - public void exit() { - scriptRuntime.exitRunningScript(); - } - - public synchronized Object getGlobal(String key) { - return globals.get(key); - } - - public Shell getShell() { - return EclipseUtils.getWindowShell(); - } - - public void include(Object... includes) throws Exception { - for (Object includeObject : includes) { - IFile fileToInclude; - if (includeObject instanceof IFile) { - fileToInclude = (IFile) includeObject; - } else { - String includeStringPath = (String) includeObject; - Path includePath = new Path(includeStringPath); - IFile executingScriptFile = scriptRuntime.getExecutingFile(); - IContainer startingScriptContainer = executingScriptFile.getParent(); - if (includePath.isAbsolute()) { - fileToInclude = startingScriptContainer.getWorkspace().getRoot().getFile(includePath); - } else { - fileToInclude = startingScriptContainer.getFile(includePath); - } - } - if (!fileToInclude.exists()) - scriptRuntime.abortRunningScript(Messages.fileToIncludeDoesNotExist - + fileToInclude.getFullPath().toOSString()); - scriptRuntime.evaluate(fileToInclude, true); - } - } - - public synchronized void putGlobal(String key, Object value) { - globals.put(key, value); - } - - public void schedule(final Object objectToSchedule) { - final IJobRunnable runnable = scriptRuntime.adaptTo(objectToSchedule, IJobRunnable.class); - if (runnable == null) - throw new IllegalArgumentException(Messages.notPossibleToScheduleObject + objectToSchedule); - String jobName = NLS.bind(Messages.scriptBackgroundJobName, scriptRuntime.getExecutingFile().getName()); - final IScriptRuntime runtime = scriptRuntime; - final IFile executingFile = scriptRuntime.getExecutingFile(); - Job job = new WorkspaceJob(jobName) { - @Override - public IStatus runInWorkspace(IProgressMonitor monitor) { - runtime.setExecutingFile(executingFile); - return runnable.run(monitor); - } - }; - job.setSystem(false); - job.setUser(true); - job.schedule(); - } - - public void syncExec(Runnable runnable) { - IWorkbench workbench = PlatformUI.getWorkbench(); - workbench.getDisplay().syncExec(runnable); - } -} +package org.eclipsescript.scriptobjects; + +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.WorkspaceJob; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.progress.IJobRunnable; +import org.eclipsescript.messages.Messages; +import org.eclipsescript.scripts.IScriptRuntime; +import org.eclipsescript.util.EclipseUtils; + +/** + * Object which is put under eclipse.runtime in the script scope containing methods for manipulating the + * currently executing scripts runtime. + */ +public class Runtime { + + private static final Map globals = new HashMap(); + private final IScriptRuntime scriptRuntime; + + public Runtime(IScriptRuntime scriptRuntime) { + this.scriptRuntime = scriptRuntime; + } + + public void asyncExec(Runnable runnable) { + IWorkbench workbench = PlatformUI.getWorkbench(); + workbench.getDisplay().asyncExec(runnable); + } + + public void die(String message) { + scriptRuntime.abortRunningScript(message); + } + + public void disableTimeout() { + scriptRuntime.disableTimeout(); + } + + public void exit() { + scriptRuntime.exitRunningScript(); + } + + public synchronized Object getGlobal(String key) { + return globals.get(key); + } + + public Shell getShell() { + return EclipseUtils.getWindowShell(); + } + + public void include(Object... includes) throws Exception { + for (Object includeObject : includes) { + IFile fileToInclude; + if (includeObject instanceof IFile) { + fileToInclude = (IFile) includeObject; + } else { + String includeStringPath = (String) includeObject; + Path includePath = new Path(includeStringPath); + IFile executingScriptFile = scriptRuntime.getExecutingFile(); + IContainer startingScriptContainer = executingScriptFile.getParent(); + if (includePath.isAbsolute()) { + fileToInclude = startingScriptContainer.getWorkspace().getRoot().getFile(includePath); + } else { + fileToInclude = startingScriptContainer.getFile(includePath); + } + } + if (!fileToInclude.exists()) + scriptRuntime.abortRunningScript(Messages.fileToIncludeDoesNotExist + + fileToInclude.getFullPath().toOSString()); + scriptRuntime.evaluate(fileToInclude, true); + } + } + + public synchronized void putGlobal(String key, Object value) { + globals.put(key, value); + } + + public void schedule(final Object objectToSchedule) { + final IJobRunnable runnable = scriptRuntime.adaptTo(objectToSchedule, IJobRunnable.class); + if (runnable == null) + throw new IllegalArgumentException(Messages.notPossibleToScheduleObject + objectToSchedule); + String jobName = NLS.bind(Messages.scriptBackgroundJobName, scriptRuntime.getExecutingFile().getName()); + final IScriptRuntime runtime = scriptRuntime; + final IFile executingFile = scriptRuntime.getExecutingFile(); + Job job = new WorkspaceJob(jobName) { + @Override + public IStatus runInWorkspace(IProgressMonitor monitor) { + runtime.setExecutingFile(executingFile); + return runnable.run(monitor); + } + }; + job.setSystem(false); + job.setUser(true); + job.schedule(); + } + + public void syncExec(Runnable runnable) { + IWorkbench workbench = PlatformUI.getWorkbench(); + workbench.getDisplay().syncExec(runnable); + } +} diff --git a/src/org/eclipsescript/scriptobjects/Window.java b/src/org/eclipsescript/scriptobjects/Window.java index f51ce8a..5cdcc14 100644 --- a/src/org/eclipsescript/scriptobjects/Window.java +++ b/src/org/eclipsescript/scriptobjects/Window.java @@ -1,159 +1,159 @@ -package org.eclipsescript.scriptobjects; - -import java.net.MalformedURLException; -import java.net.URL; - - -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IEditorSite; -import org.eclipse.ui.IViewSite; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchPartSite; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.browser.IWebBrowser; -import org.eclipse.ui.browser.IWorkbenchBrowserSupport; -import org.eclipsescript.messages.Messages; -import org.eclipsescript.util.EclipseUtils; -import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable; -import org.eclipsescript.util.JavaUtils.MutableObject; - -public class Window { - - private static class PromptDialog extends Dialog { - - private final String promptText; - Text promptField; - String enteredText; - - public PromptDialog(Shell parentShell, String promptText) { - super(parentShell); - this.promptText = promptText; - } - - @Override - public boolean close() { - enteredText = promptField.getText(); - return super.close(); - } - - @Override - protected Control createDialogArea(Composite parent) { - Composite container = (Composite) super.createDialogArea(parent); - final GridLayout gridLayout = new GridLayout(); - gridLayout.numColumns = 1; - container.setLayout(gridLayout); - - final Label nameLabel = new Label(container, SWT.NONE); - nameLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false)); - nameLabel.setText(promptText + ":"); //$NON-NLS-1$ - - promptField = new Text(container, SWT.BORDER); - promptField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); - promptField.setText(""); //$NON-NLS-1$ - - return container; - } - - } - - public static void alert(final String message) throws Exception { - EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() { - @Override - public void runWithDisplay(Display display) { - MessageDialog.openInformation(EclipseUtils.activeWindow().getShell(), Messages.scriptAlertDialogTitle, - message); - } - }); - } - - public static boolean confirm(final String message) throws Exception { - final MutableObject enteredText = new MutableObject(); - EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() { - @Override - public void runWithDisplay(Display display) { - enteredText.value = MessageDialog.openConfirm(EclipseUtils.getWindowShell(), - Messages.scriptConfirmDialogTitle, message); - } - }); - return enteredText.value; - } - - public static IWebBrowser open(String urlString) throws PartInitException, MalformedURLException { - if (urlString == null) - throw new IllegalArgumentException(Messages.windowOpenArgumentNull); - URL url = new URL(urlString); - IWorkbench workbench = PlatformUI.getWorkbench(); - IWorkbenchBrowserSupport browserSupport = workbench.getBrowserSupport(); - IWebBrowser browser = browserSupport.createBrowser(IWorkbenchBrowserSupport.AS_EXTERNAL, null, null, null); - browser.openURL(url); - return browser; - } - - public static String prompt(final String message) throws Exception { - return prompt(message, ""); //$NON-NLS-1$ - } - - public static String prompt(final String message, final String initialValue) throws Exception { - final MutableObject enteredText = new MutableObject(); - EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() { - @Override - public void runWithDisplay(Display display) { - final PromptDialog dialog = new PromptDialog(EclipseUtils.getWindowShell(), message); - - // create the window shell so the title can be set - dialog.create(); - dialog.getShell().setText(Messages.scriptPromptDialogTitle); - if (initialValue != null) { - dialog.promptField.setText(initialValue); - } - // since the Window has the blockOnOpen property set to true, it - // will dipose of the shell upon close - if (dialog.open() == org.eclipse.jface.window.Window.OK) { - enteredText.value = dialog.enteredText; - } - } - }); - return enteredText.value; - } - - public void setStatus(final String status) throws Exception { - EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() { - @Override - public void runWithDisplay(Display display) { - IWorkbenchPage page = EclipseUtils.activePage(); - IWorkbenchPart part = page.getActivePart(); - IWorkbenchPartSite site = part.getSite(); - IActionBars actionBars = null; - if (site instanceof IEditorSite) { - IEditorSite editorSite = (IEditorSite) site; - actionBars = editorSite.getActionBars(); - } else if (site instanceof IViewSite) { - IViewSite viewSite = (IViewSite) site; - actionBars = viewSite.getActionBars(); - } - if (actionBars == null) - return; - IStatusLineManager statusLineManager = actionBars.getStatusLineManager(); - if (statusLineManager == null) - return; - statusLineManager.setMessage(status); - } - }); - } - -} +package org.eclipsescript.scriptobjects; + +import java.net.MalformedURLException; +import java.net.URL; + + +import org.eclipse.jface.action.IStatusLineManager; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IActionBars; +import org.eclipse.ui.IEditorSite; +import org.eclipse.ui.IViewSite; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchPartSite; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.browser.IWebBrowser; +import org.eclipse.ui.browser.IWorkbenchBrowserSupport; +import org.eclipsescript.messages.Messages; +import org.eclipsescript.util.EclipseUtils; +import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable; +import org.eclipsescript.util.JavaUtils.MutableObject; + +public class Window { + + private static class PromptDialog extends Dialog { + + private final String promptText; + Text promptField; + String enteredText; + + public PromptDialog(Shell parentShell, String promptText) { + super(parentShell); + this.promptText = promptText; + } + + @Override + public boolean close() { + enteredText = promptField.getText(); + return super.close(); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite container = (Composite) super.createDialogArea(parent); + final GridLayout gridLayout = new GridLayout(); + gridLayout.numColumns = 1; + container.setLayout(gridLayout); + + final Label nameLabel = new Label(container, SWT.NONE); + nameLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false)); + nameLabel.setText(promptText + ":"); //$NON-NLS-1$ + + promptField = new Text(container, SWT.BORDER); + promptField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); + promptField.setText(""); //$NON-NLS-1$ + + return container; + } + + } + + public static void alert(final String message) throws Exception { + EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() { + @Override + public void runWithDisplay(Display display) { + MessageDialog.openInformation(EclipseUtils.activeWindow().getShell(), Messages.scriptAlertDialogTitle, + message); + } + }); + } + + public static boolean confirm(final String message) throws Exception { + final MutableObject enteredText = new MutableObject(); + EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() { + @Override + public void runWithDisplay(Display display) { + enteredText.value = MessageDialog.openConfirm(EclipseUtils.getWindowShell(), + Messages.scriptConfirmDialogTitle, message); + } + }); + return enteredText.value; + } + + public static IWebBrowser open(String urlString) throws PartInitException, MalformedURLException { + if (urlString == null) + throw new IllegalArgumentException(Messages.windowOpenArgumentNull); + URL url = new URL(urlString); + IWorkbench workbench = PlatformUI.getWorkbench(); + IWorkbenchBrowserSupport browserSupport = workbench.getBrowserSupport(); + IWebBrowser browser = browserSupport.createBrowser(IWorkbenchBrowserSupport.AS_EXTERNAL, null, null, null); + browser.openURL(url); + return browser; + } + + public static String prompt(final String message) throws Exception { + return prompt(message, ""); //$NON-NLS-1$ + } + + public static String prompt(final String message, final String initialValue) throws Exception { + final MutableObject enteredText = new MutableObject(); + EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() { + @Override + public void runWithDisplay(Display display) { + final PromptDialog dialog = new PromptDialog(EclipseUtils.getWindowShell(), message); + + // create the window shell so the title can be set + dialog.create(); + dialog.getShell().setText(Messages.scriptPromptDialogTitle); + if (initialValue != null) { + dialog.promptField.setText(initialValue); + } + // since the Window has the blockOnOpen property set to true, it + // will dipose of the shell upon close + if (dialog.open() == org.eclipse.jface.window.Window.OK) { + enteredText.value = dialog.enteredText; + } + } + }); + return enteredText.value; + } + + public void setStatus(final String status) throws Exception { + EclipseUtils.runInDisplayThreadAsync(new DisplayThreadRunnable() { + @Override + public void runWithDisplay(Display display) { + IWorkbenchPage page = EclipseUtils.activePage(); + IWorkbenchPart part = page.getActivePart(); + IWorkbenchPartSite site = part.getSite(); + IActionBars actionBars = null; + if (site instanceof IEditorSite) { + IEditorSite editorSite = (IEditorSite) site; + actionBars = editorSite.getActionBars(); + } else if (site instanceof IViewSite) { + IViewSite viewSite = (IViewSite) site; + actionBars = viewSite.getActionBars(); + } + if (actionBars == null) + return; + IStatusLineManager statusLineManager = actionBars.getStatusLineManager(); + if (statusLineManager == null) + return; + statusLineManager.setMessage(status); + } + }); + } + +} diff --git a/src/org/eclipsescript/scripts/IScriptLanguageSupport.java b/src/org/eclipsescript/scripts/IScriptLanguageSupport.java index b7a9318..2d91385 100644 --- a/src/org/eclipsescript/scripts/IScriptLanguageSupport.java +++ b/src/org/eclipsescript/scripts/IScriptLanguageSupport.java @@ -1,10 +1,10 @@ -package org.eclipsescript.scripts; - -public interface IScriptLanguageSupport { - - /** - * Execute all scripts in the same contexts. - */ - public void executeScript(ScriptMetadata script); - -} +package org.eclipsescript.scripts; + +public interface IScriptLanguageSupport { + + /** + * Execute all scripts in the same contexts. + */ + public void executeScript(ScriptMetadata script); + +} diff --git a/src/org/eclipsescript/scripts/ScriptClassLoader.java b/src/org/eclipsescript/scripts/ScriptClassLoader.java index b10a1f3..6a7a39f 100644 --- a/src/org/eclipsescript/scripts/ScriptClassLoader.java +++ b/src/org/eclipsescript/scripts/ScriptClassLoader.java @@ -1,61 +1,61 @@ -package org.eclipsescript.scripts; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.eclipsescript.core.Activator; -import org.osgi.framework.Bundle; - -public class ScriptClassLoader extends ClassLoader { - - private final List bundles = new CopyOnWriteArrayList(); - private final ClassLoader loader; - private final List loaders = new CopyOnWriteArrayList(); - - public ScriptClassLoader(ClassLoader loader) { - this.loader = loader; - } - - public void addBundle(Bundle bundle) { - // note that this requires script to load bundles in dependant order... - bundles.add(0, bundle); - } - - public void addLoader(ClassLoader classLoader) { - // note that this requires script to load bundles in dependant order... - loaders.add(0, classLoader); - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - try { - return loader.loadClass(name); - } catch (ClassNotFoundException e) { - // ignore - } - - for (Bundle bundle : bundles) { - try { - return bundle.loadClass(name); - } catch (ClassNotFoundException e) { - // ignore - } - } - - for (ClassLoader classLoader : loaders) { - try { - return classLoader.loadClass(name); - } catch (ClassNotFoundException e) { - // ignore - } - } - - Bundle bundleContainingClass = Activator.getBundleExportingClass(name); - if (bundleContainingClass != null) { - addBundle(bundleContainingClass); - return bundleContainingClass.loadClass(name); - } - - return null; - } -} +package org.eclipsescript.scripts; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.eclipsescript.core.Activator; +import org.osgi.framework.Bundle; + +public class ScriptClassLoader extends ClassLoader { + + private final List bundles = new CopyOnWriteArrayList(); + private final ClassLoader loader; + private final List loaders = new CopyOnWriteArrayList(); + + public ScriptClassLoader(ClassLoader loader) { + this.loader = loader; + } + + public void addBundle(Bundle bundle) { + // note that this requires script to load bundles in dependant order... + bundles.add(0, bundle); + } + + public void addLoader(ClassLoader classLoader) { + // note that this requires script to load bundles in dependant order... + loaders.add(0, classLoader); + } + + @Override + public Class loadClass(String name) throws ClassNotFoundException { + try { + return loader.loadClass(name); + } catch (ClassNotFoundException e) { + // ignore + } + + for (Bundle bundle : bundles) { + try { + return bundle.loadClass(name); + } catch (ClassNotFoundException e) { + // ignore + } + } + + for (ClassLoader classLoader : loaders) { + try { + return classLoader.loadClass(name); + } catch (ClassNotFoundException e) { + // ignore + } + } + + Bundle bundleContainingClass = Activator.getBundleExportingClass(name); + if (bundleContainingClass != null) { + addBundle(bundleContainingClass); + return bundleContainingClass.loadClass(name); + } + + return null; + } +} diff --git a/src/org/eclipsescript/scripts/ScriptLanguageHandler.java b/src/org/eclipsescript/scripts/ScriptLanguageHandler.java index e91384b..5ddae89 100644 --- a/src/org/eclipsescript/scripts/ScriptLanguageHandler.java +++ b/src/org/eclipsescript/scripts/ScriptLanguageHandler.java @@ -1,33 +1,33 @@ -package org.eclipsescript.scripts; - -import java.util.Collections; -import java.util.Map; - -import org.eclipse.core.resources.IFile; -import org.eclipsescript.javascript.JavaScriptLanguageSupport; - -public class ScriptLanguageHandler { - - public static Map getLanguageSupports() { - return Collections.singletonMap("js", new JavaScriptLanguageSupport()); //$NON-NLS-1$ - } - - static IScriptLanguageSupport getScriptSupport(IFile file) { - String fileName = file.getName(); - int index = -1; - int len = 14; - index = fileName.lastIndexOf(".eclipse.auto."); //$NON-NLS-1$ - if (index == -1) { - len = 9; - index = fileName.lastIndexOf(".eclipse."); //$NON-NLS-1$ - } - if (index == -1) - return null; - String fileExtension = fileName.substring(index + len); - return getLanguageSupports().get(fileExtension); - } - - public static boolean isEclipseScriptFile(IFile file) { - return getScriptSupport(file) != null; - } -} +package org.eclipsescript.scripts; + +import java.util.Collections; +import java.util.Map; + +import org.eclipse.core.resources.IFile; +import org.eclipsescript.javascript.JavaScriptLanguageSupport; + +public class ScriptLanguageHandler { + + public static Map getLanguageSupports() { + return Collections.singletonMap("js", new JavaScriptLanguageSupport()); //$NON-NLS-1$ + } + + static IScriptLanguageSupport getScriptSupport(IFile file) { + String fileName = file.getName(); + int index = -1; + int len = 14; + index = fileName.lastIndexOf(".eclipse.auto."); //$NON-NLS-1$ + if (index == -1) { + len = 9; + index = fileName.lastIndexOf(".eclipse."); //$NON-NLS-1$ + } + if (index == -1) + return null; + String fileExtension = fileName.substring(index + len); + return getLanguageSupports().get(fileExtension); + } + + public static boolean isEclipseScriptFile(IFile file) { + return getScriptSupport(file) != null; + } +} diff --git a/src/org/eclipsescript/scripts/ScriptMetadata.java b/src/org/eclipsescript/scripts/ScriptMetadata.java index 263bf34..c5f8c9a 100644 --- a/src/org/eclipsescript/scripts/ScriptMetadata.java +++ b/src/org/eclipsescript/scripts/ScriptMetadata.java @@ -1,78 +1,78 @@ -package org.eclipsescript.scripts; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.util.concurrent.atomic.AtomicInteger; - - -import org.eclipse.core.resources.IFile; -import org.eclipsescript.core.Activator; - -public class ScriptMetadata implements Comparable { - - private static final AtomicInteger counter = new AtomicInteger(); - - private final IFile file; - private final int instanceId; - private final String label; - - public ScriptMetadata(IFile file) { - this.instanceId = counter.getAndIncrement(); - this.file = file; - - String fileName = file.getName(); - int index = fileName.lastIndexOf(".eclipse."); //$NON-NLS-1$ - String scriptName = fileName.substring(0, index); - - String firstLine = null; - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(file.getContents(true), file.getCharset())); - try { - firstLine = reader.readLine(); - } finally { - reader.close(); - } - } catch (Exception e) { - Activator.logError(e); - } - - if (firstLine == null) { - label = scriptName; - } else { - firstLine = firstLine.trim(); - if (firstLine.startsWith("//") || firstLine.startsWith("/*")) { //$NON-NLS-1$ //$NON-NLS-2$ - this.label = scriptName + " - " + firstLine.substring(2).trim(); //$NON-NLS-1$ - } else { - this.label = scriptName; - } - } - } - - @Override - public int compareTo(ScriptMetadata o) { - return instanceId - o.instanceId; - } - - @Override - public boolean equals(Object other) { - return (other instanceof ScriptMetadata) && ((ScriptMetadata) other).instanceId == instanceId; - } - - public IFile getFile() { - return file; - } - - public String getFullPath() { - return file.getFullPath().toString(); - } - - public String getLabel() { - return label; - } - - @Override - public int hashCode() { - return instanceId; - } - -} +package org.eclipsescript.scripts; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.concurrent.atomic.AtomicInteger; + + +import org.eclipse.core.resources.IFile; +import org.eclipsescript.core.Activator; + +public class ScriptMetadata implements Comparable { + + private static final AtomicInteger counter = new AtomicInteger(); + + private final IFile file; + private final int instanceId; + private final String label; + + public ScriptMetadata(IFile file) { + this.instanceId = counter.getAndIncrement(); + this.file = file; + + String fileName = file.getName(); + int index = fileName.lastIndexOf(".eclipse."); //$NON-NLS-1$ + String scriptName = fileName.substring(0, index); + + String firstLine = null; + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(file.getContents(true), file.getCharset())); + try { + firstLine = reader.readLine(); + } finally { + reader.close(); + } + } catch (Exception e) { + Activator.logError(e); + } + + if (firstLine == null) { + label = scriptName; + } else { + firstLine = firstLine.trim(); + if (firstLine.startsWith("//") || firstLine.startsWith("/*")) { //$NON-NLS-1$ //$NON-NLS-2$ + this.label = scriptName + " - " + firstLine.substring(2).trim(); //$NON-NLS-1$ + } else { + this.label = scriptName; + } + } + } + + @Override + public int compareTo(ScriptMetadata o) { + return instanceId - o.instanceId; + } + + @Override + public boolean equals(Object other) { + return (other instanceof ScriptMetadata) && ((ScriptMetadata) other).instanceId == instanceId; + } + + public IFile getFile() { + return file; + } + + public String getFullPath() { + return file.getFullPath().toString(); + } + + public String getLabel() { + return label; + } + + @Override + public int hashCode() { + return instanceId; + } + +} diff --git a/src/org/eclipsescript/scripts/ScriptStore.java b/src/org/eclipsescript/scripts/ScriptStore.java index 2ba89ed..c26aa3d 100644 --- a/src/org/eclipsescript/scripts/ScriptStore.java +++ b/src/org/eclipsescript/scripts/ScriptStore.java @@ -1,109 +1,109 @@ -package org.eclipsescript.scripts; - -import java.util.concurrent.Callable; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipsescript.core.Activator; -import org.eclipsescript.core.RunLastHandler; -import org.eclipsescript.messages.Messages; -import org.eclipsescript.ui.ErrorDetailsDialog; -import org.eclipsescript.util.EclipseUtils; -import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable; - -public class ScriptStore { - - public static T executeRunnableWhichMayThrowScriptException(final ScriptMetadata script, Callable r) { - try { - try { - return r.call(); - } catch (final ScriptException error) { - IFile file = getFile(script, error); - MarkerManager.addMarker(file, error); - EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() { - @Override - public void runWithDisplay(Display display) throws Exception { - showMessageOfferJumpToScript(script, error); - } - }); - } - } catch (Exception e) { - Activator.logError(e); - } - return null; - } - - public static void executeScript(final ScriptMetadata script) { - // add this even if script execution fails - RunLastHandler.lastRun = script; - final IScriptLanguageSupport languageSupport = ScriptLanguageHandler.getScriptSupport(script.getFile()); - - executeRunnableWhichMayThrowScriptException(script, new Callable() { - @Override - public Void call() throws Exception { - languageSupport.executeScript(script); - return null; - } - }); - } - - static IFile getFile(ScriptMetadata script, ScriptException scriptException) { - IFile file = null; - try { - String sourceName = scriptException.getSourceName(); - int hashIdx = sourceName.indexOf('#'); - if (hashIdx != -1) { - sourceName = sourceName.substring(0, hashIdx); - } - IPath path = new Path(sourceName); - file = script.getFile().getWorkspace().getRoot().getFile(path); - } catch (Throwable t) { - file = script.getFile(); - } - return file; - } - - static void showMessageOfferJumpToScript(ScriptMetadata script, ScriptException e) { - final String[] choices = new String[] { Messages.scriptErrorWhenRunningScriptOkButton, - Messages.scriptErrorWhenRunningScriptJumpToScriptButton }; - - int lineNumber = Math.max(e.getLineNumber(), 1); - IFile file = getFile(script, e); - - String dialogTitle = Messages.scriptErrorWhenRunningScriptDialogTitle; - String dialogText = NLS.bind(Messages.scriptErrorWhenRunningScriptDialogText, new Object[] { - script.getFile().getName(), e.getCause().getMessage(), Integer.toString(lineNumber) }); - - if (e.getScriptStackTrace() != null && !e.getScriptStackTrace().isEmpty()) { - dialogText = dialogText + "\n\n" + e.getScriptStackTrace(); //$NON-NLS-1$ - } - - int result = ErrorDetailsDialog.openError(EclipseUtils.getWindowShell(), dialogTitle, dialogText, e.getCause(), - choices, e.isShowStackTrace()); - if (result == 1) { - IEditorPart editorPart = EclipseUtils.openEditor(file); - if (editorPart instanceof ITextEditor) { - ITextEditor textEditor = (ITextEditor) editorPart; - IDocumentProvider provider = textEditor.getDocumentProvider(); - IDocument document = provider.getDocument(textEditor.getEditorInput()); - try { - int start = document.getLineOffset(lineNumber - 1); - textEditor.selectAndReveal(start, 0); - IWorkbenchPage page = textEditor.getSite().getPage(); - page.activate(textEditor); - } catch (BadLocationException e2) { - throw new RuntimeException(e2); - } - } - } - } -} +package org.eclipsescript.scripts; + +import java.util.concurrent.Callable; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipsescript.core.Activator; +import org.eclipsescript.core.RunLastHandler; +import org.eclipsescript.messages.Messages; +import org.eclipsescript.ui.ErrorDetailsDialog; +import org.eclipsescript.util.EclipseUtils; +import org.eclipsescript.util.EclipseUtils.DisplayThreadRunnable; + +public class ScriptStore { + + public static T executeRunnableWhichMayThrowScriptException(final ScriptMetadata script, Callable r) { + try { + try { + return r.call(); + } catch (final ScriptException error) { + IFile file = getFile(script, error); + MarkerManager.addMarker(file, error); + EclipseUtils.runInDisplayThreadSync(new DisplayThreadRunnable() { + @Override + public void runWithDisplay(Display display) throws Exception { + showMessageOfferJumpToScript(script, error); + } + }); + } + } catch (Exception e) { + Activator.logError(e); + } + return null; + } + + public static void executeScript(final ScriptMetadata script) { + // add this even if script execution fails + RunLastHandler.lastRun = script; + final IScriptLanguageSupport languageSupport = ScriptLanguageHandler.getScriptSupport(script.getFile()); + + executeRunnableWhichMayThrowScriptException(script, new Callable() { + @Override + public Void call() throws Exception { + languageSupport.executeScript(script); + return null; + } + }); + } + + static IFile getFile(ScriptMetadata script, ScriptException scriptException) { + IFile file = null; + try { + String sourceName = scriptException.getSourceName(); + int hashIdx = sourceName.indexOf('#'); + if (hashIdx != -1) { + sourceName = sourceName.substring(0, hashIdx); + } + IPath path = new Path(sourceName); + file = script.getFile().getWorkspace().getRoot().getFile(path); + } catch (Throwable t) { + file = script.getFile(); + } + return file; + } + + static void showMessageOfferJumpToScript(ScriptMetadata script, ScriptException e) { + final String[] choices = new String[] { Messages.scriptErrorWhenRunningScriptOkButton, + Messages.scriptErrorWhenRunningScriptJumpToScriptButton }; + + int lineNumber = Math.max(e.getLineNumber(), 1); + IFile file = getFile(script, e); + + String dialogTitle = Messages.scriptErrorWhenRunningScriptDialogTitle; + String dialogText = NLS.bind(Messages.scriptErrorWhenRunningScriptDialogText, new Object[] { + script.getFile().getName(), e.getCause().getMessage(), Integer.toString(lineNumber) }); + + if (e.getScriptStackTrace() != null && !e.getScriptStackTrace().isEmpty()) { + dialogText = dialogText + "\n\n" + e.getScriptStackTrace(); //$NON-NLS-1$ + } + + int result = ErrorDetailsDialog.openError(EclipseUtils.getWindowShell(), dialogTitle, dialogText, e.getCause(), + choices, e.isShowStackTrace()); + if (result == 1) { + IEditorPart editorPart = EclipseUtils.openEditor(file); + if (editorPart instanceof ITextEditor) { + ITextEditor textEditor = (ITextEditor) editorPart; + IDocumentProvider provider = textEditor.getDocumentProvider(); + IDocument document = provider.getDocument(textEditor.getEditorInput()); + try { + int start = document.getLineOffset(lineNumber - 1); + textEditor.selectAndReveal(start, 0); + IWorkbenchPage page = textEditor.getSite().getPage(); + page.activate(textEditor); + } catch (BadLocationException e2) { + throw new RuntimeException(e2); + } + } + } + } +} diff --git a/src/org/eclipsescript/ui/CloseConsolePageParticipant.java b/src/org/eclipsescript/ui/CloseConsolePageParticipant.java index 71700ea..ff9f56c 100644 --- a/src/org/eclipsescript/ui/CloseConsolePageParticipant.java +++ b/src/org/eclipsescript/ui/CloseConsolePageParticipant.java @@ -1,77 +1,77 @@ -package org.eclipsescript.ui; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.console.ConsolePlugin; -import org.eclipse.ui.console.IConsole; -import org.eclipse.ui.console.IConsoleConstants; -import org.eclipse.ui.console.IConsoleManager; -import org.eclipse.ui.console.IConsolePageParticipant; -import org.eclipse.ui.console.actions.CloseConsoleAction; -import org.eclipse.ui.part.IPageBookViewPage; -import org.eclipse.ui.part.IPageSite; -import org.eclipsescript.core.Activator; -import org.eclipsescript.messages.Messages; -import org.eclipsescript.scriptobjects.Console; - -public class CloseConsolePageParticipant implements IConsolePageParticipant { - - public static class RemoveAllTerminatedAction extends Action { - - public RemoveAllTerminatedAction() { - super(Messages.removeAllTerminatedConsoles, Activator.getImageDescriptor(Activator.IMG_REMOVE_ALL)); - setToolTipText(Messages.removeAllTerminatedConsoles); - } - - @Override - public void run() { - // ConsolePlugin.getDefault().getConsoleManager().removeConsoles(new IConsole[] { fConsole }); - ConsolePlugin consolePlugin = ConsolePlugin.getDefault(); - IConsoleManager consoleManager = consolePlugin.getConsoleManager(); - List consolesToRemove = new ArrayList(); - for (IConsole console : consoleManager.getConsoles()) { - if (console instanceof Console.ConsoleClass) { - ((Console.ConsoleClass) console).isDisposed = true; - consolesToRemove.add(console); - } - } - consoleManager.removeConsoles(consolesToRemove.toArray(new IConsole[consolesToRemove.size()])); - } - - } - - @Override - public void activated() { - // do nothing - } - - @Override - public void deactivated() { - // do nothing - } - - @Override - public void dispose() { - // do nothing - } - - @Override - public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { - return adapter.isInstance(this) ? this : null; - } - - /** Method overridden to add close console action to the console toolbar. */ - @Override - public void init(IPageBookViewPage page, IConsole console) { - CloseConsoleAction action = new CloseConsoleAction(console); - IPageSite site = page.getSite(); - IActionBars actionBars = site.getActionBars(); - IToolBarManager manager = actionBars.getToolBarManager(); - manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, action); - manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, new RemoveAllTerminatedAction()); - } -} +package org.eclipsescript.ui; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.ui.IActionBars; +import org.eclipse.ui.console.ConsolePlugin; +import org.eclipse.ui.console.IConsole; +import org.eclipse.ui.console.IConsoleConstants; +import org.eclipse.ui.console.IConsoleManager; +import org.eclipse.ui.console.IConsolePageParticipant; +import org.eclipse.ui.console.actions.CloseConsoleAction; +import org.eclipse.ui.part.IPageBookViewPage; +import org.eclipse.ui.part.IPageSite; +import org.eclipsescript.core.Activator; +import org.eclipsescript.messages.Messages; +import org.eclipsescript.scriptobjects.Console; + +public class CloseConsolePageParticipant implements IConsolePageParticipant { + + public static class RemoveAllTerminatedAction extends Action { + + public RemoveAllTerminatedAction() { + super(Messages.removeAllTerminatedConsoles, Activator.getImageDescriptor(Activator.IMG_REMOVE_ALL)); + setToolTipText(Messages.removeAllTerminatedConsoles); + } + + @Override + public void run() { + // ConsolePlugin.getDefault().getConsoleManager().removeConsoles(new IConsole[] { fConsole }); + ConsolePlugin consolePlugin = ConsolePlugin.getDefault(); + IConsoleManager consoleManager = consolePlugin.getConsoleManager(); + List consolesToRemove = new ArrayList(); + for (IConsole console : consoleManager.getConsoles()) { + if (console instanceof Console.ConsoleClass) { + ((Console.ConsoleClass) console).isDisposed = true; + consolesToRemove.add(console); + } + } + consoleManager.removeConsoles(consolesToRemove.toArray(new IConsole[consolesToRemove.size()])); + } + + } + + @Override + public void activated() { + // do nothing + } + + @Override + public void deactivated() { + // do nothing + } + + @Override + public void dispose() { + // do nothing + } + + @Override + public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { + return adapter.isInstance(this) ? this : null; + } + + /** Method overridden to add close console action to the console toolbar. */ + @Override + public void init(IPageBookViewPage page, IConsole console) { + CloseConsoleAction action = new CloseConsoleAction(console); + IPageSite site = page.getSite(); + IActionBars actionBars = site.getActionBars(); + IToolBarManager manager = actionBars.getToolBarManager(); + manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, action); + manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, new RemoveAllTerminatedAction()); + } +} diff --git a/src/org/eclipsescript/ui/ErrorDetailsDialog.java b/src/org/eclipsescript/ui/ErrorDetailsDialog.java index 9b0d674..081e728 100644 --- a/src/org/eclipsescript/ui/ErrorDetailsDialog.java +++ b/src/org/eclipsescript/ui/ErrorDetailsDialog.java @@ -1,288 +1,288 @@ -package org.eclipsescript.ui; - -import java.io.PrintWriter; -import java.io.StringWriter; - - -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.IconAndMessageDialog; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.dnd.Clipboard; -import org.eclipse.swt.dnd.TextTransfer; -import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.MenuItem; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipsescript.core.Activator; -import org.eclipsescript.messages.Messages; -import org.osgi.framework.Constants; - -/** - * A dialog to display one or more errors to the user, as contained in an IStatus object. If an error - * contains additional detailed information then a Details button is automatically supplied, which shows or hides an - * error details viewer when pressed by the user. - * - *

- * This dialog should be considered being a "local" way of error handling. It cannot be changed or replaced by "global" - * error handling facility ( org.eclipse.ui.statushandler.StatusManager). If product defines its own way of - * handling errors, this error dialog may cause UI inconsistency, so until it is absolutely necessary, - * StatusManager should be used. - *

- * - * @see org.eclipse.core.runtime.IStatus - */ -public class ErrorDetailsDialog extends IconAndMessageDialog { - - public static int openError(Shell parent, String dialogTitle, String message, Throwable exception) { - return openError(parent, dialogTitle, message, exception, new String[] { IDialogConstants.OK_LABEL }, true); - } - - /** - * Opens an error dialog to display the given error. Use this method if the error object being displayed does not - * contain child items, or if you wish to display all such items without filtering. - * - * @param parent - * the parent shell of the dialog, or null if none - * @param dialogTitle - * the title to use for this dialog, or null to indicate that the default title should be - * used - * @param message - * the message to show in this dialog, or null to indicate that the error's message should - * be shown as the primary message - * @param choices - * @param status - * the error to show to the user - * @return the code of the button that was pressed that resulted in this dialog closing. This will be - * Dialog.OK if the OK button was pressed, or Dialog.CANCEL if this dialog's close - * window decoration or the ESC key was used. - */ - public static int openError(Shell parent, String dialogTitle, String message, Throwable exception2, - String[] choices, boolean showDetails) { - ErrorDetailsDialog dialog = new ErrorDetailsDialog(parent, dialogTitle, message, exception2, choices, - showDetails); - return dialog.open(); - } - - private final String[] choices; - private Button detailsButton; - private final String dialogTitle; - private Text errorDetailsText; - private final Throwable exception; - private final boolean showDetails; - - /** - * Creates an error dialog. Note that the dialog will have no visual representation (no widgets) until it is told to - * open. - *

- * Normally one should use openError to create and open one of these. This constructor is useful only - * if the error object being displayed contains child items and you need to specify a mask which will be - * used to filter the displaying of these children. The error dialog will only be displayed if there is at least one - * child status matching the mask. - *

- * - * @param parentShell - * the shell under which to create this dialog - * @param dialogTitle - * the title to use for this dialog, or null to indicate that the default title should be - * used - * @param message - * the message to show in this dialog, or null to indicate that the error's message should - * be shown as the primary message - * @param choices2 - */ - ErrorDetailsDialog(Shell parentShell, String dialogTitle, String message, Throwable exception, String[] choices, - boolean showDetails) { - super(parentShell); - this.dialogTitle = dialogTitle == null ? JFaceResources.getString("Problem_Occurred") : //$NON-NLS-1$ - dialogTitle; - this.message = message; - this.exception = exception; - this.choices = choices; - this.showDetails = showDetails; - } - - /* - * (non-Javadoc) Method declared on Dialog. Handles the pressing of the Ok or Details button in this dialog. If the - * Ok button was pressed then close this dialog. If the Details button was pressed then toggle the displaying of the - * error details area. Note that the Details button will only be visible if the error being displayed specifies - * child details. - */ - @Override - protected void buttonPressed(int id) { - if (id == IDialogConstants.DETAILS_ID) { - // was the details button pressed? - toggleDetailsArea(); - } else { - setReturnCode(id); - close(); - } - } - - @Override - protected void configureShell(Shell shell) { - super.configureShell(shell); - shell.setText(dialogTitle); - } - - /** Copy the contents of the statuses to the clipboard. */ - void copyToClipboard() { - String textToCopy = errorDetailsText.getText(); - Clipboard clipboard = new Clipboard(errorDetailsText.getDisplay()); - try { - clipboard.setContents(new Object[] { textToCopy }, new Transfer[] { TextTransfer.getInstance() }); - } finally { - clipboard.dispose(); - } - } - - @Override - protected void createButtonsForButtonBar(Composite parent) { - // create OK and Details buttons - boolean defaultButton = true; - int id = 0; - for (String choice : choices) { - createButton(parent, id++, choice, defaultButton); - if (defaultButton) - defaultButton = false; - } - if (showDetails) { - detailsButton = createButton(parent, IDialogConstants.DETAILS_ID, IDialogConstants.SHOW_DETAILS_LABEL, - false); - } - } - - @Override - protected void createDialogAndButtonArea(Composite parent) { - super.createDialogAndButtonArea(parent); - if (this.dialogArea instanceof Composite) { - // Create a label if there are no children to force a smaller layout - Composite dialogComposite = (Composite) dialogArea; - if (dialogComposite.getChildren().length == 0) { - new Label(dialogComposite, SWT.NULL); - } - } - } - - /** - * This implementation of the Dialog framework method creates and lays out a composite. Subclasses that - * require a different dialog area may either override this method, or call the super implementation - * and add controls to the created composite. - * - * Note: Since 3.4, the created composite no longer grabs excess vertical space. See - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=72489. If the old behavior is desired by subclasses, get the - * returned composite's layout data and set grabExcessVerticalSpace to true. - */ - @Override - protected Control createDialogArea(Composite parent) { - // Create a composite with standard margins and spacing - // Add the messageArea to this composite so that as subclasses add widgets to the messageArea - // and dialogArea, the number of children of parent remains fixed and with consistent layout. - // Fixes bug #240135 - Composite composite = new Composite(parent, SWT.NONE); - createMessageArea(composite); - GridLayout layout = new GridLayout(); - layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.numColumns = 2; - composite.setLayout(layout); - GridData childData = new GridData(GridData.FILL_BOTH); - childData.horizontalSpan = 2; - childData.grabExcessVerticalSpace = false; - composite.setLayoutData(childData); - composite.setFont(parent.getFont()); - - return composite; - } - - /** - * Create this dialog's drop-down list component. - * - * @param parent - * the parent composite - * @return the drop-down list component - */ - protected Text createDropDownList(Composite parent) { - // create the list - errorDetailsText = new Text(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY | SWT.WRAP); - - StringWriter writer = new StringWriter(); - exception.printStackTrace(new PrintWriter(writer)); - String stackTraceText = writer.getBuffer().toString(); - - String detailsText = NLS.bind(Messages.internalErrorDialogDetails, new Object[] { - Activator.getDefault().getBundle().getHeaders().get(Constants.BUNDLE_NAME), - Activator.getDefault().getBundle().getSymbolicName(), - Activator.getDefault().getBundle().getHeaders().get(Constants.BUNDLE_VERSION), stackTraceText }); - errorDetailsText.setText(detailsText); - - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL - | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_VERTICAL); - data.heightHint = 300; - data.horizontalSpan = 2; - errorDetailsText.setLayoutData(data); - errorDetailsText.setFont(parent.getFont()); - Menu copyMenu = new Menu(errorDetailsText); - MenuItem copyItem = new MenuItem(copyMenu, SWT.NONE); - copyItem.addSelectionListener(new SelectionListener() { - /** @see SelectionListener.widgetDefaultSelected(SelectionEvent) */ - @Override - public void widgetDefaultSelected(SelectionEvent e) { - copyToClipboard(); - } - - /** @see SelectionListener.widgetSelected (SelectionEvent) */ - @Override - public void widgetSelected(SelectionEvent e) { - copyToClipboard(); - } - }); - copyItem.setText(JFaceResources.getString("copy")); //$NON-NLS-1$ - errorDetailsText.setMenu(copyMenu); - return errorDetailsText; - } - - @Override - protected Image getImage() { - // If it was not a warning or an error then return the error image - return getErrorImage(); - } - - @Override - protected boolean isResizable() { - return true; - } - - /** - * Toggles the unfolding of the details area. This is triggered by the user pressing the details button. - */ - private void toggleDetailsArea() { - Point windowSize = getShell().getSize(); - Point oldSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT); - if (errorDetailsText != null && !errorDetailsText.isDisposed()) { - errorDetailsText.dispose(); - detailsButton.setText(IDialogConstants.SHOW_DETAILS_LABEL); - } else { - errorDetailsText = createDropDownList((Composite) getContents()); - detailsButton.setText(IDialogConstants.HIDE_DETAILS_LABEL); - getContents().getShell().layout(); - } - Point newSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT); - getShell().setSize(new Point(windowSize.x, windowSize.y + (newSize.y - oldSize.y))); - } - -} +package org.eclipsescript.ui; + +import java.io.PrintWriter; +import java.io.StringWriter; + + +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.IconAndMessageDialog; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWT; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.TextTransfer; +import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipsescript.core.Activator; +import org.eclipsescript.messages.Messages; +import org.osgi.framework.Constants; + +/** + * A dialog to display one or more errors to the user, as contained in an IStatus object. If an error + * contains additional detailed information then a Details button is automatically supplied, which shows or hides an + * error details viewer when pressed by the user. + * + *

+ * This dialog should be considered being a "local" way of error handling. It cannot be changed or replaced by "global" + * error handling facility ( org.eclipse.ui.statushandler.StatusManager). If product defines its own way of + * handling errors, this error dialog may cause UI inconsistency, so until it is absolutely necessary, + * StatusManager should be used. + *

+ * + * @see org.eclipse.core.runtime.IStatus + */ +public class ErrorDetailsDialog extends IconAndMessageDialog { + + public static int openError(Shell parent, String dialogTitle, String message, Throwable exception) { + return openError(parent, dialogTitle, message, exception, new String[] { IDialogConstants.OK_LABEL }, true); + } + + /** + * Opens an error dialog to display the given error. Use this method if the error object being displayed does not + * contain child items, or if you wish to display all such items without filtering. + * + * @param parent + * the parent shell of the dialog, or null if none + * @param dialogTitle + * the title to use for this dialog, or null to indicate that the default title should be + * used + * @param message + * the message to show in this dialog, or null to indicate that the error's message should + * be shown as the primary message + * @param choices + * @param status + * the error to show to the user + * @return the code of the button that was pressed that resulted in this dialog closing. This will be + * Dialog.OK if the OK button was pressed, or Dialog.CANCEL if this dialog's close + * window decoration or the ESC key was used. + */ + public static int openError(Shell parent, String dialogTitle, String message, Throwable exception2, + String[] choices, boolean showDetails) { + ErrorDetailsDialog dialog = new ErrorDetailsDialog(parent, dialogTitle, message, exception2, choices, + showDetails); + return dialog.open(); + } + + private final String[] choices; + private Button detailsButton; + private final String dialogTitle; + private Text errorDetailsText; + private final Throwable exception; + private final boolean showDetails; + + /** + * Creates an error dialog. Note that the dialog will have no visual representation (no widgets) until it is told to + * open. + *

+ * Normally one should use openError to create and open one of these. This constructor is useful only + * if the error object being displayed contains child items and you need to specify a mask which will be + * used to filter the displaying of these children. The error dialog will only be displayed if there is at least one + * child status matching the mask. + *

+ * + * @param parentShell + * the shell under which to create this dialog + * @param dialogTitle + * the title to use for this dialog, or null to indicate that the default title should be + * used + * @param message + * the message to show in this dialog, or null to indicate that the error's message should + * be shown as the primary message + * @param choices2 + */ + ErrorDetailsDialog(Shell parentShell, String dialogTitle, String message, Throwable exception, String[] choices, + boolean showDetails) { + super(parentShell); + this.dialogTitle = dialogTitle == null ? JFaceResources.getString("Problem_Occurred") : //$NON-NLS-1$ + dialogTitle; + this.message = message; + this.exception = exception; + this.choices = choices; + this.showDetails = showDetails; + } + + /* + * (non-Javadoc) Method declared on Dialog. Handles the pressing of the Ok or Details button in this dialog. If the + * Ok button was pressed then close this dialog. If the Details button was pressed then toggle the displaying of the + * error details area. Note that the Details button will only be visible if the error being displayed specifies + * child details. + */ + @Override + protected void buttonPressed(int id) { + if (id == IDialogConstants.DETAILS_ID) { + // was the details button pressed? + toggleDetailsArea(); + } else { + setReturnCode(id); + close(); + } + } + + @Override + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText(dialogTitle); + } + + /** Copy the contents of the statuses to the clipboard. */ + void copyToClipboard() { + String textToCopy = errorDetailsText.getText(); + Clipboard clipboard = new Clipboard(errorDetailsText.getDisplay()); + try { + clipboard.setContents(new Object[] { textToCopy }, new Transfer[] { TextTransfer.getInstance() }); + } finally { + clipboard.dispose(); + } + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + // create OK and Details buttons + boolean defaultButton = true; + int id = 0; + for (String choice : choices) { + createButton(parent, id++, choice, defaultButton); + if (defaultButton) + defaultButton = false; + } + if (showDetails) { + detailsButton = createButton(parent, IDialogConstants.DETAILS_ID, IDialogConstants.SHOW_DETAILS_LABEL, + false); + } + } + + @Override + protected void createDialogAndButtonArea(Composite parent) { + super.createDialogAndButtonArea(parent); + if (this.dialogArea instanceof Composite) { + // Create a label if there are no children to force a smaller layout + Composite dialogComposite = (Composite) dialogArea; + if (dialogComposite.getChildren().length == 0) { + new Label(dialogComposite, SWT.NULL); + } + } + } + + /** + * This implementation of the Dialog framework method creates and lays out a composite. Subclasses that + * require a different dialog area may either override this method, or call the super implementation + * and add controls to the created composite. + * + * Note: Since 3.4, the created composite no longer grabs excess vertical space. See + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=72489. If the old behavior is desired by subclasses, get the + * returned composite's layout data and set grabExcessVerticalSpace to true. + */ + @Override + protected Control createDialogArea(Composite parent) { + // Create a composite with standard margins and spacing + // Add the messageArea to this composite so that as subclasses add widgets to the messageArea + // and dialogArea, the number of children of parent remains fixed and with consistent layout. + // Fixes bug #240135 + Composite composite = new Composite(parent, SWT.NONE); + createMessageArea(composite); + GridLayout layout = new GridLayout(); + layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.numColumns = 2; + composite.setLayout(layout); + GridData childData = new GridData(GridData.FILL_BOTH); + childData.horizontalSpan = 2; + childData.grabExcessVerticalSpace = false; + composite.setLayoutData(childData); + composite.setFont(parent.getFont()); + + return composite; + } + + /** + * Create this dialog's drop-down list component. + * + * @param parent + * the parent composite + * @return the drop-down list component + */ + protected Text createDropDownList(Composite parent) { + // create the list + errorDetailsText = new Text(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY | SWT.WRAP); + + StringWriter writer = new StringWriter(); + exception.printStackTrace(new PrintWriter(writer)); + String stackTraceText = writer.getBuffer().toString(); + + String detailsText = NLS.bind(Messages.internalErrorDialogDetails, new Object[] { + Activator.getDefault().getBundle().getHeaders().get(Constants.BUNDLE_NAME), + Activator.getDefault().getBundle().getSymbolicName(), + Activator.getDefault().getBundle().getHeaders().get(Constants.BUNDLE_VERSION), stackTraceText }); + errorDetailsText.setText(detailsText); + + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_VERTICAL); + data.heightHint = 300; + data.horizontalSpan = 2; + errorDetailsText.setLayoutData(data); + errorDetailsText.setFont(parent.getFont()); + Menu copyMenu = new Menu(errorDetailsText); + MenuItem copyItem = new MenuItem(copyMenu, SWT.NONE); + copyItem.addSelectionListener(new SelectionListener() { + /** @see SelectionListener.widgetDefaultSelected(SelectionEvent) */ + @Override + public void widgetDefaultSelected(SelectionEvent e) { + copyToClipboard(); + } + + /** @see SelectionListener.widgetSelected (SelectionEvent) */ + @Override + public void widgetSelected(SelectionEvent e) { + copyToClipboard(); + } + }); + copyItem.setText(JFaceResources.getString("copy")); //$NON-NLS-1$ + errorDetailsText.setMenu(copyMenu); + return errorDetailsText; + } + + @Override + protected Image getImage() { + // If it was not a warning or an error then return the error image + return getErrorImage(); + } + + @Override + protected boolean isResizable() { + return true; + } + + /** + * Toggles the unfolding of the details area. This is triggered by the user pressing the details button. + */ + private void toggleDetailsArea() { + Point windowSize = getShell().getSize(); + Point oldSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT); + if (errorDetailsText != null && !errorDetailsText.isDisposed()) { + errorDetailsText.dispose(); + detailsButton.setText(IDialogConstants.SHOW_DETAILS_LABEL); + } else { + errorDetailsText = createDropDownList((Composite) getContents()); + detailsButton.setText(IDialogConstants.HIDE_DETAILS_LABEL); + getContents().getShell().layout(); + } + Point newSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT); + getShell().setSize(new Point(windowSize.x, windowSize.y + (newSize.y - oldSize.y))); + } + +} diff --git a/src/org/eclipsescript/util/EclipseUtils.java b/src/org/eclipsescript/util/EclipseUtils.java index ddbad57..0581f11 100644 --- a/src/org/eclipsescript/util/EclipseUtils.java +++ b/src/org/eclipsescript/util/EclipseUtils.java @@ -1,179 +1,179 @@ -package org.eclipsescript.util; - -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorDescriptor; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IEditorRegistry; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.part.FileEditorInput; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipsescript.core.Activator; -import org.eclipsescript.util.JavaUtils.MutableObject; - -public class EclipseUtils { - - public static interface DisplayThreadCallable { - public T callWithDisplay(Display display) throws Exception; - } - - /** A runnable to run in the display thread. */ - public static interface DisplayThreadRunnable { - public void runWithDisplay(Display display) throws Exception; - } - - public static IWorkbenchPage activePage() { - return activeWindow().getActivePage(); - } - - public static IWorkbenchWindow activeWindow() { - return PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - } - - public static IDocument getCurrentDocument() { - ITextEditor editor = getCurrentTextEditor(); - if (editor == null) - return null; - IDocumentProvider documentProvider = editor.getDocumentProvider(); - IDocument document = documentProvider.getDocument(editor.getEditorInput()); - return document; - } - - public static IEditorInput getCurrentEditorInput() { - ITextEditor editor = getCurrentTextEditor(); - if (editor == null) - return null; - return editor.getEditorInput(); - } - - public static TextSelection getCurrentEditorSelection() { - ITextEditor editor = getCurrentTextEditor(); - if (editor == null) - return null; - ISelectionProvider selectionProvider = editor.getSelectionProvider(); - ISelection selection = selectionProvider.getSelection(); - if (selection instanceof TextSelection) { - TextSelection textSelection = (TextSelection) selection; - return textSelection; - } - return null; - } - - public static ITextEditor getCurrentTextEditor() { - IWorkbench workbench = PlatformUI.getWorkbench(); - IWorkbenchWindow activeWindow = workbench.getActiveWorkbenchWindow(); - IWorkbenchPage activePage = activeWindow.getActivePage(); - if (activePage == null) - return null; - IEditorPart activeEditor = activePage.getActiveEditor(); - if (activeEditor == null) - return null; - ITextEditor textEditor = (ITextEditor) activeEditor.getAdapter(ITextEditor.class); - return textEditor; - } - - public static IEditorDescriptor getDefaultEditor(final IFile file) { - if (file == null) - return null; - IWorkbench workbench = PlatformUI.getWorkbench(); - IEditorDescriptor descriptor = workbench.getEditorRegistry().getDefaultEditor(file.getName()); - if (descriptor != null) - return descriptor; - descriptor = workbench.getEditorRegistry().getDefaultEditor("simple_text_file.txt"); //$NON-NLS-1$ - if (descriptor != null) - return descriptor; - descriptor = workbench.getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); - if (descriptor != null) - return descriptor; - return workbench.getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); - } - - public static Shell getWindowShell() { - return activeWindow().getShell(); - } - - public static IEditorPart openEditor(final IFile file) { - final IEditorDescriptor descriptor = getDefaultEditor(file); - try { - return activePage().openEditor(new FileEditorInput(file), descriptor.getId()); - } catch (PartInitException e) { - Activator.logError(e); - return null; - } - } - - private static T runInDisplayThread(final DisplayThreadCallable runnable, final boolean sync) - throws Exception { - final Display display = PlatformUI.getWorkbench().getDisplay(); - - if (Thread.currentThread().equals(display.getThread())) { - return runnable.callWithDisplay(display); - } else { - final MutableObject exceptionThrownInUIThread = new MutableObject(); - final MutableObject result = new MutableObject(); - - Runnable showExceptionWrapper = new Runnable() { - @Override - public void run() { - try { - result.value = runnable.callWithDisplay(display); - } catch (Exception e) { - if (sync) { - exceptionThrownInUIThread.value = e; - } else { - Activator.logError(e); - } - } - } - }; - - if (sync) { - display.syncExec(showExceptionWrapper); - } else { - display.asyncExec(showExceptionWrapper); - } - if (exceptionThrownInUIThread.value != null) { - throw exceptionThrownInUIThread.value; - } - - return result.value; - } - } - - public static void runInDisplayThreadAsync(final DisplayThreadRunnable runnable) throws Exception { - runInDisplayThread(new DisplayThreadCallable() { - - @Override - public Void callWithDisplay(Display display) throws Exception { - runnable.runWithDisplay(display); - return null; - } - }, false); - } - - public static T runInDisplayThreadSync(final DisplayThreadCallable runnable) throws Exception { - return runInDisplayThread(runnable, true); - } - - public static void runInDisplayThreadSync(final DisplayThreadRunnable runnable) throws Exception { - runInDisplayThread(new DisplayThreadCallable() { - - @Override - public Void callWithDisplay(Display display) throws Exception { - runnable.runWithDisplay(display); - return null; - } - }, false); - } -} +package org.eclipsescript.util; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipsescript.core.Activator; +import org.eclipsescript.util.JavaUtils.MutableObject; + +public class EclipseUtils { + + public static interface DisplayThreadCallable { + public T callWithDisplay(Display display) throws Exception; + } + + /** A runnable to run in the display thread. */ + public static interface DisplayThreadRunnable { + public void runWithDisplay(Display display) throws Exception; + } + + public static IWorkbenchPage activePage() { + return activeWindow().getActivePage(); + } + + public static IWorkbenchWindow activeWindow() { + return PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + } + + public static IDocument getCurrentDocument() { + ITextEditor editor = getCurrentTextEditor(); + if (editor == null) + return null; + IDocumentProvider documentProvider = editor.getDocumentProvider(); + IDocument document = documentProvider.getDocument(editor.getEditorInput()); + return document; + } + + public static IEditorInput getCurrentEditorInput() { + ITextEditor editor = getCurrentTextEditor(); + if (editor == null) + return null; + return editor.getEditorInput(); + } + + public static TextSelection getCurrentEditorSelection() { + ITextEditor editor = getCurrentTextEditor(); + if (editor == null) + return null; + ISelectionProvider selectionProvider = editor.getSelectionProvider(); + ISelection selection = selectionProvider.getSelection(); + if (selection instanceof TextSelection) { + TextSelection textSelection = (TextSelection) selection; + return textSelection; + } + return null; + } + + public static ITextEditor getCurrentTextEditor() { + IWorkbench workbench = PlatformUI.getWorkbench(); + IWorkbenchWindow activeWindow = workbench.getActiveWorkbenchWindow(); + IWorkbenchPage activePage = activeWindow.getActivePage(); + if (activePage == null) + return null; + IEditorPart activeEditor = activePage.getActiveEditor(); + if (activeEditor == null) + return null; + ITextEditor textEditor = (ITextEditor) activeEditor.getAdapter(ITextEditor.class); + return textEditor; + } + + public static IEditorDescriptor getDefaultEditor(final IFile file) { + if (file == null) + return null; + IWorkbench workbench = PlatformUI.getWorkbench(); + IEditorDescriptor descriptor = workbench.getEditorRegistry().getDefaultEditor(file.getName()); + if (descriptor != null) + return descriptor; + descriptor = workbench.getEditorRegistry().getDefaultEditor("simple_text_file.txt"); //$NON-NLS-1$ + if (descriptor != null) + return descriptor; + descriptor = workbench.getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); + if (descriptor != null) + return descriptor; + return workbench.getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); + } + + public static Shell getWindowShell() { + return activeWindow().getShell(); + } + + public static IEditorPart openEditor(final IFile file) { + final IEditorDescriptor descriptor = getDefaultEditor(file); + try { + return activePage().openEditor(new FileEditorInput(file), descriptor.getId()); + } catch (PartInitException e) { + Activator.logError(e); + return null; + } + } + + private static T runInDisplayThread(final DisplayThreadCallable runnable, final boolean sync) + throws Exception { + final Display display = PlatformUI.getWorkbench().getDisplay(); + + if (Thread.currentThread().equals(display.getThread())) { + return runnable.callWithDisplay(display); + } else { + final MutableObject exceptionThrownInUIThread = new MutableObject(); + final MutableObject result = new MutableObject(); + + Runnable showExceptionWrapper = new Runnable() { + @Override + public void run() { + try { + result.value = runnable.callWithDisplay(display); + } catch (Exception e) { + if (sync) { + exceptionThrownInUIThread.value = e; + } else { + Activator.logError(e); + } + } + } + }; + + if (sync) { + display.syncExec(showExceptionWrapper); + } else { + display.asyncExec(showExceptionWrapper); + } + if (exceptionThrownInUIThread.value != null) { + throw exceptionThrownInUIThread.value; + } + + return result.value; + } + } + + public static void runInDisplayThreadAsync(final DisplayThreadRunnable runnable) throws Exception { + runInDisplayThread(new DisplayThreadCallable() { + + @Override + public Void callWithDisplay(Display display) throws Exception { + runnable.runWithDisplay(display); + return null; + } + }, false); + } + + public static T runInDisplayThreadSync(final DisplayThreadCallable runnable) throws Exception { + return runInDisplayThread(runnable, true); + } + + public static void runInDisplayThreadSync(final DisplayThreadRunnable runnable) throws Exception { + runInDisplayThread(new DisplayThreadCallable() { + + @Override + public Void callWithDisplay(Display display) throws Exception { + runnable.runWithDisplay(display); + return null; + } + }, false); + } +} diff --git a/src/org/eclipsescript/util/JavaUtils.java b/src/org/eclipsescript/util/JavaUtils.java index 3136def..cc05a52 100644 --- a/src/org/eclipsescript/util/JavaUtils.java +++ b/src/org/eclipsescript/util/JavaUtils.java @@ -1,115 +1,119 @@ -package org.eclipsescript.util; - -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.net.URL; -import java.net.URLConnection; - -public class JavaUtils { - - public static abstract class BaseRunnable implements Runnable { - public abstract void doRun() throws Exception; - - @Override - public final void run() { - try { - doRun(); - } catch (Exception e) { - throw asRuntime(e); - } - } - } - - public static class MutableObject { - public T value; - } - - private static final String UTF8_CHARSET_NAME = "utf-8"; //$NON-NLS-1$ - - public static RuntimeException asRuntime(Throwable e) { - return (e instanceof RuntimeException) ? ((RuntimeException) e) : new RuntimeException(e); - } - - public static void close(Closeable c) { - if (c == null) - return; - try { - c.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static boolean isNotBlank(String s) { - return s != null && s.length() != 0; - } - - public static byte[] readAll(InputStream in) throws IOException { - try { - byte[] buffer = new byte[512]; - int n; - ByteArrayOutputStream baous = new ByteArrayOutputStream(); - while ((n = in.read(buffer)) != -1) { - baous.write(buffer, 0, n); - } - return baous.toByteArray(); - } finally { - close(in); - } - } - - public static String readAllToStringAndClose(InputStream in) { - return readAllToStringAndClose(in, UTF8_CHARSET_NAME); - } - - public static String readAllToStringAndClose(InputStream in, String charSetName) { - try { - String charSetNameToUse = charSetName; - if (charSetName == null || charSetName.isEmpty()) - charSetNameToUse = UTF8_CHARSET_NAME; - return new String(readAll(in), charSetNameToUse); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - close(in); - } - } - - public static String readAllToStringAndClose(Reader in) { - StringBuilder result = new StringBuilder(); - try { - char[] buffer = new char[4096]; - int n; - while ((n = in.read(buffer)) != -1) { - result.append(buffer, 0, n); - } - return result.toString(); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - close(in); - } - } - - public static String readURL(URL url) throws Exception { - URLConnection uc = url.openConnection(); - return readURLConnection(uc); - } - - public static String readURLConnection(URLConnection uc) throws Exception { - String contentType = uc.getContentType(); - int charSetNameIndex = contentType.indexOf("charset="); //$NON-NLS-1$ - String charSet; - if (charSetNameIndex == -1) { - charSet = UTF8_CHARSET_NAME; - } else { - charSet = contentType.substring(charSetNameIndex + 8); - } - InputStream in = uc.getInputStream(); - return readAllToStringAndClose(in, charSet); - } - -} +package org.eclipsescript.util; + +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.net.URL; +import java.net.URLConnection; + +public class JavaUtils { + + public static abstract class BaseRunnable implements Runnable { + public abstract void doRun() throws Exception; + + @Override + public final void run() { + try { + doRun(); + } catch (Exception e) { + throw asRuntime(e); + } + } + } + + public static class MutableObject { + public T value; + } + + private static final String UTF8_CHARSET_NAME = "utf-8"; //$NON-NLS-1$ + + public static RuntimeException asRuntime(Throwable e) { + return (e instanceof RuntimeException) ? ((RuntimeException) e) : new RuntimeException(e); + } + + public static void close(Closeable c) { + if (c == null) + return; + try { + c.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static boolean isNotBlank(String s) { + return s != null && s.length() != 0; + } + + public static byte[] readAll(InputStream in) throws IOException { + try { + byte[] buffer = new byte[512]; + int n; + ByteArrayOutputStream baous = new ByteArrayOutputStream(); + while ((n = in.read(buffer)) != -1) { + baous.write(buffer, 0, n); + } + return baous.toByteArray(); + } finally { + close(in); + } + } + + public static String readAllToStringAndClose(InputStream in) { + return readAllToStringAndClose(in, UTF8_CHARSET_NAME); + } + + public static String readAllToStringAndClose(InputStream in, String charSetName) { + try { + String charSetNameToUse = charSetName; + if (charSetName == null || charSetName.isEmpty()) + charSetNameToUse = UTF8_CHARSET_NAME; + return new String(readAll(in), charSetNameToUse); + } catch (IOException e) { + throw new RuntimeException(e); + } finally { + close(in); + } + } + + public static String readAllToStringAndClose(Reader in) { + StringBuilder result = new StringBuilder(); + try { + char[] buffer = new char[4096]; + int n; + while ((n = in.read(buffer)) != -1) { + result.append(buffer, 0, n); + } + return result.toString(); + } catch (IOException e) { + throw new RuntimeException(e); + } finally { + close(in); + } + } + + public static String readURL(URL url) throws Exception { + URLConnection uc = url.openConnection(); + return readURLConnection(uc); + } + + public static String readURLConnection(URLConnection uc) throws Exception { + String contentType = uc.getContentType(); + int charSetNameIndex = contentType.indexOf("charset="); //$NON-NLS-1$ + String charSet; + if (charSetNameIndex == -1) { + charSet = UTF8_CHARSET_NAME; + } else { + charSet = contentType.substring(charSetNameIndex + 8); + } + InputStream in = uc.getInputStream(); + try { + return readAllToStringAndClose(in, charSet); + } finally { + in.close(); + } + } + +}