How to close a ViewPart in Eclipse? - eclipse

I have a view in Eclipse (implemented by a class which extends org.eclipse.ui.part.ViewPart) which I need to close. I mean completely close, not just hide. I want a new ViewPart instance to be created when the user (or my code) asks to open the view again.
The only method I found was IWorkbenchPage.hideView which hides the view, but does not completely dispose of it. Invoking dispose on the view has no affect, either.
BTW, my view is defined as allowMultiple="false" but I tried with true and that didn't make any difference.
Any help will be appreciated.

I found the problem eventually. If the view is open on more than one perspective, hiding it on one perspective will not close it. It is possible to iterate over all the open perspective and look for the view. Hiding it on all perspectives will close it.

I think the IWorkbenchPage.hideView() method you mentioned is the only one available to programmaticaly close a view. I also think this method name should be closeView() beacause it really close the view.
I have been using this method for a while (with allowMultiple=true views) and after debugging it seems my view.dispose() method is invoked each time I invoke hideView().
Next time I open this view again (I mean from my code and not from user interface), a new one is created by Eclipse and the createPartControl() method is invoked again.
Moreover, the call hierarchy view told me than the hideView() should call the dispose method() ....
hideView() >> releaseView() >> partRemoved() >> disposePart() >> dispose() >> doDisposePart() >> doDisposePart() >> dispose()
Hope this can help ....
One last question, how did you checked that your view was not correctly disposed ??

The org.eclipse.ui.internal.ViewFactory has a method called releaseView that I think closes the view completely (though I'm not certain). It takes an IViewReference.
You can access the ViewFactory by calling Perspective.getViewFactory, and you can access the Perspective, you then pass it an IViewReference to release the view.
IWorkbenchPage page =
Workbench.getInstance().getActiveWorkbenchWindow().getActivePage()
Perspective perspective = page.getPerspective();
String viewId = "myViewId"; //defined by you
//get the reference for your viewId
IViewReference ref = page.findViewReference(viewId);
//release the view
perspective.getViewFactory.releaseView(ref);

I overridden dispose method from IWorkbenchPart and that worked.
I had something like this in my overridden dispose method:
public void dispose() {
super.dispose();
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (page != null) {
IViewReference[] viewReferences = page.getViewReferences();
for (IViewReference ivr : viewReferences) {
if (ivr.getId().equalsIgnoreCase("your view id")
|| ivr.getId().equalsIgnoreCase("more view id if you want to close more than one at a time")) {
page.hideView(ivr);
}
}
}
}

In order to dispose ViewPart on closing Perspective we used the next code:
IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (workbenchWindow != null) {
workbenchWindow.addPerspectiveListener(new PerspectiveAdapter() {
#Override
public void perspectiveActivated(IWorkbenchPage page,
IPerspectiveDescriptor perspectiveDescriptor) {
super.perspectiveActivated(page, perspectiveDescriptor);
}
#Override
public void perspectiveDeactivated(IWorkbenchPage page,
IPerspectiveDescriptor perspective) {
super.perspectiveDeactivated(page, perspective);
page.closePerspective(perspective, false, true);
}
});
}
In result of page.closePerspective(perspective, false, true);, ViewPart that was opened within perspective, will be disposed.

To close views, opened in different perspective, I overridden perspectiveDeactivated() of org.eclipse.ui.PerspectiveAdapter.
public void perspectiveDeactivated(IWorkbenchPage page,
IPerspectiveDescriptor perspective) {
super.perspectiveDeactivated(page, perspective);
boolean myPerspective = MyPerspective.PERSPECTIVE_ID.equals(perspective.getId());
if(!myPerspective) {
//close Error Log view if it is opened in any perspective except My perspective.
IViewPart errorView = page.findView("org.eclipse.pde.runtime.LogView");
if(errorView != null) {
page.hideView(errorView);
}
}
}
My requirement was to close "Error Log" view. Above code can be modified to close any view.

Related

button back to my app in the background and when you resume it starts again

I am developing an app in Xamarin.Forms, before I was trying to make a master detail page to become my MainPage when I logged in to my app, this I have already achieved. Now I have the problem that when I use the button behind the phone my app is miimiza and goes to the background which is the behavior I hope, but when I return to my app does not continue showing my master detail page, but returns to my LginPage.
It is as if my app was running twice or at least there were two instances of LoginPage existing at the same time, this is because in my LoginPage I trigger some DisplayAlert according to some messages that my page is listening through the MessaginCenter and they are they shoot twice.
Can someone tell me how I can return the same to my app on the master detail page and not restart in the strange way described?
LoginView.xaml.cs:
public partial class LogonView : ContentPage
{
LogonViewModel contexto = new LogonViewModel();
public LogonView ()
{
InitializeComponent ();
BindingContext = contexto;
MessagingCenter.Subscribe<LogonViewModel>(this, "ErrorCredentials", async (sender) =>
{
await DisplayAlert("Error", "Email or password is incorrect.", "Ok");
}
);
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<LogonViewModel>(this, "ErrorCredentials");
}
}
Part of my ViewModel:
if (Loged)
{
App.token = token;
Application.Current.MainPage = new RootView();
}
else
{
MessagingCenter.Send(this, "ErrorCredentials");
}
Thanks.
I hope this is in Android. All you can do is, you can override the backbuttonpressed method in MainActivity for not closing on back button pressed of the entry page. like below, you can add some conditions as well.
public override void OnBackPressed()
{
Page currentPage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
if (currentPage != null)
{
if (currentPage.GetType().Name == "HomePage" || currentPage.GetType().Name == "LoginPage")
{
return;
}
}
base.OnBackPressed();
}
When you press the Home button, the application is paused and the
current state is saved, and finally the application is frozen in
whatever state it is. After this, when you start the app, it is
resumed from the last point it was saved with.
However, when you use the Back button, you keep traversing back in
the activity stack, closing one activity after another. in the end,
when you close the first activity that you opened, your application
exits. This is why whenever you close your application like this, it
gets restarted when you open it again.
Answer taken from this answer. The original question asks about the native Android platform, but it still applies here.
It means you have to Use Setting Plugin or save data in Application properties.
You have to add below code in App.xaml.cs file:
if (SettingClass.UserName == null)
MainPage = new LoginPage();
else
MainPage = new MasterDetailPage();
For Setting Plugin you can refer this link.

Custom Perspective Switcher Toolbar: How can I dynamically update it?

I'm trying to implement a custom perspective switcher toolbar to replace eclipse's built-in one. I couldn't get the toolbar to display, and it was shown to me that due to a bug with the dynamic element in a menu contribution, I have to use a control element instead, as described in the workaround to the dynamic bug.
I have a toolbar displaying following that approach, but I cannot figure out how to update it dynamically. The workaround instruction is to call ContributionItem#fill(CoolBar, int) from my WorkbenchControlContributionItem's update method instead of doing the fill in the createControl method.
I don't know who is supposed to call update, but it never gets invoked no matter what I do. I have a perspective listener which knows when to update the toolbar, so from that listener's callback I call fill(CoolBar, int). But I wasn't sure how to get the CoolBar to pass to that method, so I created one on the current shell.
The end result of all this is that the toolbar displays the correct number of items initially, but when I need to add an item, it has no effect. I call fill(CoolBar, int) and it adds the new item to the toolbar, but everything I've tried to make the CoolBar and ToolBarupdate does not work. When I re-launch the app, the toolbar has the added item.
I'm sure I'm doing this wrong, but I can't figure out the right way. Here's an elided representation of my code (omitting methods, layout code, etc not related to the update problem).
public class PerspectiveSwitcherToolbar extends WorkbenchWindowControlContribution implements IPerspectiveListener {
...
#Override
protected Control createControl(Composite parent) {
this.parent = parent;
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
page.getWorkbenchWindow().addPerspectiveListener(this);
toolBarManager = (ToolBarManager)parent.getParent().getData();
fTopControl = new Composite(parent, SWT.BORDER);
fill(new CoolBar(page.getWorkbenchWindow().getShell(), SWT.HORIZONTAL), -1);
return fTopControl;
}
#Override
public void fill(CoolBar coolbar, int index) {
IPerspectiveDescriptor[] openPerspectives = page.getOpenPerspectives();
String activePerspective = getPerspectiveId();
ToolBar toolbar = new ToolBar(fTopControl, SWT.NONE);
for(IPerspectiveDescriptor descriptor : openPerspectives) {
ToolItem item = new ToolItem(toolbar, SWT.RADIO);
//overkill here, trying to find some way to upate the toolbar
toolbar.update();
parent.update();
parent.layout(true);
parent.getParent().update();
parent.getParent().layout(true);
coolbar.layout(true);
}
//PerspectiveListener callback
#Override
public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
fill(new CoolBar(page.getWorkbenchWindow().getShell(), SWT.HORIZONTAL), -1);
if (page.getWorkbenchWindow() instanceof WorkbenchWindow){
//this non-API call doesn't help either
((WorkbenchWindow) page.getWorkbenchWindow()).updateActionBars();
}
}
...
}

Block gwt DisclosurePanel on open state

How may I block a gwt DisclosurePanel on the open state ?
I mean, how can I prevent this DisclosurePanel to close if the user click the header more than once ?
(My header is a textBox, I want the user to enter a text, and the panel should remain open if the user unfocus the textBox and focus newly by clicking it. The DisclosurePanel content has a "cancel" button that closes the panel)
Thank you very much.
I edit my question after 2 first answers: I would like to avoid to reopen the DisclosurePanel once closed to avoid flashing effect. I actually want to prevent the DisclosurePanel to close. Maybe sinkEvents can help me... if so, how? Thanks.
A NativePreviewHandler receives all events before they are fired to their handlers. By registering a nativePreviewHandler the first time your disclosurePanel is opened, you can cancel the click event. You can later decide to remove this handler by preventClose.removeHandler();
HandlerRegistration preventClose = null;
....
panel.addOpenHandler(new OpenHandler<DisclosurePanel>() {
#Override
public void onOpen(OpenEvent<DisclosurePanel> event) {
if (preventClose == null){
preventClose = Event.addNativePreviewHandler(new NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (event.getTypeInt()==Event.ONCLICK && event.getNativeEvent().getEventTarget() == panel.getHeader().getElement().cast())
event.cancel();
}
});
}
}
});
The obvious answer is review the javadoc here: https://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/DisclosurePanel.html
There is a setOpen() method that: Changes the visible state of this DisclosurePanel.
Set it to false from a click event to capture the user action.
The JavaDoc is right here: https://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/user/client/ui/DisclosurePanel.html
jamesDrinkard pointed the old 1.5 javadoc.
You can use the addCloseHandler(CloseHandler<DisclosurePanel> handler) method to add a handler so when the user tries to close it you can reopen it again with setOpen().
Maybe not the best way, but it worked for me (maybe just one of both will work too):
dPanel.setOpen(true);
dPanel.addOpenHandler(new OpenHandler<DisclosurePanel>() {
#Override
public void onOpen(OpenEvent<DisclosurePanel> event) {
dPanel.setOpen(true);
}
});
dPanel.addCloseHandler(new CloseHandler<DisclosurePanel>() {
#Override
public void onClose(CloseEvent<DisclosurePanel> event) {
dPanel.setOpen(true);
}
});

GWT, disable autoclose MenuBar when clicking on MenuItem?

I want to if it is possible to disable the auto-close MenuBar when I click on a MenuItem?
I have several MenuItem that are like checkboxes, so I can check more than one MenuItem and don't want my menu close everytime I checked one.
Thanks.
I was facing same problem and I will share with you my solution:
1) Create new class MyMenuItemWithCheckBox that extends the MenuItem.
In the constructor set element ID to (forexample) menuItemWIthCheckBox + Unique text.
this.getElement().setId("menuItemWithCheckBox_" + menuItemLabel);
2) Create new class MyMenuBar that extends the MenuBar.
Override the onBrowserEvent method by following:
Override
public void onBrowserEvent(Event event) {
if (DOM.eventGetType(event) == Event.ONCLICK && getSelectedItem().getElement().getId().contains("CheckBox")) {
Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
#Override
public void execute() {
getSelectedItem().getScheduledCommand().execute();
}
});
event.stopPropagation();
} else {
super.onBrowserEvent(event);
}
}
Now scheduled command of MenuItem is always called, but in the case of your
menu checkBox item there is no close of a menubar.
I hope this help you, I spend more than day to create this solution. :-)
First, directly it's not possible because the popup-panel which displays the submenu is private in the MenuBar class.
Buuut, there is a way to do so ...
Simpley fetch the current MenuBar.java code out of googles code repository and include it in your eclipse gwt-project.
You don't have to change anything e.g. package deklaration or something. Just put your source in your project and it will simply replace the original MenuBar-class from the gwt-sdk during compilation (works also with hosted development mode).
Then you can simply set the property autoHide of the popup-Panel to false and the popup shouldn't disappear after clicking.
You can set hideOnClick to false on the menuItems
See here.

Using the Selection service on something that is *not* a JFace view

I am building an image Editor as an Eclipse plugin.
I would like to use the Properties view to view & edit properties of the model underneath the image. Accordingly I am calling ..
getSite().setSelectionProvider( this );
.. within createPartControl, and implementing the ISelectionProvider interface in my EditorPart implementation, so that the model is returned as the selection (which must therefore implement the ISelection interface).
The next step is for the Editor to implement IAdaptable to supply an adapter for the selected object.
My problem however is that getAdapter is never called with IPropertySource.class, and therefore the Properties View never gets what it needs to make sense of the image model.
Your help is much appreciated.
M.
The answer in the end broke down into a few pieces ...
1.) When your selection does change (if a user has zoomed into the image, for example) be sure to tell Eclipse this. It won't happen otherwise.
2.) When sending your SelectionChangedEvent, wrap up your IAdaptable in a StructuredSelection object - otherwise the Properties view will ignore it.
This boiled down to the following method
public void fireSelectionChanged()
{
final SelectionChangedEvent event = new SelectionChangedEvent( this, new StructuredSelection( this ) );
Object[] listeners = selectionChangedListeners.getListeners();
for (int i = 0; i < listeners.length; ++i)
{
final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
SafeRunnable.run(new SafeRunnable() {
public void run() {
l.selectionChanged( event );
}
});
}
}
... on an class that implemented ISelectionProvider & IAdaptable.
M.