Find the open eclipse dialog programmatically - eclipse

It is possible to find an active page/editor in eclipse. How can we programmatically get hold of the instance of the open modal dialog in eclipse.

There are no corresponding interface in Eclipse to access any current model dialog. The best approximation is Display.getActiveShell(), which will return the shell that hosts the active dialog if one exists.
[Dialogs are implemented by having their own event loop, so it can be rather difficult to run your own code...]
EDIT: Based on your comment below, here is a small snippet I use constantly to test for the presence of specific preference pages. I guess this can be used used as the starting point for your own test... Note the use of Display.timerExec(...).
public void test(String pageId) {
try {
final IWorkbench workbench = PlatformUI.getWorkbench();
final Shell[] shells = workbench.getDisplay().getShells();
final ICommandService cs = (ICommandService) workbench.getService(ICommandService.class);
final ParameterizedCommand command = cs.deserialize("org.eclipse.ui.window.preferences(preferencePageId="
+ pageId + ")");
assertNotNull(command);
final IHandlerService hs = (IHandlerService) workbench.getService(IHandlerService.class);
// Have to use timerExec to get the runnable executed after the dialog is shown
workbench.getDisplay().timerExec(2000, new Runnable() {
#Override
public void run() {
assertEquals(shells.length + 1, workbench.getDisplay().getShells().length);
final Shell lastShell = findLastShell(workbench.getDisplay().getShells(), shells);
assertNotNull(lastShell);
final Object data = lastShell.getData();
assertNotNull(data);
assertTrue(data instanceof PreferenceDialog);
lastShell.close();
assertEquals(shells.length, workbench.getDisplay().getShells().length);
}
private Shell findLastShell(Shell[] currentShells, Shell[] oldShells) {
CheckNext: for (final Shell cs : currentShells) {
for (final Shell os : oldShells) {
if (os == cs) {
continue CheckNext;
}
}
return cs;
}
return null;
}
});
hs.executeCommand(command, null);
} catch (final Exception ex) {
fail(ex.getMessage());
}
}

Related

Combo Box is not observed

I have the following Code:
public class GuiView extends Application {
private ObservableList<String> shareNames = FXCollections.observableArrayList();
public void start(Stage stage) {
...
ComboBox<String> comboBox = new ComboBox<String>();
comboBox.getItems().addAll(this.shareNames);
MenuItem open = new MenuItem("Open...");
open.setOnAction( e -> {
// FileChooser code...
if (selctedFile != null) {
this.shareNames.addAll("teststring");
}
});
}
}
When I run through the open dialog successfully the combo box doesn't update and shows the teststring. What is going wrong here?
You are updating shareNames, but that is not the list used by the combo box.
Either replace
comboBox.getItems().addAll(this.shareNames);
with
comboBox.setItems(this.shareNames);
or replace
this.shareNames.addAll("teststring");
with
comboBox.getItems().add("teststring");

Eclipse 4: disable native alt-f4 behavior

does anyone know if it is possible to disable or overwrite the native behavior of "alt+f4" (on windows closes the application) in an e4 application?
what is suggested solution to achieve this?
best regards
My solution is NOT pure SWT solution. It only works on Windows. But you mentioned Windows, and if you only target one platform this is good enough. It uses internal code from SWT, but it maps to Windows API, documented by Microsoft, so it will not change.
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.addListener(SWT.Close, new Listener() {
#Override
public void handleEvent(Event event) {
if (OS.GetKeyState(OS.VK_MENU) < 0 && OS.GetKeyState(OS.VK_F4) < 0) {
event.doit = false;
}
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
found a solution but i am not to happy with that one.
created a addon:
that is registering an event handler on the UIEvents.UILifeCycle.APP_STARTUP_COMPLETE topic.
then somehow retrieve the shell from the topics metadata and registering a filter on the display.
#PostConstruct
void hookListeners() {
eventHandler = new EventHandler() {
#Override
public void handleEvent(Event arg0) {
MElementContainer property = (MElementContainer) arg0.getProperty("org.eclipse.e4.data");
final Shell shell = (Shell) property.getSelectedElement().getWidget();
final Display display = shell.getDisplay();
display.addFilter(SWT.Close, new Listener() {
#Override
public void handleEvent(org.eclipse.swt.widgets.Event event) {
if (!MessageDialog.openQuestion(shell, "Exit",
"Do you really want to close the Application?")) {
//see api documentation display.addFilter(
event.type = SWT.NONE;
event.doit = false;
}
}
});
}
};
eventBroker.subscribe(UIEvents.UILifeCycle.APP_STARTUP_COMPLETE, eventHandler);
}
this solution does not seem to correct to me so if anyone has a better one please share it :-)

Netbeans lookup not getting executed first time when the application is started

I have an application in which lookup provider is in explorer window and it is a jcomboBox. Its selected value is provided as lookup to other top components and displayed one in editor and one in output window area. The value of the jcombobox is saved at the time of closing the application and initialized into the jcombobox when the application is started.
When I clean and build the application and start the application, the initial value displayed in the jcombobox is not updated in the lookup and listner windows display uninitialized values. Once the new value is selected in the jcombobox it gets displayed in the other windows.
If I close the application without changing the value of the jcombobox and start the application, the lookup is not updated.
If I change the selection in the combobox, close the application and start again, the lookup gets updated.
I expect anytime when the application is started, the other windows will get the value of the lookup. Any help in this regards will be appreciated. Thanks in advance.
The code for the explorer window which provides the lookup is as follows:
public final class ProviderTopComponent extends TopComponent {
public ProviderTopComponent() {
initComponents();
setName(Bundle.CTL_ProviderTopComponent());
setToolTipText(Bundle.HINT_ProviderTopComponent());
associateLookup(new AbstractLookup(content));
}
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
str = (String) jComboBox1.getSelectedItem();
content.set(Collections.singleton(str), null);
}
private final InstanceContent content = new InstanceContent();
String str;
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
p.setProperty("val", (String) jComboBox1.getSelectedItem());
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
String v = p.getProperty("val");
if(v != null) {
jComboBox1.setSelectedItem(v);
}
}
}
The code for the lookup listener window is as follows:
public final class Listner_1TopComponent extends TopComponent implements LookupListener{
public Listner_1TopComponent() {
initComponents();
setName(Bundle.CTL_editorTopComponent());
setToolTipText(Bundle.HINT_editorTopComponent());
}
...
private void initComponents() {
...
jLabel1 = new javax.swing.JLabel();
...
Collection<? extends String> str_collection;
private Lookup.Result<String> result = null;
String str;
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
#Override
public void componentOpened() {
result = org.openide.util.Utilities.actionsGlobalContext().lookupResult(String.class);
result.addLookupListener(this);
}
#Override
public void componentClosed() {
result.removeLookupListener(this);
}
#Override
public void resultChanged(LookupEvent le) {
str_collection = result.allInstances();
if (str_collection.isEmpty()) {
} else {
str = str_collection.iterator().next();
}
jLabel1.setText(str);
jLabel1.repaint();
}
}

How do I manage console output in a long running Eclipse plug-in?

I have written an Eclipse plugin that works. What happens, though, is that during the run, no console output is displayed. Only when the process is finished does the output show up in the console. Below is my handler, which appears as an extension point of type org.eclipse.ui.commands:
public class MyHandler extends AbstractHandler {
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
...
MessageConsoleStream out = myConsole.newMessageStream();
...
IConsoleView view = (IConsoleView) page.showView(id);
view.display(myConsole);
...
out.println("output that only shows up at the end");
myConsole.activate();
...
// Slow process
...
out.println("everything is done");
return null;
}
}
So while the process runs, nothing in the console. Then at the end, both output lines pop into view.
I'm obviously doing the console thing incorrectly, but I haven't found any good examples, nor has my experimentation proven very fruitful. Please advise.
You could consider using a ProgressMonitor (possibly with cancelation in case the user wants to abort), so that the user can see that there is something going on.
This worked:
public class Merge extends AbstractHandler {
private static MessageConsole myConsole = null;
private static ExecutionEvent event = null;
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Merge.event = event;
//same idea as original post and other examples where it makes new or finds existing
myConsole = makeConsole(Merge.event);
Job job = new Job("My Job Name"){
#Override
protected IStatus run(IProgressMonitor monitor){
...
if (blah) {
MessageConsoleStream out = myConsole.newMessageStream();
out.println("output show up right away");
...
// Slow process
...
out.println("everything is done");
} else {
MessageDialog.openInformation(HandlerUtil.getActiveShell(Merge.event), "Information", "Please select valid file");
}
monitor.done();
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
return null;
}
...
}
Maybe you can call out.flush() after every out.print...

Calling organize imports programmatically

I'm trying to execute 'OrganizeImports' programmatically on files that I'm editing programmatically.
My code looks like this:
final ICommandService cmdService = (ICommandService)PlatformUI.getWorkbench().getService (ICommandService.class);
if (cmdService != null) {
final Command cmd = cmdService.getCommand(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS);
final ExecutionEvent execEvt = new ExecutionEvent(cmd, Collections.EMPTY_MAP, compileationUnit, null);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
ResourcesPlugin.getWorkspace().
Display.getDefault().syncExec(new Runnable() {
#Override
public void run() {
try {
//cmd.executeWithChecks(execEvt);
cmd.execute(execEvt);
} catch (Exception e) {
getLogger().severe("organize imports failed: " + e.getMessage());
}
}
My problem is that OrganizeImportsAction executes on the current selection which is not the same as the compilation unit I'm editing. I would like to set the selection programmatically on the compilation unit but I don't know how to do that. Or maybe there is another way to trigger OrganizeImports.
thanks,
stefan
May be this test ui.org.eclipse.jdt.ui.tests.quickfix.CleanUpTest class could offer some clue.
It is based on the enable method in ui.org.eclipse.jdt.ui.tests.quickfix.CleanUpTestCase and on the org.eclipse.ltk.core.refactoring.PerformChangeOperation class.
You can see PerformChangeOperation invoked ink the class org.eclipse.ltk.ui.refactoring.RefactoringWizard.