KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > Perspective


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11
12 package org.eclipse.ui.internal;
13
14 import java.io.IOException JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.HashMap JavaDoc;
17 import java.util.HashSet JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Map JavaDoc;
21
22 import org.eclipse.core.runtime.CoreException;
23 import org.eclipse.core.runtime.IStatus;
24 import org.eclipse.core.runtime.MultiStatus;
25 import org.eclipse.core.runtime.Status;
26 import org.eclipse.jface.dialogs.ErrorDialog;
27 import org.eclipse.jface.dialogs.MessageDialog;
28 import org.eclipse.jface.preference.IPreferenceStore;
29 import org.eclipse.jface.util.Geometry;
30 import org.eclipse.osgi.util.NLS;
31 import org.eclipse.swt.SWT;
32 import org.eclipse.swt.graphics.Point;
33 import org.eclipse.swt.graphics.Rectangle;
34 import org.eclipse.swt.widgets.Composite;
35 import org.eclipse.swt.widgets.Control;
36 import org.eclipse.swt.widgets.Shell;
37 import org.eclipse.ui.IMemento;
38 import org.eclipse.ui.IPageLayout;
39 import org.eclipse.ui.IPerspectiveDescriptor;
40 import org.eclipse.ui.IPerspectiveFactory;
41 import org.eclipse.ui.IPlaceholderFolderLayout;
42 import org.eclipse.ui.IViewLayout;
43 import org.eclipse.ui.IViewPart;
44 import org.eclipse.ui.IViewReference;
45 import org.eclipse.ui.IViewSite;
46 import org.eclipse.ui.IWorkbenchPart;
47 import org.eclipse.ui.IWorkbenchPartReference;
48 import org.eclipse.ui.IWorkbenchPreferenceConstants;
49 import org.eclipse.ui.IWorkbenchWindow;
50 import org.eclipse.ui.PartInitException;
51 import org.eclipse.ui.PlatformUI;
52 import org.eclipse.ui.WorkbenchException;
53 import org.eclipse.ui.XMLMemento;
54 import org.eclipse.ui.contexts.IContextService;
55 import org.eclipse.ui.internal.StartupThreading.StartupRunnable;
56 import org.eclipse.ui.internal.contexts.ContextAuthority;
57 import org.eclipse.ui.internal.intro.IIntroConstants;
58 import org.eclipse.ui.internal.layout.ITrimManager;
59 import org.eclipse.ui.internal.layout.IWindowTrim;
60 import org.eclipse.ui.internal.layout.TrimLayout;
61 import org.eclipse.ui.internal.misc.StatusUtil;
62 import org.eclipse.ui.internal.registry.ActionSetRegistry;
63 import org.eclipse.ui.internal.registry.IActionSetDescriptor;
64 import org.eclipse.ui.internal.registry.IWorkbenchRegistryConstants;
65 import org.eclipse.ui.internal.registry.PerspectiveDescriptor;
66 import org.eclipse.ui.internal.registry.PerspectiveExtensionReader;
67 import org.eclipse.ui.internal.registry.PerspectiveRegistry;
68 import org.eclipse.ui.internal.registry.StickyViewDescriptor;
69 import org.eclipse.ui.internal.util.PrefUtil;
70 import org.eclipse.ui.presentations.AbstractPresentationFactory;
71 import org.eclipse.ui.presentations.IStackPresentationSite;
72 import org.eclipse.ui.statushandlers.StatusManager;
73 import org.eclipse.ui.views.IStickyViewDescriptor;
74 import org.eclipse.ui.views.IViewDescriptor;
75 import org.eclipse.ui.views.IViewRegistry;
76
77 /**
78  * The ViewManager is a factory for workbench views.
79  */

80 public class Perspective {
81     private PerspectiveDescriptor descriptor;
82
83     protected WorkbenchPage page;
84
85     // Editor Area management
86
protected LayoutPart editorArea;
87     private PartPlaceholder editorHolder;
88     private boolean editorHidden = false;
89     private boolean editorAreaRestoreOnUnzoom = false;
90     private int editorAreaState = IStackPresentationSite.STATE_RESTORED;
91
92     private ViewFactory viewFactory;
93     
94     private ArrayList JavaDoc alwaysOnActionSets;
95
96     private ArrayList JavaDoc alwaysOffActionSets;
97
98     private ArrayList JavaDoc newWizardShortcuts;
99
100     private ArrayList JavaDoc showViewShortcuts;
101
102     private ArrayList JavaDoc perspectiveShortcuts;
103
104     //private List fastViews;
105
private FastViewManager fastViewManager = null;
106
107     private Map JavaDoc mapIDtoViewLayoutRec;
108
109     private boolean fixed;
110
111     private ArrayList JavaDoc showInPartIds;
112
113     private HashMap JavaDoc showInTimes = new HashMap JavaDoc();
114
115     private IViewReference activeFastView;
116
117     private IMemento memento;
118
119     protected PerspectiveHelper presentation;
120
121     final static private String JavaDoc VERSION_STRING = "0.016";//$NON-NLS-1$
122

123     private FastViewPane fastViewPane = new FastViewPane();
124
125     // fields used by fast view resizing via a sash
126
private static final int FASTVIEW_HIDE_STEPS = 5;
127
128     /**
129      * Reference to the part that was previously active
130      * when this perspective was deactivated.
131      */

132     private IWorkbenchPartReference oldPartRef = null;
133
134     private boolean shouldHideEditorsOnActivate = false;
135
136     private PageLayout layout;
137
138     /**
139      * ViewManager constructor comment.
140      */

141     public Perspective(PerspectiveDescriptor desc, WorkbenchPage page)
142             throws WorkbenchException {
143         this(page);
144         descriptor = desc;
145         if (desc != null) {
146             createPresentation(desc);
147         }
148     }
149
150     /**
151      * ViewManager constructor comment.
152      */

153     protected Perspective(WorkbenchPage page) throws WorkbenchException {
154         this.page = page;
155         this.editorArea = page.getEditorPresentation().getLayoutPart();
156         this.viewFactory = page.getViewFactory();
157         alwaysOnActionSets = new ArrayList JavaDoc(2);
158         alwaysOffActionSets = new ArrayList JavaDoc(2);
159         
160         // We'll only make a FastView Manager if there's a
161
// Trim manager in the WorkbenchWindow
162
IWorkbenchWindow wbw = page.getWorkbenchWindow();
163         if (wbw instanceof WorkbenchWindow) {
164             if (((WorkbenchWindow)wbw).getTrimManager() != null)
165                 fastViewManager = new FastViewManager(this, page);
166         }
167         
168         mapIDtoViewLayoutRec = new HashMap JavaDoc();
169     }
170
171     /**
172      * Sets the fast view attribute. Note: The page is expected to update action
173      * bars.
174      */

175     public void makeFastView(IViewReference ref) {
176         addFastView(ref, true);
177     }
178     
179     /**
180      * Sets the fast view attribute. Note: The page is expected to update action
181      * bars.
182      */

183     public void addFastView(IViewReference ref, boolean handleLayout) {
184         ViewPane pane = (ViewPane) ((WorkbenchPartReference) ref).getPane();
185         if (!isFastView(ref)) {
186             if (handleLayout) {
187                 // Only remove the part from the presentation if it
188
// is actually in the presentation.
189
if (presentation.hasPlaceholder(ref.getId(), ref.getSecondaryId())
190                         || pane.getContainer() != null) {
191                     presentation.removePart(pane);
192                 }
193             }
194             
195             // We are drag-enabling the pane because it has been disabled
196
// when it was removed from the perspective presentation.
197
pane.setFast(true);
198             Control ctrl = pane.getControl();
199             if (ctrl != null) {
200                 ctrl.setEnabled(false); // Remove focus support.
201
}
202         }
203     }
204
205     /**
206      * Moves a part forward in the Z order of a perspective so it is visible.
207      *
208      * @param part the part to bring to move forward
209      * @return true if the part was brought to top, false if not.
210      */

211     public boolean bringToTop(IViewReference ref) {
212         if (isFastView(ref)) {
213             setActiveFastView(ref);
214             return true;
215         } else {
216             return presentation.bringPartToTop(getPane(ref));
217         }
218     }
219
220     /**
221      * Returns whether a view exists within the perspective.
222      */

223     public boolean containsView(IViewPart view) {
224         IViewSite site = view.getViewSite();
225         IViewReference ref = findView(site.getId(), site.getSecondaryId());
226         if (ref == null) {
227             return false;
228         }
229         return (view == ref.getPart(false));
230     }
231
232     /**
233      * Create the initial list of action sets.
234      */

235     private void createInitialActionSets(List JavaDoc outputList, List JavaDoc stringList) {
236         ActionSetRegistry reg = WorkbenchPlugin.getDefault()
237                 .getActionSetRegistry();
238         Iterator JavaDoc iter = stringList.iterator();
239         while (iter.hasNext()) {
240             String JavaDoc id = (String JavaDoc) iter.next();
241             IActionSetDescriptor desc = reg.findActionSet(id);
242             if (desc != null) {
243                 outputList.add(desc);
244             } else {
245                 WorkbenchPlugin.log("Unable to find Action Set: " + id);//$NON-NLS-1$
246
}
247         }
248     }
249
250     /**
251      * Create a presentation for a perspective.
252      */

253     private void createPresentation(PerspectiveDescriptor persp)
254             throws WorkbenchException {
255         if (persp.hasCustomDefinition()) {
256             loadCustomPersp(persp);
257         } else {
258             loadPredefinedPersp(persp);
259         }
260     }
261
262     /**
263      * Dispose the perspective and all views contained within.
264      */

265     public void dispose() {
266         // Get rid of presentation.
267
if (presentation == null) {
268             return;
269         }
270
271         presentation.deactivate();
272         presentation.dispose();
273
274         fastViewPane.dispose();
275         
276         // Release each view.
277
IViewReference refs[] = getViewReferences();
278         for (int i = 0, length = refs.length; i < length; i++) {
279             getViewFactory().releaseView(refs[i]);
280         }
281
282         mapIDtoViewLayoutRec.clear();
283     }
284
285     /**
286      * Finds the view with the given ID that is open in this page, or <code>null</code>
287      * if not found.
288      *
289      * @param viewId the view ID
290      */

291     public IViewReference findView(String JavaDoc viewId) {
292         return findView(viewId, null);
293     }
294
295     /**
296      * Finds the view with the given id and secondary id that is open in this page,
297      * or <code>null</code> if not found.
298      *
299      * @param viewId the view ID
300      * @param secondaryId the secondary ID
301      */

302     public IViewReference findView(String JavaDoc id, String JavaDoc secondaryId) {
303         IViewReference refs[] = getViewReferences();
304         for (int i = 0; i < refs.length; i++) {
305             IViewReference ref = refs[i];
306             if (id.equals(ref.getId())
307                     && (secondaryId == null ? ref.getSecondaryId() == null
308                             : secondaryId.equals(ref.getSecondaryId()))) {
309                 return ref;
310             }
311         }
312         return null;
313     }
314
315     /**
316      * Returns the window's client composite widget
317      * which views and editor area will be parented.
318      */

319     public Composite getClientComposite() {
320         return page.getClientComposite();
321     }
322
323     /**
324      * Returns the perspective.
325      */

326     public IPerspectiveDescriptor getDesc() {
327         return descriptor;
328     }
329
330     /**
331      * Returns the bounds of the given fast view.
332      */

333     /*package*/Rectangle getFastViewBounds(IViewReference ref) {
334         // Copy the bounds of the page composite
335
Rectangle bounds = page.getClientComposite().getBounds();
336         // get the width ratio of the fast view
337
float ratio = getFastViewWidthRatio(ref);
338         // Compute the actual width of the fast view.
339
bounds.width = (int) (ratio * getClientComposite().getSize().x);
340         return bounds;
341     }
342
343     /**
344      * Returns the docked views.
345      */

346     public IViewReference[] getFastViews() {
347         if (fastViewManager == null)
348             return new IViewReference[0];
349         
350         List JavaDoc trueFVBRefs = fastViewManager.getFastViews(FastViewBar.FASTVIEWBAR_ID);
351         IViewReference array[] = new IViewReference[trueFVBRefs.size()];
352         trueFVBRefs.toArray(array);
353         return array;
354     }
355
356     /**
357      * Returns the new wizard shortcuts associated with this perspective.
358      *
359      * @return an array of new wizard identifiers
360      */

361     public String JavaDoc[] getNewWizardShortcuts() {
362         return (String JavaDoc[]) newWizardShortcuts.toArray(new String JavaDoc[newWizardShortcuts.size()]);
363     }
364
365     /**
366      * Returns the pane for a view reference.
367      */

368     private ViewPane getPane(IViewReference ref) {
369         return (ViewPane) ((WorkbenchPartReference) ref).getPane();
370     }
371
372     /**
373      * Returns the perspective shortcuts associated with this perspective.
374      *
375      * @return an array of perspective identifiers
376      */

377     public String JavaDoc[] getPerspectiveShortcuts() {
378         return (String JavaDoc[]) perspectiveShortcuts.toArray(new String JavaDoc[perspectiveShortcuts.size()]);
379     }
380
381     /**
382      * Returns the presentation.
383      */

384     public PerspectiveHelper getPresentation() {
385         return presentation;
386     }
387
388     /**
389      * Retrieves the fast view width ratio for the given view.
390      * If the ratio is not known, the default ratio for the view is assigned and returned.
391      */

392     public float getFastViewWidthRatio(IViewReference ref) {
393         ViewLayoutRec rec = getViewLayoutRec(ref, true);
394         if (rec.fastViewWidthRatio == IPageLayout.INVALID_RATIO) {
395             IViewRegistry reg = WorkbenchPlugin.getDefault().getViewRegistry();
396             IViewDescriptor desc = reg.find(ref.getId());
397             rec.fastViewWidthRatio =
398                 (desc != null
399                     ? desc.getFastViewWidthRatio()
400                     : IPageLayout.DEFAULT_FASTVIEW_RATIO);
401         }
402         return rec.fastViewWidthRatio;
403     }
404
405     /**
406      * Returns the ids of the parts to list in the Show In... dialog.
407      * This is a List of Strings.
408      */

409     public ArrayList JavaDoc getShowInPartIds() {
410         return showInPartIds;
411     }
412
413     /**
414      * Returns the time at which the last Show In was performed
415      * for the given target part, or 0 if unknown.
416      */

417     public long getShowInTime(String JavaDoc partId) {
418         Long JavaDoc t = (Long JavaDoc) showInTimes.get(partId);
419         return t == null ? 0L : t.longValue();
420     }
421
422     /**
423      * Returns the show view shortcuts associated with this perspective.
424      *
425      * @return an array of view identifiers
426      */

427     public String JavaDoc[] getShowViewShortcuts() {
428         return (String JavaDoc[]) showViewShortcuts.toArray(new String JavaDoc[showViewShortcuts.size()]);
429     }
430
431     /**
432      * Returns the view factory.
433      */

434     public ViewFactory getViewFactory() {
435         return viewFactory;
436     }
437
438     /**
439      * See IWorkbenchPage.
440      */

441     public IViewReference[] getViewReferences() {
442         // Get normal views.
443
if (presentation == null) {
444             return new IViewReference[0];
445         }
446
447         List JavaDoc panes = new ArrayList JavaDoc(5);
448         presentation.collectViewPanes(panes);
449
450         List JavaDoc fastViews = (fastViewManager != null) ?
451                             fastViewManager.getFastViews(null)
452                             : new ArrayList JavaDoc();
453         IViewReference[] resultArray = new IViewReference[panes.size()
454                 + fastViews.size()];
455
456         // Copy fast views.
457
int nView = 0;
458         for (int i = 0; i < fastViews.size(); i++) {
459             resultArray[nView] = (IViewReference) fastViews.get(i);
460             ++nView;
461         }
462
463         // Copy normal views.
464
for (int i = 0; i < panes.size(); i++) {
465             ViewPane pane = (ViewPane) panes.get(i);
466             resultArray[nView] = pane.getViewReference();
467             ++nView;
468         }
469
470         return resultArray;
471     }
472
473
474     /**
475      * Hide the editor area if visible
476      */

477     protected void hideEditorArea() {
478         if (!isEditorAreaVisible()) {
479             return;
480         }
481         
482         // Show the editor in the appropriate location
483
if (useNewMinMax(this)) {
484             // If it's the currently maximized part we have to restore first
485
if (getPresentation().getMaximizedStack() instanceof EditorStack) {
486                 getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED);
487             }
488             
489             boolean isMinimized = editorAreaState == IStackPresentationSite.STATE_MINIMIZED;
490             if (!isMinimized)
491                 hideEditorAreaLocal();
492             else
493                 setEditorAreaTrimVisibility(false);
494         }
495         else {
496             hideEditorAreaLocal();
497         }
498         
499         editorHidden = true;
500     }
501
502     /**
503      * Hide the editor area if visible
504      */

505     protected void hideEditorAreaLocal() {
506         if (editorHolder != null) {
507             return;
508         }
509
510         // Replace the editor area with a placeholder so we
511
// know where to put it back on show editor area request.
512
editorHolder = new PartPlaceholder(editorArea.getID());
513         presentation.getLayout().replace(editorArea, editorHolder);
514     }
515
516     /**
517      * Hides a fast view. The view shrinks equally <code>steps</code> times
518      * before disappearing completely.
519      */

520     private void hideFastView(IViewReference ref, int steps) {
521         setFastViewIconSelection(ref, false);
522
523         // Note: We always do at least one step of the animation.
524
// Note: This doesn't take into account the overhead of doing
525
if (ref == activeFastView) {
526             saveFastViewWidthRatio();
527             fastViewPane.hideView();
528         }
529     }
530
531     /**
532      * Hides the fast view sash for zooming in a fast view.
533      */

534     void hideFastViewSash() {
535         fastViewPane.hideFastViewSash();
536     }
537
538     public boolean hideView(IViewReference ref) {
539         // If the view is locked just return.
540
ViewPane pane = getPane(ref);
541
542         // Remove the view from the current presentation.
543
if (isFastView(ref)) {
544             if (pane != null) {
545                 pane.setFast(false); //force an update of the toolbar
546
}
547             if (activeFastView == ref) {
548                 setActiveFastView(null);
549             }
550             if (pane != null) {
551                 pane.getControl().setEnabled(true);
552             }
553         } else {
554             presentation.removePart(pane);
555         }
556
557         // Dispose view if ref count == 0.
558
getViewFactory().releaseView(ref);
559         return true;
560     }
561
562     /*
563      * Return whether the editor area is visible or not.
564      */

565     protected boolean isEditorAreaVisible() {
566         return !editorHidden;
567     }
568
569     /**
570      * Returns true if a view is fast.
571      */

572     public boolean isFastView(IViewReference ref) {
573         if (fastViewManager == null)
574             return false;
575         
576         return fastViewManager.isFastView(ref);
577     }
578
579     /**
580      * Returns the view layout rec for the given view reference,
581      * or null if not found. If create is true, it creates the record
582      * if not already created.
583      */

584     public ViewLayoutRec getViewLayoutRec(IViewReference ref, boolean create) {
585         ViewLayoutRec result = getViewLayoutRec(ViewFactory.getKey(ref), create);
586         if (result == null && create==false) {
587             result = getViewLayoutRec(ref.getId(), false);
588         }
589         return result;
590     }
591
592     /**
593      * Returns the view layout record for the given view id
594      * or null if not found. If create is true, it creates the record
595      * if not already created.
596      */

597     private ViewLayoutRec getViewLayoutRec(String JavaDoc viewId, boolean create) {
598         ViewLayoutRec rec = (ViewLayoutRec) mapIDtoViewLayoutRec.get(viewId);
599         if (rec == null && create) {
600             rec = new ViewLayoutRec();
601             mapIDtoViewLayoutRec.put(viewId, rec);
602         }
603         return rec;
604     }
605
606     /**
607      * Returns true if a layout or perspective is fixed.
608      */

609     public boolean isFixedLayout() {
610         //@issue is there a difference between a fixed
611
//layout and a fixed perspective?? If not the API
612
//may need some polish, WorkbenchPage, PageLayout
613
//and Perspective all have isFixed methods.
614
//PageLayout and Perspective have their own fixed
615
//attribute, we are assuming they are always in sync.
616
//WorkbenchPage delegates to the perspective.
617
return fixed;
618     }
619
620     /**
621      * Returns true if a view is standalone.
622      *
623      * @since 3.0
624      */

625     public boolean isStandaloneView(IViewReference ref) {
626         ViewLayoutRec rec = getViewLayoutRec(ref, false);
627         return rec != null && rec.isStandalone;
628     }
629
630     /**
631      * Returns whether the title for a view should
632      * be shown. This applies only to standalone views.
633      *
634      * @since 3.0
635      */

636     public boolean getShowTitleView(IViewReference ref) {
637         ViewLayoutRec rec = getViewLayoutRec(ref, false);
638         return rec != null && rec.showTitle;
639     }
640
641     /**
642      * Creates a new presentation from a persistence file.
643      * Note: This method should not modify the current state of the perspective.
644      */

645     private void loadCustomPersp(PerspectiveDescriptor persp) {
646         //get the layout from the registry
647
PerspectiveRegistry perspRegistry = (PerspectiveRegistry) WorkbenchPlugin
648                 .getDefault().getPerspectiveRegistry();
649         try {
650             IMemento memento = perspRegistry.getCustomPersp(persp.getId());
651             // Restore the layout state.
652
MultiStatus status = new MultiStatus(
653                     PlatformUI.PLUGIN_ID,
654                     IStatus.OK,
655                     NLS.bind(WorkbenchMessages.Perspective_unableToRestorePerspective, persp.getLabel()),
656                     null);
657             status.merge(restoreState(memento));
658             status.merge(restoreState());
659             if (status.getSeverity() != IStatus.OK) {
660                 unableToOpenPerspective(persp, status);
661             }
662         } catch (IOException JavaDoc e) {
663             unableToOpenPerspective(persp, null);
664         } catch (WorkbenchException e) {
665             unableToOpenPerspective(persp, e.getStatus());
666         }
667     }
668
669     private void unableToOpenPerspective(PerspectiveDescriptor persp,
670             IStatus status) {
671         PerspectiveRegistry perspRegistry = (PerspectiveRegistry) WorkbenchPlugin
672                 .getDefault().getPerspectiveRegistry();
673         perspRegistry.deletePerspective(persp);
674         // If this is a predefined perspective, we will not be able to delete
675
// the perspective (we wouldn't want to). But make sure to delete the
676
// customized portion.
677
persp.deleteCustomDefinition();
678         String JavaDoc title = WorkbenchMessages.Perspective_problemRestoringTitle;
679         String JavaDoc msg = WorkbenchMessages.Perspective_errorReadingState;
680         if (status == null) {
681             MessageDialog.openError((Shell) null, title, msg);
682         } else {
683             ErrorDialog.openError((Shell) null, title, msg, status);
684         }
685     }
686
687     /**
688      * Create a presentation for a perspective.
689      * Note: This method should not modify the current state of the perspective.
690      */

691     private void loadPredefinedPersp(PerspectiveDescriptor persp)
692             throws WorkbenchException {
693         // Create layout engine.
694
IPerspectiveFactory factory = null;
695         try {
696             factory = persp.createFactory();
697         } catch (CoreException e) {
698             throw new WorkbenchException(NLS.bind(WorkbenchMessages.Perspective_unableToLoad, persp.getId() ));
699         }
700         
701         /*
702          * IPerspectiveFactory#createFactory() can return null
703          */

704         if (factory == null) {
705             throw new WorkbenchException(NLS.bind(WorkbenchMessages.Perspective_unableToLoad, persp.getId() ));
706         }
707         
708         
709         // Create layout factory.
710
ViewSashContainer container = new ViewSashContainer(page, getClientComposite());
711         layout = new PageLayout(container, getViewFactory(),
712                 editorArea, descriptor);
713         layout.setFixed(descriptor.getFixed());
714
715         // add the placeholders for the sticky folders and their contents
716
IPlaceholderFolderLayout stickyFolderRight = null, stickyFolderLeft = null, stickyFolderTop = null, stickyFolderBottom = null;
717
718         IStickyViewDescriptor[] descs = WorkbenchPlugin.getDefault()
719                 .getViewRegistry().getStickyViews();
720         for (int i = 0; i < descs.length; i++) {
721             IStickyViewDescriptor stickyViewDescriptor = descs[i];
722             String JavaDoc id = stickyViewDescriptor.getId();
723             switch (stickyViewDescriptor.getLocation()) {
724             case IPageLayout.RIGHT:
725                 if (stickyFolderRight == null) {
726                     stickyFolderRight = layout
727                             .createPlaceholderFolder(
728                                     StickyViewDescriptor.STICKY_FOLDER_RIGHT,
729                                     IPageLayout.RIGHT, .75f,
730                                     IPageLayout.ID_EDITOR_AREA);
731                 }
732                 stickyFolderRight.addPlaceholder(id);
733                 break;
734             case IPageLayout.LEFT:
735                 if (stickyFolderLeft == null) {
736                     stickyFolderLeft = layout.createPlaceholderFolder(
737                             StickyViewDescriptor.STICKY_FOLDER_LEFT,
738                             IPageLayout.LEFT, .25f, IPageLayout.ID_EDITOR_AREA);
739                 }
740                 stickyFolderLeft.addPlaceholder(id);
741                 break;
742             case IPageLayout.TOP:
743                 if (stickyFolderTop == null) {
744                     stickyFolderTop = layout.createPlaceholderFolder(
745                             StickyViewDescriptor.STICKY_FOLDER_TOP,
746                             IPageLayout.TOP, .25f, IPageLayout.ID_EDITOR_AREA);
747                 }
748                 stickyFolderTop.addPlaceholder(id);
749                 break;
750             case IPageLayout.BOTTOM:
751                 if (stickyFolderBottom == null) {
752                     stickyFolderBottom = layout.createPlaceholderFolder(
753                             StickyViewDescriptor.STICKY_FOLDER_BOTTOM,
754                             IPageLayout.BOTTOM, .75f,
755                             IPageLayout.ID_EDITOR_AREA);
756                 }
757                 stickyFolderBottom.addPlaceholder(id);
758                 break;
759             }
760
761             //should never be null as we've just added the view above
762
IViewLayout viewLayout = layout.getViewLayout(id);
763             viewLayout.setCloseable(stickyViewDescriptor.isCloseable());
764             viewLayout.setMoveable(stickyViewDescriptor.isMoveable());
765         }
766
767         // Run layout engine.
768
factory.createInitialLayout(layout);
769         PerspectiveExtensionReader extender = new PerspectiveExtensionReader();
770         extender.extendLayout(page.getExtensionTracker(), descriptor.getId(), layout);
771
772         // Retrieve view layout info stored in the page layout.
773
mapIDtoViewLayoutRec.putAll(layout.getIDtoViewLayoutRecMap());
774
775         // Create action sets.
776
List JavaDoc temp = new ArrayList JavaDoc();
777         createInitialActionSets(temp, layout.getActionSets());
778
779         IContextService service = null;
780         if (page != null) {
781             service = (IContextService) page.getWorkbenchWindow().getService(
782                     IContextService.class);
783         }
784         try {
785             if (service!=null) {
786                 service.activateContext(ContextAuthority.DEFER_EVENTS);
787             }
788             for (Iterator JavaDoc iter = temp.iterator(); iter.hasNext();) {
789                 IActionSetDescriptor descriptor = (IActionSetDescriptor) iter
790                         .next();
791                 addAlwaysOn(descriptor);
792             }
793         } finally {
794             if (service!=null) {
795                 service.activateContext(ContextAuthority.SEND_EVENTS);
796             }
797         }
798         newWizardShortcuts = layout.getNewWizardShortcuts();
799         showViewShortcuts = layout.getShowViewShortcuts();
800         perspectiveShortcuts = layout.getPerspectiveShortcuts();
801         showInPartIds = layout.getShowInPartIds();
802
803         // Retrieve fast views
804
if (fastViewManager != null) {
805             ArrayList JavaDoc fastViews = layout.getFastViews();
806             for (Iterator JavaDoc fvIter = fastViews.iterator(); fvIter.hasNext();) {
807                 IViewReference ref = (IViewReference) fvIter.next();
808                 fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref,
809                         !fvIter.hasNext());
810             }
811         }
812
813         // Is the layout fixed
814
fixed = layout.isFixed();
815
816         // Create presentation.
817
presentation = new PerspectiveHelper(page, container, this);
818
819         // Hide editor area if requested by factory
820
if (!layout.isEditorAreaVisible()) {
821             hideEditorArea();
822         }
823
824     }
825
826     private void removeAlwaysOn(IActionSetDescriptor descriptor) {
827         if (descriptor == null) {
828             return;
829         }
830         if (!alwaysOnActionSets.contains(descriptor)) {
831             return;
832         }
833         
834         alwaysOnActionSets.remove(descriptor);
835         if (page != null) {
836             page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_HIDE);
837         }
838     }
839     
840     private void addAlwaysOff(IActionSetDescriptor descriptor) {
841         if (descriptor == null) {
842             return;
843         }
844         if (alwaysOffActionSets.contains(descriptor)) {
845             return;
846         }
847         alwaysOffActionSets.add(descriptor);
848         if (page != null) {
849             page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_MASK);
850         }
851         removeAlwaysOn(descriptor);
852     }
853     
854     private void addAlwaysOn(IActionSetDescriptor descriptor) {
855         if (descriptor == null) {
856             return;
857         }
858         if (alwaysOnActionSets.contains(descriptor)) {
859             return;
860         }
861         alwaysOnActionSets.add(descriptor);
862         if (page != null) {
863             page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_SHOW);
864         }
865         removeAlwaysOff(descriptor);
866     }
867     
868     private void removeAlwaysOff(IActionSetDescriptor descriptor) {
869         if (descriptor == null) {
870             return;
871         }
872         if (!alwaysOffActionSets.contains(descriptor)) {
873             return;
874         }
875         alwaysOffActionSets.remove(descriptor);
876         if (page != null) {
877             page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_UNMASK);
878         }
879     }
880     
881     /**
882      * activate.
883      */

884     protected void onActivate() {
885         // Update editor area state.
886
if (editorArea.getControl() != null) {
887             boolean visible = isEditorAreaVisible();
888             boolean inTrim = editorAreaState == IStackPresentationSite.STATE_MINIMIZED;
889             
890             // Funky check: Intro uses the old zoom behaviour when maximized. Make sure we don't show the
891
// editor if it's supposed to be hidden because the intro is maximized. Note that
892
// 'childObscuredByZoom' will only respond 'true' when using the old behaviour.
893
boolean introMaxed = getPresentation().getLayout().childObscuredByZoom(editorArea);
894             
895             editorArea.setVisible(visible && !inTrim && !introMaxed);
896         }
897
898         // Update fast views.
899
// Make sure the control for the fastviews are created so they can
900
// be activated.
901
if (fastViewManager != null) {
902             List JavaDoc fastViews = fastViewManager.getFastViews(null);
903             for (int i = 0; i < fastViews.size(); i++) {
904                 ViewPane pane = getPane((IViewReference) fastViews.get(i));
905                 if (pane != null) {
906                     Control ctrl = pane.getControl();
907                     if (ctrl == null) {
908                         pane.createControl(getClientComposite());
909                         ctrl = pane.getControl();
910                     }
911                     ctrl.setEnabled(false); // Remove focus support.
912
}
913             }
914         }
915
916         // Set the visibility of all fast view pins
917
setAllPinsVisible(true);
918
919         // Trim Stack Support
920
boolean useNewMinMax = Perspective.useNewMinMax(this);
921         boolean hideEditorArea = shouldHideEditorsOnActivate || (editorHidden && editorHolder == null);
922         
923         // We have to set the editor area's stack state -before-
924
// activating the presentation since it's used there to determine
925
// size of the resulting stack
926
if (useNewMinMax && !hideEditorArea) {
927             refreshEditorAreaVisibility();
928         }
929
930         // Show the layout
931
presentation.activate(getClientComposite());
932
933         if (useNewMinMax) {
934             fastViewManager.activate();
935
936             // Move any minimized extension stacks to the trim
937
if (layout != null) {
938                 // Turn aimations off
939
IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
940                 boolean useAnimations = preferenceStore
941                         .getBoolean(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS);
942                 preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, false);
943                 
944                 List JavaDoc minStacks = layout.getMinimizedStacks();
945                 for (Iterator JavaDoc msIter = minStacks.iterator(); msIter.hasNext();) {
946                     ViewStack vs = (ViewStack) msIter.next();
947                     vs.setMinimized(true);
948                 }
949
950                 // Restore the animation pref
951
preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, useAnimations);
952
953                 // this is a one-off deal...set during the extension reading
954
minStacks.clear();
955                 layout = null;
956             }
957         }
958         else {
959             // Update the FVB only if not using the new min/max
960
WorkbenchWindow wbw = (WorkbenchWindow) page.getWorkbenchWindow();
961             if (wbw != null) {
962                 ITrimManager tbm = wbw.getTrimManager();
963                 if (tbm != null) {
964                     IWindowTrim fvb = tbm.getTrim(FastViewBar.FASTVIEWBAR_ID);
965                     if (fvb instanceof FastViewBar) {
966                         ((FastViewBar)fvb).update(true);
967                     }
968                 }
969             }
970         }
971         
972         // If we are -not- using the new min/max then ensure that there
973
// are no stacks in the trim. This can happen when a user switches
974
// back to the 3.0 presentation...
975
if (!Perspective.useNewMinMax(this) && fastViewManager != null) {
976             boolean stacksWereRestored = fastViewManager.restoreAllTrimStacks();
977             setEditorAreaTrimVisibility(false);
978             
979             // Restore any 'maximized' view stack since we've restored
980
// the minimized stacks
981
if (stacksWereRestored && presentation.getMaximizedStack() instanceof ViewStack) {
982                 ViewStack vs = (ViewStack) presentation.getMaximizedStack();
983                 vs.setPresentationState(IStackPresentationSite.STATE_RESTORED);
984                 presentation.setMaximizedStack(null);
985             }
986         }
987
988         // We hide the editor area -after- the presentation activates
989
if (hideEditorArea) {
990             // We do this here to ensure that createPartControl is called on the
991
// top editor
992
// before it is hidden. See bug 20166.
993
hideEditorArea();
994             shouldHideEditorsOnActivate = false;
995             
996             // this is an override so it should handle both states
997
if (useNewMinMax)
998                 setEditorAreaTrimVisibility(editorAreaState == IStackPresentationSite.STATE_MINIMIZED);
999         }
1000    }
1001
1002    /**
1003     * deactivate.
1004     */

1005    protected void onDeactivate() {
1006        presentation.deactivate();
1007        setActiveFastView(null);
1008        setAllPinsVisible(false);
1009
1010        // Update fast views.
1011
if (fastViewManager != null) {
1012            List JavaDoc fastViews = fastViewManager.getFastViews(null);
1013            for (int i = 0; i < fastViews.size(); i++) {
1014                ViewPane pane = getPane((IViewReference) fastViews.get(i));
1015                if (pane != null) {
1016                    Control ctrl = pane.getControl();
1017                    if (ctrl != null) {
1018                        ctrl.setEnabled(true); // Add focus support.
1019
}
1020                }
1021            }
1022            
1023            fastViewManager.deActivate();
1024        }
1025        
1026        // Ensure that the editor area trim is hidden as well
1027
setEditorAreaTrimVisibility(false);
1028    }
1029
1030    /**
1031     * Notifies that a part has been activated.
1032     */

1033    public void partActivated(IWorkbenchPart activePart) {
1034        // If a fastview is open close it.
1035
if (activeFastView != null
1036                && activeFastView.getPart(false) != activePart) {
1037            setActiveFastView(null);
1038        }
1039    }
1040
1041    /**
1042     * The user successfully performed a Show In... action on the specified part.
1043     * Update the history.
1044     */

1045    public void performedShowIn(String JavaDoc partId) {
1046        showInTimes.put(partId, new Long JavaDoc(System.currentTimeMillis()));
1047    }
1048
1049    /**
1050     * Sets the fast view attribute. Note: The page is expected to update action
1051     * bars.
1052     */

1053    public void removeFastView(IViewReference ref) {
1054        removeFastView(ref, true);
1055    }
1056    
1057    /**
1058     * Sets the fast view attribute. Note: The page is expected to update action
1059     * bars.
1060     */

1061    public void removeFastView(IViewReference ref, boolean handleLayout) {
1062        ViewPane pane = getPane(ref);
1063
1064        if (activeFastView == ref) {
1065            setActiveFastView(null);
1066        }
1067        
1068        pane.setFast(false);
1069        Control ctrl = pane.getControl();
1070        if (ctrl != null) {
1071            ctrl.setEnabled(true); // Modify focus support.
1072
}
1073        
1074        if (handleLayout) {
1075            // We are disabling the pane because it will be enabled when it
1076
// is added to the presentation. When a pane is enabled a drop
1077
// listener is added to it, and we do not want to have multiple
1078
// listeners for a pane
1079
presentation.addPart(pane);
1080        }
1081    }
1082
1083    /**
1084     * Fills a presentation with layout data.
1085     * Note: This method should not modify the current state of the perspective.
1086     */

1087    public IStatus restoreState(IMemento memento) {
1088        MultiStatus result = new MultiStatus(
1089                PlatformUI.PLUGIN_ID,
1090                IStatus.OK,
1091                WorkbenchMessages.Perspective_problemsRestoringPerspective, null);
1092
1093        // Create persp descriptor.
1094
descriptor = new PerspectiveDescriptor(null, null, null);
1095        result.add(descriptor.restoreState(memento));
1096        PerspectiveDescriptor desc = (PerspectiveDescriptor) WorkbenchPlugin
1097                .getDefault().getPerspectiveRegistry().findPerspectiveWithId(
1098                        descriptor.getId());
1099        if (desc != null) {
1100            descriptor = desc;
1101        }
1102
1103        this.memento = memento;
1104        // Add the visible views.
1105
IMemento views[] = memento.getChildren(IWorkbenchConstants.TAG_VIEW);
1106        result.merge(createReferences(views));
1107
1108        memento = memento.getChild(IWorkbenchConstants.TAG_FAST_VIEWS);
1109        if (memento != null) {
1110            views = memento.getChildren(IWorkbenchConstants.TAG_VIEW);
1111            result.merge(createReferences(views));
1112        }
1113        return result;
1114    }
1115
1116    IStatus createReferences(IMemento views[]) {
1117        MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK,
1118                WorkbenchMessages.Perspective_problemsRestoringViews, null);
1119
1120        for (int x = 0; x < views.length; x++) {
1121            // Get the view details.
1122
IMemento childMem = views[x];
1123            String JavaDoc id = childMem.getString(IWorkbenchConstants.TAG_ID);
1124            // skip creation of the intro reference - it's handled elsewhere.
1125
if (id.equals(IIntroConstants.INTRO_VIEW_ID)) {
1126                continue;
1127            }
1128
1129            String JavaDoc secondaryId = ViewFactory.extractSecondaryId(id);
1130            if (secondaryId != null) {
1131                id = ViewFactory.extractPrimaryId(id);
1132            }
1133            // Create and open the view.
1134
try {
1135                if (!"true".equals(childMem.getString(IWorkbenchConstants.TAG_REMOVED))) { //$NON-NLS-1$
1136
viewFactory.createView(id, secondaryId);
1137                }
1138            } catch (PartInitException e) {
1139                childMem.putString(IWorkbenchConstants.TAG_REMOVED, "true"); //$NON-NLS-1$
1140
result.add(StatusUtil.newStatus(IStatus.ERROR,
1141                        e.getMessage() == null ? "" : e.getMessage(), //$NON-NLS-1$
1142
e));
1143            }
1144        }
1145        return result;
1146    }
1147
1148    /**
1149     * Fills a presentation with layout data.
1150     * Note: This method should not modify the current state of the perspective.
1151     */

1152    public IStatus restoreState() {
1153        if (this.memento == null) {
1154            return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); //$NON-NLS-1$
1155
}
1156
1157        MultiStatus result = new MultiStatus(
1158                PlatformUI.PLUGIN_ID,
1159                IStatus.OK,
1160                WorkbenchMessages.Perspective_problemsRestoringPerspective, null);
1161
1162        IMemento memento = this.memento;
1163        this.memento = null;
1164
1165        final IMemento boundsMem = memento.getChild(IWorkbenchConstants.TAG_WINDOW);
1166        if (boundsMem != null) {
1167            final Rectangle r = new Rectangle(0, 0, 0, 0);
1168            r.x = boundsMem.getInteger(IWorkbenchConstants.TAG_X).intValue();
1169            r.y = boundsMem.getInteger(IWorkbenchConstants.TAG_Y).intValue();
1170            r.height = boundsMem.getInteger(IWorkbenchConstants.TAG_HEIGHT)
1171                    .intValue();
1172            r.width = boundsMem.getInteger(IWorkbenchConstants.TAG_WIDTH)
1173                    .intValue();
1174            StartupThreading.runWithoutExceptions(new StartupRunnable() {
1175
1176                public void runWithException() throws Throwable JavaDoc {
1177                    if (page.getWorkbenchWindow().getPages().length == 0) {
1178                        page.getWorkbenchWindow().getShell().setBounds(r);
1179                    }
1180                }
1181            });
1182
1183        }
1184
1185        // Create an empty presentation..
1186
final PerspectiveHelper [] presArray = new PerspectiveHelper[1];
1187        StartupThreading.runWithoutExceptions(new StartupRunnable() {
1188
1189            public void runWithException() throws Throwable JavaDoc {
1190                ViewSashContainer mainLayout = new ViewSashContainer(page, getClientComposite());
1191                presArray[0] = new PerspectiveHelper(page, mainLayout, Perspective.this);
1192            }});
1193        final PerspectiveHelper pres = presArray[0];
1194
1195        // Read the layout.
1196
result.merge(pres.restoreState(memento
1197                .getChild(IWorkbenchConstants.TAG_LAYOUT)));
1198
1199        StartupThreading.runWithoutExceptions(new StartupRunnable() {
1200
1201            public void runWithException() throws Throwable JavaDoc {
1202                // Add the editor workbook. Do not hide it now.
1203
pres.replacePlaceholderWithPart(editorArea);
1204            }});
1205
1206        // Add the visible views.
1207
IMemento[] views = memento.getChildren(IWorkbenchConstants.TAG_VIEW);
1208
1209        for (int x = 0; x < views.length; x++) {
1210            // Get the view details.
1211
IMemento childMem = views[x];
1212            String JavaDoc id = childMem.getString(IWorkbenchConstants.TAG_ID);
1213            String JavaDoc secondaryId = ViewFactory.extractSecondaryId(id);
1214            if (secondaryId != null) {
1215                id = ViewFactory.extractPrimaryId(id);
1216            }
1217
1218            // skip the intro as it is restored higher up in workbench.
1219
if (id.equals(IIntroConstants.INTRO_VIEW_ID)) {
1220                continue;
1221            }
1222            
1223            // Create and open the view.
1224
IViewReference viewRef = viewFactory.getView(id, secondaryId);
1225            WorkbenchPartReference ref = (WorkbenchPartReference) viewRef;
1226
1227            // report error
1228
if (ref == null) {
1229                String JavaDoc key = ViewFactory.getKey(id, secondaryId);
1230                result.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0,
1231                        NLS.bind(WorkbenchMessages.Perspective_couldNotFind, key ), null));
1232                continue;
1233            }
1234            boolean willPartBeVisible = pres.willPartBeVisible(ref.getId(),
1235                    secondaryId);
1236            if (willPartBeVisible) {
1237                IViewPart view = (IViewPart) ref.getPart(true);
1238                if (view != null) {
1239                    ViewSite site = (ViewSite) view.getSite();
1240                    ViewPane pane = (ViewPane) site.getPane();
1241                    pres.replacePlaceholderWithPart(pane);
1242                }
1243            } else {
1244                pres.replacePlaceholderWithPart(ref.getPane());
1245            }
1246        }
1247
1248        // Load the fast views
1249
if (fastViewManager != null)
1250            fastViewManager.restoreState(memento, result);
1251
1252        // Load the view layout recs
1253
IMemento[] recMementos = memento
1254                .getChildren(IWorkbenchConstants.TAG_VIEW_LAYOUT_REC);
1255        for (int i = 0; i < recMementos.length; i++) {
1256            IMemento recMemento = recMementos[i];
1257            String JavaDoc compoundId = recMemento
1258                    .getString(IWorkbenchConstants.TAG_ID);
1259            if (compoundId != null) {
1260                ViewLayoutRec rec = getViewLayoutRec(compoundId, true);
1261                if (IWorkbenchConstants.FALSE.equals(recMemento
1262                        .getString(IWorkbenchConstants.TAG_CLOSEABLE))) {
1263                    rec.isCloseable = false;
1264                }
1265                if (IWorkbenchConstants.FALSE.equals(recMemento
1266                        .getString(IWorkbenchConstants.TAG_MOVEABLE))) {
1267                    rec.isMoveable = false;
1268                }
1269                if (IWorkbenchConstants.TRUE.equals(recMemento
1270                        .getString(IWorkbenchConstants.TAG_STANDALONE))) {
1271                    rec.isStandalone = true;
1272                    rec.showTitle = !IWorkbenchConstants.FALSE
1273                            .equals(recMemento
1274                                    .getString(IWorkbenchConstants.TAG_SHOW_TITLE));
1275                }
1276            }
1277        }
1278
1279        final IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class);
1280        try { // one big try block, don't kill me here
1281
// defer context events
1282
if (service != null) {
1283                service.activateContext(ContextAuthority.DEFER_EVENTS);
1284            }
1285
1286            HashSet JavaDoc knownActionSetIds = new HashSet JavaDoc();
1287
1288            // Load the always on action sets.
1289
IMemento[] actions = memento
1290                    .getChildren(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET);
1291            for (int x = 0; x < actions.length; x++) {
1292                String JavaDoc actionSetID = actions[x]
1293                        .getString(IWorkbenchConstants.TAG_ID);
1294                final IActionSetDescriptor d = WorkbenchPlugin.getDefault()
1295                        .getActionSetRegistry().findActionSet(actionSetID);
1296                if (d != null) {
1297                    StartupThreading
1298                            .runWithoutExceptions(new StartupRunnable() {
1299                                public void runWithException() throws Throwable JavaDoc {
1300                                    addAlwaysOn(d);
1301                                }
1302                            });
1303
1304                    knownActionSetIds.add(actionSetID);
1305                }
1306            }
1307
1308            // Load the always off action sets.
1309
actions = memento
1310                    .getChildren(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET);
1311            for (int x = 0; x < actions.length; x++) {
1312                String JavaDoc actionSetID = actions[x]
1313                        .getString(IWorkbenchConstants.TAG_ID);
1314                final IActionSetDescriptor d = WorkbenchPlugin.getDefault()
1315                        .getActionSetRegistry().findActionSet(actionSetID);
1316                if (d != null) {
1317                    StartupThreading
1318                            .runWithoutExceptions(new StartupRunnable() {
1319                                public void runWithException() throws Throwable JavaDoc {
1320                                    addAlwaysOff(d);
1321                                }
1322                            });
1323                    knownActionSetIds.add(actionSetID);
1324                }
1325            }
1326
1327            // Load "show view actions".
1328
actions = memento
1329                    .getChildren(IWorkbenchConstants.TAG_SHOW_VIEW_ACTION);
1330            showViewShortcuts = new ArrayList JavaDoc(actions.length);
1331            for (int x = 0; x < actions.length; x++) {
1332                String JavaDoc id = actions[x].getString(IWorkbenchConstants.TAG_ID);
1333                showViewShortcuts.add(id);
1334            }
1335
1336            // Load "show in times".
1337
actions = memento.getChildren(IWorkbenchConstants.TAG_SHOW_IN_TIME);
1338            for (int x = 0; x < actions.length; x++) {
1339                String JavaDoc id = actions[x].getString(IWorkbenchConstants.TAG_ID);
1340                String JavaDoc timeStr = actions[x]
1341                        .getString(IWorkbenchConstants.TAG_TIME);
1342                if (id != null && timeStr != null) {
1343                    try {
1344                        long time = Long.parseLong(timeStr);
1345                        showInTimes.put(id, new Long JavaDoc(time));
1346                    } catch (NumberFormatException JavaDoc e) {
1347                        // skip this one
1348
}
1349                }
1350            }
1351
1352            // Load "show in parts" from registry, not memento
1353
showInPartIds = getShowInIdsFromRegistry();
1354
1355            // Load "new wizard actions".
1356
actions = memento
1357                    .getChildren(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION);
1358            newWizardShortcuts = new ArrayList JavaDoc(actions.length);
1359            for (int x = 0; x < actions.length; x++) {
1360                String JavaDoc id = actions[x].getString(IWorkbenchConstants.TAG_ID);
1361                newWizardShortcuts.add(id);
1362            }
1363
1364            // Load "perspective actions".
1365
actions = memento
1366                    .getChildren(IWorkbenchConstants.TAG_PERSPECTIVE_ACTION);
1367            perspectiveShortcuts = new ArrayList JavaDoc(actions.length);
1368            for (int x = 0; x < actions.length; x++) {
1369                String JavaDoc id = actions[x].getString(IWorkbenchConstants.TAG_ID);
1370                perspectiveShortcuts.add(id);
1371            }
1372
1373            ArrayList JavaDoc extActionSets = getPerspectiveExtensionActionSets();
1374            for (int i = 0; i < extActionSets.size(); i++) {
1375                String JavaDoc actionSetID = (String JavaDoc) extActionSets.get(i);
1376                if (knownActionSetIds.contains(actionSetID)) {
1377                    continue;
1378                }
1379                final IActionSetDescriptor d = WorkbenchPlugin.getDefault()
1380                        .getActionSetRegistry().findActionSet(actionSetID);
1381                if (d != null) {
1382                    StartupThreading
1383                            .runWithoutExceptions(new StartupRunnable() {
1384                                public void runWithException() throws Throwable JavaDoc {
1385                                    addAlwaysOn(d);
1386                                }
1387                            });
1388                    knownActionSetIds.add(d.getId());
1389                }
1390            }
1391
1392            // Add the visible set of action sets to our knownActionSetIds
1393
// Now go through the registry to ensure we pick up any new action
1394
// sets
1395
// that have been added but not yet considered by this perspective.
1396
ActionSetRegistry reg = WorkbenchPlugin.getDefault()
1397                    .getActionSetRegistry();
1398            IActionSetDescriptor[] array = reg.getActionSets();
1399            int count = array.length;
1400            for (int i = 0; i < count; i++) {
1401                IActionSetDescriptor desc = array[i];
1402                if ((!knownActionSetIds.contains(desc.getId()))
1403                        && (desc.isInitiallyVisible())) {
1404                    addActionSet(desc);
1405                }
1406            }
1407        } finally {
1408            // restart context changes
1409
if (service != null) {
1410                StartupThreading.runWithoutExceptions(new StartupRunnable() {
1411                    public void runWithException() throws Throwable JavaDoc {
1412                        service.activateContext(ContextAuthority.SEND_EVENTS);
1413                    }
1414                });
1415            }
1416        }
1417
1418        // Save presentation.
1419
presentation = pres;
1420
1421        // Hide the editor area if needed. Need to wait for the
1422
// presentation to be fully setup first.
1423
Integer JavaDoc areaVisible = memento
1424                .getInteger(IWorkbenchConstants.TAG_AREA_VISIBLE);
1425        // Rather than hiding the editors now we must wait until after their
1426
// controls
1427
// are created. This ensures that if an editor is instantiated,
1428
// createPartControl
1429
// is also called. See bug 20166.
1430
shouldHideEditorsOnActivate = (areaVisible != null && areaVisible
1431                .intValue() == 0);
1432
1433        // Restore the trim state of the editor area
1434
IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
1435        boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX);
1436        if (useNewMinMax) {
1437            Integer JavaDoc trimStateInt = memento.getInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE);
1438            if (trimStateInt != null) {
1439                editorAreaState = trimStateInt.intValue() & 0x3; // low order two bits contain the state
1440
editorAreaRestoreOnUnzoom = (trimStateInt.intValue() & 4) != 0;
1441            }
1442        }
1443        
1444        // restore the fixed state
1445
Integer JavaDoc isFixed = memento.getInteger(IWorkbenchConstants.TAG_FIXED);
1446        fixed = (isFixed != null && isFixed.intValue() == 1);
1447
1448        return result;
1449    }
1450
1451    /**
1452     * Restores a fast view to its corrent presentation structure.
1453     * This method is pubilc because the FastViewManager uses it to
1454     * reconstruct it minimized stacks on startup.
1455     *
1456     * @param fvMemento The mement containing the fast view info
1457     * @param result The result status
1458     * @return The reference to the restored view
1459     */

1460    public IViewReference restoreFastView(IMemento fvMemento, MultiStatus result) {
1461        String JavaDoc viewID = fvMemento.getString(IWorkbenchConstants.TAG_ID);
1462        String JavaDoc secondaryId = ViewFactory.extractSecondaryId(viewID);
1463        if (secondaryId != null) {
1464            viewID = ViewFactory.extractPrimaryId(viewID);
1465        }
1466
1467        IViewReference viewRef = getViewReference(viewID, secondaryId);
1468        if (viewRef == null) {
1469            String JavaDoc key = ViewFactory.getKey(viewID, secondaryId);
1470            WorkbenchPlugin
1471                    .log("Could not create view: '" + key + "'."); //$NON-NLS-1$ //$NON-NLS-2$
1472
result
1473                    .add(new Status(
1474                            IStatus.ERROR,
1475                            PlatformUI.PLUGIN_ID,
1476                            0,
1477                            NLS.bind(WorkbenchMessages.Perspective_couldNotFind, key ),
1478                            null));
1479            return null;
1480        }
1481
1482        // Restore fast view width ratio
1483
Float JavaDoc ratio = fvMemento.getFloat(IWorkbenchConstants.TAG_RATIO);
1484        if (ratio == null) {
1485            Integer JavaDoc viewWidth = fvMemento
1486                    .getInteger(IWorkbenchConstants.TAG_WIDTH);
1487            if (viewWidth == null) {
1488                ratio = new Float JavaDoc(IPageLayout.DEFAULT_FASTVIEW_RATIO);
1489            } else {
1490                ratio = new Float JavaDoc((float) viewWidth.intValue()
1491                        / (float) getClientComposite().getSize().x);
1492            }
1493        }
1494        ViewLayoutRec rec = getViewLayoutRec(viewRef, true);
1495        rec.fastViewWidthRatio = ratio.floatValue();
1496        
1497        return viewRef;
1498    }
1499    
1500    /**
1501     * Returns the ActionSets read from perspectiveExtensions in the registry.
1502     */

1503    private ArrayList JavaDoc getPerspectiveExtensionActionSets() {
1504        PerspectiveExtensionReader reader = new PerspectiveExtensionReader();
1505        reader
1506                .setIncludeOnlyTags(new String JavaDoc[] { IWorkbenchRegistryConstants.TAG_ACTION_SET });
1507        PageLayout layout = new PageLayout();
1508        reader.extendLayout(null, descriptor.getOriginalId(), layout);
1509        return layout.getActionSets();
1510    }
1511
1512    /**
1513     * Returns the Show In... part ids read from the registry.
1514     */

1515    private ArrayList JavaDoc getShowInIdsFromRegistry() {
1516        PerspectiveExtensionReader reader = new PerspectiveExtensionReader();
1517        reader
1518                .setIncludeOnlyTags(new String JavaDoc[] { IWorkbenchRegistryConstants.TAG_SHOW_IN_PART });
1519        PageLayout layout = new PageLayout();
1520        reader.extendLayout(null, descriptor.getOriginalId(), layout);
1521        return layout.getShowInPartIds();
1522    }
1523
1524    /**
1525     * Save the layout.
1526     */

1527    public void saveDesc() {
1528        saveDescAs(descriptor);
1529    }
1530
1531    /**
1532     * Save the layout.
1533     */

1534    public void saveDescAs(IPerspectiveDescriptor desc) {
1535        PerspectiveDescriptor realDesc = (PerspectiveDescriptor) desc;
1536        //get the layout from the registry
1537
PerspectiveRegistry perspRegistry = (PerspectiveRegistry) WorkbenchPlugin
1538                .getDefault().getPerspectiveRegistry();
1539        // Capture the layout state.
1540
XMLMemento memento = XMLMemento.createWriteRoot("perspective");//$NON-NLS-1$
1541
IStatus status = saveState(memento, realDesc, false);
1542        if (status.getSeverity() == IStatus.ERROR) {
1543            ErrorDialog.openError((Shell) null, WorkbenchMessages.Perspective_problemSavingTitle,
1544                    WorkbenchMessages.Perspective_problemSavingMessage,
1545                    status);
1546            return;
1547        }
1548        //save it to the preference store
1549
try {
1550            perspRegistry.saveCustomPersp(realDesc, memento);
1551            descriptor = realDesc;
1552        } catch (IOException JavaDoc e) {
1553            perspRegistry.deletePerspective(realDesc);
1554            MessageDialog.openError((Shell) null, WorkbenchMessages.Perspective_problemSavingTitle,
1555                    WorkbenchMessages.Perspective_problemSavingMessage);
1556        }
1557    }
1558
1559    /**
1560     * Save the layout.
1561     */

1562    public IStatus saveState(IMemento memento) {
1563        MultiStatus result = new MultiStatus(
1564                PlatformUI.PLUGIN_ID,
1565                IStatus.OK,
1566                WorkbenchMessages.Perspective_problemsSavingPerspective, null);
1567
1568        result.merge(saveState(memento, descriptor, true));
1569
1570        return result;
1571    }
1572
1573    /**
1574     * Save the layout.
1575     */

1576    private IStatus saveState(IMemento memento, PerspectiveDescriptor p,
1577            boolean saveInnerViewState) {
1578        MultiStatus result = new MultiStatus(
1579                PlatformUI.PLUGIN_ID,
1580                IStatus.OK,
1581                WorkbenchMessages.Perspective_problemsSavingPerspective, null);
1582
1583        if (this.memento != null) {
1584            memento.putMemento(this.memento);
1585            return result;
1586        }
1587
1588        // Save the version number.
1589
memento.putString(IWorkbenchConstants.TAG_VERSION, VERSION_STRING);
1590        result.add(p.saveState(memento));
1591        if (!saveInnerViewState) {
1592            Rectangle bounds = page.getWorkbenchWindow().getShell().getBounds();
1593            IMemento boundsMem = memento
1594                    .createChild(IWorkbenchConstants.TAG_WINDOW);
1595            boundsMem.putInteger(IWorkbenchConstants.TAG_X, bounds.x);
1596            boundsMem.putInteger(IWorkbenchConstants.TAG_Y, bounds.y);
1597            boundsMem.putInteger(IWorkbenchConstants.TAG_HEIGHT, bounds.height);
1598            boundsMem.putInteger(IWorkbenchConstants.TAG_WIDTH, bounds.width);
1599        }
1600
1601
1602        // Save the "always on" action sets.
1603
Iterator JavaDoc itr = alwaysOnActionSets.iterator();
1604        while (itr.hasNext()) {
1605            IActionSetDescriptor desc = (IActionSetDescriptor) itr.next();
1606            IMemento child = memento
1607                    .createChild(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET);
1608            child.putString(IWorkbenchConstants.TAG_ID, desc.getId());
1609        }
1610
1611        // Save the "always off" action sets.
1612
itr = alwaysOffActionSets.iterator();
1613        while (itr.hasNext()) {
1614            IActionSetDescriptor desc = (IActionSetDescriptor) itr.next();
1615            IMemento child = memento
1616                    .createChild(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET);
1617            child.putString(IWorkbenchConstants.TAG_ID, desc.getId());
1618        }
1619
1620        // Save "show view actions"
1621
itr = showViewShortcuts.iterator();
1622        while (itr.hasNext()) {
1623            String JavaDoc str = (String JavaDoc) itr.next();
1624            IMemento child = memento
1625                    .createChild(IWorkbenchConstants.TAG_SHOW_VIEW_ACTION);
1626            child.putString(IWorkbenchConstants.TAG_ID, str);
1627        }
1628
1629        // Save "show in times"
1630
itr = showInTimes.keySet().iterator();
1631        while (itr.hasNext()) {
1632            String JavaDoc id = (String JavaDoc) itr.next();
1633            Long JavaDoc time = (Long JavaDoc) showInTimes.get(id);
1634            IMemento child = memento
1635                    .createChild(IWorkbenchConstants.TAG_SHOW_IN_TIME);
1636            child.putString(IWorkbenchConstants.TAG_ID, id);
1637            child.putString(IWorkbenchConstants.TAG_TIME, time.toString());
1638        }
1639
1640        // Save "new wizard actions".
1641
itr = newWizardShortcuts.iterator();
1642        while (itr.hasNext()) {
1643            String JavaDoc str = (String JavaDoc) itr.next();
1644            IMemento child = memento
1645                    .createChild(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION);
1646            child.putString(IWorkbenchConstants.TAG_ID, str);
1647        }
1648
1649        // Save "perspective actions".
1650
itr = perspectiveShortcuts.iterator();
1651        while (itr.hasNext()) {
1652            String JavaDoc str = (String JavaDoc) itr.next();
1653            IMemento child = memento
1654                    .createChild(IWorkbenchConstants.TAG_PERSPECTIVE_ACTION);
1655            child.putString(IWorkbenchConstants.TAG_ID, str);
1656        }
1657
1658        // Get visible views.
1659
List JavaDoc viewPanes = new ArrayList JavaDoc(5);
1660        presentation.collectViewPanes(viewPanes);
1661
1662        // Save the views.
1663
itr = viewPanes.iterator();
1664        int errors = 0;
1665        while (itr.hasNext()) {
1666            ViewPane pane = (ViewPane) itr.next();
1667            IViewReference ref = pane.getViewReference();
1668            IMemento viewMemento = memento
1669                    .createChild(IWorkbenchConstants.TAG_VIEW);
1670            viewMemento.putString(IWorkbenchConstants.TAG_ID, ViewFactory
1671                    .getKey(ref));
1672        }
1673
1674        // save all fastview state
1675
if (fastViewManager != null)
1676            fastViewManager.saveState(memento);
1677        
1678        // Save the view layout recs.
1679
for (Iterator JavaDoc i = mapIDtoViewLayoutRec.keySet().iterator(); i.hasNext();) {
1680            String JavaDoc compoundId = (String JavaDoc) i.next();
1681            ViewLayoutRec rec = (ViewLayoutRec) mapIDtoViewLayoutRec
1682                    .get(compoundId);
1683            if (rec != null
1684                    && (!rec.isCloseable || !rec.isMoveable || rec.isStandalone)) {
1685                IMemento layoutMemento = memento
1686                        .createChild(IWorkbenchConstants.TAG_VIEW_LAYOUT_REC);
1687                layoutMemento.putString(IWorkbenchConstants.TAG_ID, compoundId);
1688                if (!rec.isCloseable) {
1689                    layoutMemento.putString(IWorkbenchConstants.TAG_CLOSEABLE,
1690                            IWorkbenchConstants.FALSE);
1691                }
1692                if (!rec.isMoveable) {
1693                    layoutMemento.putString(IWorkbenchConstants.TAG_MOVEABLE,
1694                            IWorkbenchConstants.FALSE);
1695                }
1696                if (rec.isStandalone) {
1697                    layoutMemento.putString(IWorkbenchConstants.TAG_STANDALONE,
1698                            IWorkbenchConstants.TRUE);
1699                    layoutMemento.putString(IWorkbenchConstants.TAG_SHOW_TITLE,
1700                            String.valueOf(rec.showTitle));
1701                }
1702            }
1703        }
1704
1705        if (errors > 0) {
1706            String JavaDoc message = WorkbenchMessages.Perspective_multipleErrors;
1707            if (errors == 1) {
1708                message = WorkbenchMessages.Perspective_oneError;
1709            }
1710            MessageDialog.openError(null,
1711                    WorkbenchMessages.Error, message);
1712        }
1713
1714        // Save the layout.
1715
IMemento childMem = memento.createChild(IWorkbenchConstants.TAG_LAYOUT);
1716        result.add(presentation.saveState(childMem));
1717
1718        // Save the editor visibility state
1719
if (isEditorAreaVisible()) {
1720            memento.putInteger(IWorkbenchConstants.TAG_AREA_VISIBLE, 1);
1721        } else {
1722            memento.putInteger(IWorkbenchConstants.TAG_AREA_VISIBLE, 0);
1723        }
1724
1725        // Save the trim state of the editor area if using the new min/max
1726
IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
1727        boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX);
1728        if (useNewMinMax) {
1729            int trimState = editorAreaState;
1730            trimState |= editorAreaRestoreOnUnzoom ? 4 : 0;
1731            memento.putInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE, trimState);
1732        }
1733        
1734        // Save the fixed state
1735
if (fixed) {
1736            memento.putInteger(IWorkbenchConstants.TAG_FIXED, 1);
1737        } else {
1738            memento.putInteger(IWorkbenchConstants.TAG_FIXED, 0);
1739        }
1740
1741        return result;
1742    }
1743    
1744    public void turnOnActionSets(IActionSetDescriptor[] newArray) {
1745        for (int i = 0; i < newArray.length; i++) {
1746            IActionSetDescriptor descriptor = newArray[i];
1747            
1748            addAlwaysOn(descriptor);
1749        }
1750    }
1751    
1752    public void turnOffActionSets(IActionSetDescriptor[] toDisable) {
1753        for (int i = 0; i < toDisable.length; i++) {
1754            IActionSetDescriptor descriptor = toDisable[i];
1755            
1756            turnOffActionSet(descriptor);
1757        }
1758    }
1759
1760    public void turnOffActionSet(IActionSetDescriptor toDisable) {
1761        addAlwaysOff(toDisable);
1762    }
1763    
1764    /**
1765     * Return the active fast view or null if there are no
1766     * fast views or if there are all minimized.
1767     */

1768    public IViewReference getActiveFastView() {
1769        return activeFastView;
1770    }
1771
1772    /**
1773     * Sets the active fast view. If a different fast view is already open,
1774     * it shrinks equally <code>steps</code> times before disappearing
1775     * completely. Then, <code>view</code> becomes active and is shown.
1776     */

1777    /*package*/void setActiveFastView(IViewReference ref, int steps) {
1778        if (activeFastView == ref) {
1779            return;
1780        }
1781
1782        if (activeFastView != null) {
1783            ViewPane pane = getPane(activeFastView);
1784            if (pane != null) {
1785                if (pane.isZoomed()) {
1786                    presentation.zoomOut();
1787                }
1788                hideFastView(activeFastView, steps);
1789            }
1790        }
1791        activeFastView = ref;
1792        try {
1793            if (activeFastView != null) {
1794                if (!showFastView(activeFastView)) {
1795                    activeFastView = null;
1796                }
1797            }
1798        } catch (RuntimeException JavaDoc e) {
1799            activeFastView = null;
1800        }
1801    }
1802
1803    /**
1804     * Sets the active fast view.
1805     */

1806    /*package*/void setActiveFastView(IViewReference ref) {
1807        setActiveFastView(ref, FASTVIEW_HIDE_STEPS);
1808    }
1809
1810    /**
1811     * Sets the visibility of all fast view pins.
1812     */

1813    private void setAllPinsVisible(boolean visible) {
1814        if (fastViewManager == null)
1815            return;
1816        
1817        Iterator JavaDoc iter = fastViewManager.getFastViews(null).iterator();
1818        while (iter.hasNext()) {
1819            ViewPane pane = getPane((IViewReference) iter.next());
1820            if (pane != null) {
1821                pane.setFast(visible);
1822            }
1823        }
1824    }
1825
1826    /**
1827     * Sets the selection for the shortcut bar icon representing the givevn fast view.
1828     */

1829    private void setFastViewIconSelection(IViewReference ref, boolean selected) {
1830        if (fastViewManager == null)
1831            return;
1832        
1833        fastViewManager.setFastViewIconSelection(ref, selected);
1834    }
1835
1836    /**
1837     * Sets the new wizard actions for the page.
1838     * This is List of Strings.
1839     */

1840    public void setNewWizardActionIds(ArrayList JavaDoc newList) {
1841        newWizardShortcuts = newList;
1842    }
1843
1844    /**
1845     * Sets the perspective actions for this page.
1846     * This is List of Strings.
1847     */

1848    public void setPerspectiveActionIds(ArrayList JavaDoc list) {
1849        perspectiveShortcuts = list;
1850    }
1851
1852    /**
1853     * Sets the ids of the parts to list in the Show In... prompter.
1854     * This is a List of Strings.
1855     */

1856    public void setShowInPartIds(ArrayList JavaDoc list) {
1857        showInPartIds = list;
1858    }
1859
1860    /**
1861     * Sets the ids of the views to list in the Show View shortcuts.
1862     * This is a List of Strings.
1863     */

1864    public void setShowViewActionIds(ArrayList JavaDoc list) {
1865        showViewShortcuts = list;
1866    }
1867
1868
1869    /**
1870     * Show the editor area if not visible
1871     */

1872    protected void showEditorArea() {
1873        if (isEditorAreaVisible()) {
1874            return;
1875        }
1876
1877        editorHidden = false;
1878        
1879        // Show the editor in the appropriate location
1880
if (useNewMinMax(this)) {
1881            boolean isMinimized = editorAreaState == IStackPresentationSite.STATE_MINIMIZED;
1882            if (!isMinimized) {
1883                // If the editor area is going to show then we have to restore
1884
if (getPresentation().getMaximizedStack() != null)
1885                    getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED);
1886                
1887                showEditorAreaLocal();
1888            }
1889            else
1890                setEditorAreaTrimVisibility(true);
1891        }
1892        else {
1893            showEditorAreaLocal();
1894        }
1895    }
1896
1897    /**
1898     * Show the editor area if not visible
1899     */

1900    protected void showEditorAreaLocal() {
1901        if (editorHolder == null || editorHidden) {
1902            return;
1903        }
1904
1905        // Replace the part holder with the editor area.
1906
presentation.getLayout().replace(editorHolder, editorArea);
1907        editorHolder = null;
1908    }
1909
1910    private EditorAreaTrimToolBar getEditorAreaTrim(boolean createIfNecessary) {
1911        WorkbenchWindow wbw = (WorkbenchWindow) page.getWorkbenchWindow();
1912        ITrimManager tbm = wbw.getTrimManager();
1913        if (tbm == null)
1914            return null;
1915
1916        // Create if necesary
1917
EditorAreaTrimToolBar editorAreaTrim = (EditorAreaTrimToolBar) tbm.getTrim(IPageLayout.ID_EDITOR_AREA);
1918        if (editorAreaTrim == null && createIfNecessary) {
1919            int suggestedSide = SWT.RIGHT;
1920            int cachedSide = ((TrimLayout)tbm).getPreferredArea(IPageLayout.ID_EDITOR_AREA);
1921            if (cachedSide != -1)
1922                suggestedSide = cachedSide;
1923            
1924            IWindowTrim beforeMe = ((TrimLayout)tbm).getPreferredLocation(IPageLayout.ID_EDITOR_AREA);
1925            
1926            // Gain access to the trim manager
1927
editorAreaTrim = new EditorAreaTrimToolBar(wbw, editorArea);
1928            editorAreaTrim.dock(suggestedSide);
1929            tbm.addTrim(suggestedSide, editorAreaTrim, beforeMe);
1930        }
1931        
1932        return editorAreaTrim;
1933    }
1934    
1935    public void setEditorAreaState(int newState) {
1936        if (newState == editorAreaState)
1937            return;
1938        
1939        editorAreaState = newState;
1940        
1941        // reset the restore flag if we're not minimized
1942
if (newState != IStackPresentationSite.STATE_MINIMIZED)
1943            editorAreaRestoreOnUnzoom = false;
1944        
1945        refreshEditorAreaVisibility();
1946    }
1947    
1948    public int getEditorAreaState() {
1949        return editorAreaState;
1950    }
1951    
1952    /**
1953     *
1954     */

1955    public void refreshEditorAreaVisibility() {
1956        // Nothing shows up if the editor area isn't visible at all
1957
if (editorHidden) {
1958            hideEditorAreaLocal();
1959            setEditorAreaTrimVisibility(false);
1960            return;
1961        }
1962        
1963        EditorStack editorStack = ((EditorSashContainer) editorArea).getUpperRightEditorStack(null);
1964        if (editorStack == null)
1965            return;
1966        
1967        // Whatever we're doing, make the current editor stack match it
1968
editorStack.setStateLocal(editorAreaState);
1969        
1970        // If it's minimized then it's in the trim
1971
if (editorAreaState == IStackPresentationSite.STATE_MINIMIZED) {
1972            // Hide the editor area and show its trim
1973
hideEditorAreaLocal();
1974            setEditorAreaTrimVisibility(true);
1975        }
1976        else {
1977            // Show the editor area and hide its trim
1978
setEditorAreaTrimVisibility(false);
1979            showEditorAreaLocal();
1980            
1981            if (editorAreaState == IStackPresentationSite.STATE_MAXIMIZED)
1982                getPresentation().setMaximizedStack(editorStack);
1983        }
1984    }
1985
1986    protected EditorAreaTrimToolBar setEditorAreaTrimVisibility(boolean visible) {
1987        WorkbenchWindow wbw = (WorkbenchWindow) page.getWorkbenchWindow();
1988        ITrimManager tbm = wbw.getTrimManager();
1989        if (tbm == null)
1990            return null;
1991        
1992        // Only create the trim element if it's going to be visible
1993
EditorAreaTrimToolBar editorAreaTrim = getEditorAreaTrim(visible);
1994        if (editorAreaTrim == null)
1995            return null;
1996        
1997        tbm.setTrimVisible(editorAreaTrim, visible);
1998        tbm.forceLayout();
1999        
2000        return editorAreaTrim;
2001    }
2002    
2003    /**
2004     * Shows a fast view.
2005     * @return whether the view was successfully shown
2006     */

2007    boolean showFastView(IViewReference ref) {
2008        if (fastViewManager == null)
2009            return false;
2010        
2011        // Make sure the part is restored.
2012
IWorkbenchPart refPart = ref.getPart(true);
2013        if (refPart == null) {
2014            return false;
2015        }
2016
2017        ViewPane pane = getPane(ref);
2018        if (pane == null) {
2019            return false;
2020        }
2021
2022        saveFastViewWidthRatio();
2023
2024        // Special check to ensure that a 'minimized' intro view shows
2025
// as 'standby'
2026
if (ref.getId().equals("org.eclipse.ui.internal.introview")) { //$NON-NLS-1$
2027
if (refPart instanceof ViewIntroAdapterPart) {
2028                ((ViewIntroAdapterPart)refPart).setStandby(true);
2029            }
2030        }
2031        
2032        // Determine the display orientation
2033
int side = fastViewManager.getViewSide(ref);
2034        fastViewPane.showView(getClientComposite(), pane, side,
2035                getFastViewWidthRatio(ref));
2036
2037        setFastViewIconSelection(ref, true);
2038
2039        return true;
2040    }
2041
2042    private void saveFastViewWidthRatio() {
2043        ViewPane pane = fastViewPane.getCurrentPane();
2044        if (pane != null) {
2045            ViewLayoutRec rec = getViewLayoutRec(pane.getViewReference(), true);
2046            rec.fastViewWidthRatio = fastViewPane.getCurrentRatio();
2047        }
2048    }
2049
2050    /**
2051     * Resolves a view's id into its reference, creating the
2052     * view if necessary.
2053     *
2054     * @param viewId The primary id of the view (must not be
2055     * <code>null</code>
2056     * @param secondaryId The secondary id of a multiple-instance view
2057     * (may be <code>null</code>).
2058     *
2059     * @return The reference to the specified view. This may be null if the
2060     * view fails to create (i.e. thrown a PartInitException)
2061     */

2062    public IViewReference getViewReference(String JavaDoc viewId, String JavaDoc secondaryId) {
2063        IViewReference ref = page.findViewReference(viewId, secondaryId);
2064        if (ref == null) {
2065            ViewFactory factory = getViewFactory();
2066            try {
2067                ref = factory.createView(viewId, secondaryId);
2068            } catch (PartInitException e) {
2069                IStatus status = StatusUtil.newStatus(IStatus.ERROR,
2070                        e.getMessage() == null ? "" : e.getMessage(), //$NON-NLS-1$
2071
e);
2072                StatusUtil.handleStatus(status, "Failed to create view: id=" + viewId, //$NON-NLS-1$
2073
StatusManager.LOG);
2074            }
2075        }
2076        return ref;
2077    }
2078    
2079    /**
2080     * Shows the view with the given id and secondary id.
2081     */

2082    public IViewPart showView(String JavaDoc viewId, String JavaDoc secondaryId)
2083            throws PartInitException {
2084        ViewFactory factory = getViewFactory();
2085        IViewReference ref = factory.createView(viewId, secondaryId);
2086        IViewPart part = (IViewPart) ref.getPart(true);
2087        if (part == null) {
2088            throw new PartInitException(NLS.bind(WorkbenchMessages.ViewFactory_couldNotCreate, ref.getId()));
2089        }
2090        ViewSite site = (ViewSite) part.getSite();
2091        ViewPane pane = (ViewPane) site.getPane();
2092
2093        IPreferenceStore store = WorkbenchPlugin.getDefault()
2094                .getPreferenceStore();
2095        int openViewMode = store.getInt(IPreferenceConstants.OPEN_VIEW_MODE);
2096
2097        if (openViewMode == IPreferenceConstants.OVM_FAST &&
2098            fastViewManager != null) {
2099            fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, true);
2100            setActiveFastView(ref);
2101        } else if (openViewMode == IPreferenceConstants.OVM_FLOAT
2102                && presentation.canDetach()) {
2103            presentation.addDetachedPart(pane);
2104        } else {
2105            if (useNewMinMax(this)) {
2106                // Is this view going to show in the trim?
2107
LayoutPart vPart = presentation.findPart(viewId, secondaryId);
2108
2109                // Determine if there is a trim stack that should get the view
2110
String JavaDoc trimId = null;
2111                
2112                // If we can locate the correct trim stack then do so
2113
if (vPart != null) {
2114                    String JavaDoc id = null;
2115                    ILayoutContainer container = vPart.getContainer();
2116                    if (container instanceof ContainerPlaceholder)
2117                        id = ((ContainerPlaceholder)container).getID();
2118                    else if (container instanceof ViewStack)
2119                        id = ((ViewStack)container).getID();
2120                    
2121                    // Is this place-holder in the trim?
2122
if (id != null && fastViewManager.getFastViews(id).size() > 0) {
2123                        trimId = id;
2124                    }
2125                }
2126                
2127                // No explicit trim found; If we're maximized then we either have to find an
2128
// arbitrary stack...
2129
if (trimId == null && presentation.getMaximizedStack() != null) {
2130                    if (vPart == null) {
2131                        ViewStackTrimToolBar blTrimStack = fastViewManager.getBottomRightTrimStack();
2132                        if (blTrimStack != null) {
2133                            // OK, we've found a trim stack to add it to...
2134
trimId = blTrimStack.getId();
2135                            
2136                            // Since there was no placeholder we have to add one
2137
LayoutPart blPart = presentation.findPart(trimId, null);
2138                            if (blPart instanceof ContainerPlaceholder) {
2139                                ContainerPlaceholder cph = (ContainerPlaceholder) blPart;
2140                                if (cph.getRealContainer() instanceof ViewStack) {
2141                                    ViewStack vs = (ViewStack) cph.getRealContainer();
2142                                    
2143                                    // Create a 'compound' id if this is a multi-instance part
2144
String JavaDoc compoundId = ref.getId();
2145                                    if (ref.getSecondaryId() != null)
2146                                        compoundId = compoundId + ':' + ref.getSecondaryId();
2147
2148                                    // Add the new placeholder
2149
vs.add(new PartPlaceholder(compoundId));
2150                                }
2151                            }
2152                        }
2153                    }
2154                }
2155                
2156                // If we have a trim stack located then add the view to it
2157
if (trimId != null) {
2158                    fastViewManager.addViewReference(trimId, -1, ref, true);
2159                }
2160                else {
2161                    boolean inMaximizedStack = vPart != null && vPart.getContainer() == presentation.getMaximizedStack();
2162
2163                    // Do the default behavior
2164
presentation.addPart(pane);
2165                    
2166                    // Now, if we're maximized then we have to minimize the new stack
2167
if (presentation.getMaximizedStack() != null && !inMaximizedStack) {
2168                        vPart = presentation.findPart(viewId, secondaryId);
2169                        if (vPart != null && vPart.getContainer() instanceof ViewStack) {
2170                            ViewStack vs = (ViewStack)vPart.getContainer();
2171                            vs.setState(IStackPresentationSite.STATE_MINIMIZED);
2172                            
2173                            // setting the state to minimized will create the trim toolbar
2174
// so we don't need a null pointer check here...
2175
fastViewManager.getViewStackTrimToolbar(vs.getID()).setRestoreOnUnzoom(true);
2176                        }
2177                    }
2178                }
2179            }
2180            else {
2181                presentation.addPart(pane);
2182            }
2183        }
2184        return part;
2185    }
2186
2187    /**
2188     * Toggles the visibility of a fast view. If the view is active it
2189     * is deactivated. Otherwise, it is activated.
2190     */

2191    public void toggleFastView(IViewReference ref) {
2192        if (ref == activeFastView) {
2193            setActiveFastView(null);
2194        } else {
2195            setActiveFastView(ref);
2196        }
2197    }
2198
2199    /**
2200     * Returns the old part reference.
2201     * Returns null if there was no previously active part.
2202     *
2203     * @return the old part reference or <code>null</code>
2204     */

2205    public IWorkbenchPartReference getOldPartRef() {
2206        return oldPartRef;
2207    }
2208
2209    /**
2210     * Sets the old part reference.
2211     *
2212     * @param oldPartRef The old part reference to set, or <code>null</code>
2213     */

2214    public void setOldPartRef(IWorkbenchPartReference oldPartRef) {
2215        this.oldPartRef = oldPartRef;
2216    }
2217
2218    //for dynamic UI
2219
/* package */void addActionSet(IActionSetDescriptor newDesc) {
2220        IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class);
2221        try {
2222            service.activateContext(ContextAuthority.DEFER_EVENTS);
2223            for (int i = 0; i < alwaysOnActionSets.size(); i++) {
2224                IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOnActionSets
2225                        .get(i);
2226                if (desc.getId().equals(newDesc.getId())) {
2227                    removeAlwaysOn(desc);
2228                    removeAlwaysOff(desc);
2229                    break;
2230                }
2231            }
2232            addAlwaysOn(newDesc);
2233        } finally {
2234            service.activateContext(ContextAuthority.SEND_EVENTS);
2235        }
2236    }
2237
2238    // for dynamic UI
2239
/* package */void removeActionSet(String JavaDoc id) {
2240        IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class);
2241        try {
2242            service.activateContext(ContextAuthority.DEFER_EVENTS);
2243            for (int i = 0; i < alwaysOnActionSets.size(); i++) {
2244                IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOnActionSets
2245                        .get(i);
2246                if (desc.getId().equals(id)) {
2247                    removeAlwaysOn(desc);
2248                    break;
2249                }
2250            }
2251
2252            for (int i = 0; i < alwaysOffActionSets.size(); i++) {
2253                IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOffActionSets
2254                        .get(i);
2255                if (desc.getId().equals(id)) {
2256                    removeAlwaysOff(desc);
2257                    break;
2258                }
2259            }
2260        } finally {
2261            service.activateContext(ContextAuthority.SEND_EVENTS);
2262        }
2263    }
2264    
2265    void removeActionSet(IActionSetDescriptor toRemove) {
2266        removeAlwaysOn(toRemove);
2267        removeAlwaysOff(toRemove);
2268    }
2269
2270    public void setFastViewState(int newState) {
2271        fastViewPane.setState(newState);
2272    }
2273    
2274    public int getFastViewState() {
2275        return fastViewPane.getState();
2276    }
2277
2278    /**
2279     * Returns whether the given view is closeable in this perspective.
2280     *
2281     * @since 3.0
2282     */

2283    public boolean isCloseable(IViewReference reference) {
2284        ViewLayoutRec rec = getViewLayoutRec(reference, false);
2285        if (rec != null) {
2286            return rec.isCloseable;
2287        }
2288        return true;
2289    }
2290
2291    /**
2292     * Returns whether the given view is moveable in this perspective.
2293     *
2294     * @since 3.0
2295     */

2296    public boolean isMoveable(IViewReference reference) {
2297        ViewLayoutRec rec = getViewLayoutRec(reference, false);
2298        if (rec != null) {
2299            return rec.isMoveable;
2300        }
2301        return true;
2302    }
2303
2304    /**
2305     * Writes a description of the layout to the given string buffer.
2306     * This is used for drag-drop test suites to determine if two layouts are the
2307     * same. Like a hash code, the description should compare as equal iff the
2308     * layouts are the same. However, it should be user-readable in order to
2309     * help debug failed tests. Although these are english readable strings,
2310     * they should not be translated or equality tests will fail.
2311     * <p>
2312     * This is only intended for use by test suites.
2313     * </p>
2314     *
2315     * @param buf
2316     */

2317    public void describeLayout(StringBuffer JavaDoc buf) {
2318        IViewReference[] fastViews = getFastViews();
2319
2320        if (fastViews.length != 0) {
2321            buf.append("fastviews ("); //$NON-NLS-1$
2322
for (int idx = 0; idx < fastViews.length; idx++) {
2323                IViewReference ref = fastViews[idx];
2324
2325                if (idx > 0) {
2326                    buf.append(", "); //$NON-NLS-1$
2327
}
2328
2329                buf.append(ref.getPartName());
2330            }
2331            buf.append("), "); //$NON-NLS-1$
2332
}
2333
2334        getPresentation().describeLayout(buf);
2335    }
2336
2337    /**
2338     * Sanity-checks the LayoutParts in this perspective. Throws an Assertation exception
2339     * if an object's internal state is invalid.
2340     */

2341    public void testInvariants() {
2342        getPresentation().getLayout().testInvariants();
2343    }
2344
2345    public IActionSetDescriptor[] getAlwaysOnActionSets() {
2346        return (IActionSetDescriptor[]) alwaysOnActionSets.toArray(new IActionSetDescriptor[alwaysOnActionSets.size()]);
2347    }
2348    
2349    public IActionSetDescriptor[] getAlwaysOffActionSets() {
2350        return (IActionSetDescriptor[]) alwaysOffActionSets.toArray(new IActionSetDescriptor[alwaysOffActionSets.size()]);
2351    }
2352
2353    /* package */ FastViewPane getFastViewPane() {
2354        return fastViewPane;
2355    }
2356
2357
2358    /**
2359     * Restores a part in the trim to the actual layout
2360     * @param part The part to restore
2361     */

2362    public void restoreTrimPart(LayoutPart part) {
2363        if (fastViewManager == null)
2364            return;
2365        
2366        // Remove any current fastview
2367
setActiveFastView(null);
2368
2369        // Set the part's state to place it back in the layout
2370
if (part instanceof ViewStack) {
2371            ViewStack vs = (ViewStack) part;
2372            fastViewManager.restoreToPresentation(vs.getID());
2373        }
2374
2375        if (part == editorArea) {
2376            setEditorAreaState(IStackPresentationSite.STATE_RESTORED);
2377            editorAreaRestoreOnUnzoom = false;
2378        }
2379    }
2380
2381    /**
2382     * Determine the correct side to initially dock a new
2383     * trim part on. We do this by checking its rect against
2384     * the editor area.
2385     *
2386     * @param stackBounds The bounds of the stack we want to create trim for
2387     * @return the SWT side to dock the trim element on
2388     */

2389    public int calcStackSide(Rectangle stackBounds) {
2390        // Where is the stack in relation to the EditorArea?
2391
Rectangle editorAreaBounds = editorArea.getBounds();
2392        
2393        // Is this the Editor Area
2394
if (editorAreaBounds.equals(stackBounds))
2395            return SWT.TOP;
2396        
2397        Point stackCenter = Geometry.centerPoint(stackBounds);
2398        Point editorAreaCenter = Geometry.centerPoint(editorAreaBounds);
2399
2400        int dx = editorAreaCenter.x - stackCenter.x;
2401        int dy = editorAreaCenter.y - stackCenter.y;
2402
2403        if (Math.abs(dx) > Math.abs(dy)) {
2404            return (dx > 0) ? SWT.LEFT : SWT.RIGHT;
2405        }
2406
2407        if (dy > 0) {
2408            return (dx > 0) ? SWT.LEFT : SWT.RIGHT;
2409        }
2410        
2411        return SWT.BOTTOM;
2412    }
2413
2414    /**
2415     * Restore any parts that are showing in the trim as
2416     * a result of a 'zoom' operation
2417     */

2418    public void restoreZoomedParts() {
2419        if (fastViewManager == null)
2420            return;
2421        
2422        // Remove any current fastview
2423
setActiveFastView(null);
2424            
2425        // have the layout restore the parts
2426
fastViewManager.restoreZoomedViewStacks();
2427        
2428        if (editorAreaRestoreOnUnzoom) {
2429            restoreTrimPart(editorArea);
2430        }
2431    }
2432
2433    /**
2434     * @return Returns the fastViewManager.
2435     */

2436    public FastViewManager getFastViewManager() {
2437        return fastViewManager;
2438    }
2439
2440    /**
2441     * Sets the restore on unzoom state for the editor area
2442     * @param restore the new state
2443     */

2444    public void setEditorAreaRestoreOnUnzoom(boolean restore) {
2445        editorAreaRestoreOnUnzoom = restore;
2446    }
2447
2448    /**
2449     * @return the restore on unzoom state
2450     */

2451    public boolean getEditorAreaRestoreOnUnzoom() {
2452        return editorAreaRestoreOnUnzoom;
2453    }
2454
2455    /**
2456     * Used to restrict the use of the new min/max behavior to envoronments
2457     * in which it has a chance of working...
2458     *
2459     * @param activePerspective We pass this in as an arg so others won't have
2460     * to check it for 'null' (which is one of the failure cases)
2461     *
2462     */

2463    public static boolean useNewMinMax(Perspective activePerspective) {
2464        // We need to have an active perspective
2465
if (activePerspective == null)
2466            return false;
2467        
2468        // We need to have a trim manager (if we don't then we
2469
// don't create a FastViewManager because it'd be useless)
2470
if (activePerspective.getFastViewManager() == null)
2471            return false;
2472        
2473        // Make sure we don't NPE anyplace
2474
WorkbenchWindow wbw = (WorkbenchWindow) activePerspective.page.getWorkbenchWindow();
2475        if (wbw == null)
2476            return false;
2477        
2478        WorkbenchWindowConfigurer configurer = wbw.getWindowConfigurer();
2479        if (configurer == null)
2480            return false;
2481        
2482        AbstractPresentationFactory factory = configurer.getPresentationFactory();
2483        if (factory == null)
2484            return false;
2485        
2486        // Ok, we should be good to go, return the pref
2487
IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
2488        boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX);
2489        return useNewMinMax;
2490    }
2491}
2492
Popular Tags