KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > editor > PDEFormEditor


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 package org.eclipse.pde.internal.ui.editor;
12 import java.io.File JavaDoc;
13 import java.io.IOException JavaDoc;
14 import java.io.PrintWriter JavaDoc;
15 import java.io.StringWriter JavaDoc;
16 import java.util.ArrayList JavaDoc;
17
18 import org.eclipse.core.filesystem.EFS;
19 import org.eclipse.core.filesystem.IFileStore;
20 import org.eclipse.core.resources.IFile;
21 import org.eclipse.core.resources.IMarker;
22 import org.eclipse.core.resources.IProject;
23 import org.eclipse.core.resources.IResource;
24 import org.eclipse.core.runtime.CoreException;
25 import org.eclipse.core.runtime.IProgressMonitor;
26 import org.eclipse.core.runtime.NullProgressMonitor;
27 import org.eclipse.jface.action.IAction;
28 import org.eclipse.jface.action.IMenuListener;
29 import org.eclipse.jface.action.IMenuManager;
30 import org.eclipse.jface.action.IStatusLineManager;
31 import org.eclipse.jface.action.MenuManager;
32 import org.eclipse.jface.dialogs.IDialogSettings;
33 import org.eclipse.jface.text.IDocument;
34 import org.eclipse.jface.text.ITextSelection;
35 import org.eclipse.jface.text.source.IAnnotationModel;
36 import org.eclipse.jface.viewers.IPostSelectionProvider;
37 import org.eclipse.jface.viewers.ISelection;
38 import org.eclipse.jface.viewers.ISelectionChangedListener;
39 import org.eclipse.jface.viewers.ISelectionProvider;
40 import org.eclipse.jface.viewers.IStructuredSelection;
41 import org.eclipse.jface.viewers.SelectionChangedEvent;
42 import org.eclipse.pde.core.IBaseModel;
43 import org.eclipse.pde.core.IWritable;
44 import org.eclipse.pde.internal.core.IWorkspaceModel;
45 import org.eclipse.pde.internal.core.plugin.IWritableDelimiter;
46 import org.eclipse.pde.internal.core.util.XMLComponentRegistry;
47 import org.eclipse.pde.internal.ui.IPDEUIConstants;
48 import org.eclipse.pde.internal.ui.PDEPlugin;
49 import org.eclipse.pde.internal.ui.PDEUIMessages;
50 import org.eclipse.pde.internal.ui.editor.context.IInputContextListener;
51 import org.eclipse.pde.internal.ui.editor.context.InputContext;
52 import org.eclipse.pde.internal.ui.editor.context.InputContextManager;
53 import org.eclipse.pde.internal.ui.editor.plugin.MissingResourcePage;
54 import org.eclipse.pde.internal.ui.editor.plugin.OverviewPage;
55 import org.eclipse.pde.internal.ui.util.PDEModelUtility;
56 import org.eclipse.search.ui.text.ISearchEditorAccess;
57 import org.eclipse.search.ui.text.Match;
58 import org.eclipse.swt.dnd.Clipboard;
59 import org.eclipse.swt.dnd.TextTransfer;
60 import org.eclipse.swt.dnd.Transfer;
61 import org.eclipse.swt.widgets.Display;
62 import org.eclipse.swt.widgets.Menu;
63 import org.eclipse.ui.IEditorActionBarContributor;
64 import org.eclipse.ui.IEditorInput;
65 import org.eclipse.ui.IEditorPart;
66 import org.eclipse.ui.IEditorSite;
67 import org.eclipse.ui.IFileEditorInput;
68 import org.eclipse.ui.IStorageEditorInput;
69 import org.eclipse.ui.IURIEditorInput;
70 import org.eclipse.ui.IWorkbenchPart;
71 import org.eclipse.ui.PartInitException;
72 import org.eclipse.ui.actions.ActionFactory;
73 import org.eclipse.ui.forms.editor.FormEditor;
74 import org.eclipse.ui.forms.editor.IFormPage;
75 import org.eclipse.ui.forms.widgets.FormToolkit;
76 import org.eclipse.ui.ide.IDE;
77 import org.eclipse.ui.ide.IGotoMarker;
78 import org.eclipse.ui.part.MultiPageEditorPart;
79 import org.eclipse.ui.part.MultiPageEditorSite;
80 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
81
82 /**
83  * A simple multi-page form editor that uses Eclipse Forms support. Example
84  * plug-in is configured to create one instance of form colors that is shared
85  * between multiple editor instances.
86  */

87 public abstract class PDEFormEditor extends FormEditor
88         implements
89             IInputContextListener,
90             IGotoMarker, ISearchEditorAccess {
91     /**
92      * Updates the OutlinePage selection.
93      *
94      * @since 3.0
95      */

96     public class PDEFormEditorChangeListener implements
97             ISelectionChangedListener {
98
99         /**
100          * Installs this selection changed listener with the given selection
101          * provider. If the selection provider is a post selection provider,
102          * post selection changed events are the preferred choice, otherwise
103          * normal selection changed events are requested.
104          *
105          * @param selectionProvider
106          */

107         public void install(ISelectionProvider selectionProvider) {
108             if (selectionProvider == null) {
109                 return;
110             }
111
112             if (selectionProvider instanceof IPostSelectionProvider) {
113                 IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
114                 provider.addPostSelectionChangedListener(this);
115             } else {
116                 selectionProvider.addSelectionChangedListener(this);
117             }
118         }
119
120         /*
121          * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
122          */

123         public void selectionChanged(SelectionChangedEvent event) {
124             if (PDEPlugin.getDefault().getPreferenceStore().getBoolean(
125                     "ToggleLinkWithEditorAction.isChecked")) //$NON-NLS-1$
126
if (getFormOutline() != null) {
127                     getFormOutline().setSelection(event.getSelection());
128                 }
129         }
130
131         /**
132          * Removes this selection changed listener from the given selection
133          * provider.
134          *
135          * @param selectionProviderstyle
136          */

137         public void uninstall(ISelectionProvider selectionProvider) {
138             if (selectionProvider == null) {
139                 return;
140             }
141
142             if (selectionProvider instanceof IPostSelectionProvider) {
143                 IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
144                 provider.removePostSelectionChangedListener(this);
145             } else {
146                 selectionProvider.removeSelectionChangedListener(this);
147             }
148         }
149
150     }
151
152     private static final String JavaDoc F_DIALOG_EDITOR_SECTION_KEY = "pde-form-editor"; //$NON-NLS-1$
153

154     /**
155      * The editor selection changed listener.
156      *
157      * @since 3.0
158      */

159     private PDEFormEditorChangeListener fEditorSelectionChangedListener;
160     private Clipboard clipboard;
161     private Menu fContextMenu;
162     protected InputContextManager fInputContextManager;
163     private ISortableContentOutlinePage fFormOutline;
164     private PDEMultiPageContentOutline fContentOutline;
165     private String JavaDoc fLastActivePageId;
166     private boolean fLastDirtyState;
167     private boolean fError;
168
169     private static class PDEMultiPageEditorSite extends MultiPageEditorSite {
170         public PDEMultiPageEditorSite(MultiPageEditorPart multiPageEditor,
171                 IEditorPart editor) {
172             super(multiPageEditor, editor);
173         }
174         public IEditorActionBarContributor getActionBarContributor() {
175             PDEFormEditor editor = (PDEFormEditor) getMultiPageEditor();
176             PDEFormEditorContributor contributor = editor.getContributor();
177             return contributor.getSourceContributor();
178         }
179         
180         public IWorkbenchPart getPart() {
181             return getMultiPageEditor();
182         }
183     }
184
185     public PDEFormEditor() {
186         PDEPlugin.getDefault().getLabelProvider().connect(this);
187         XMLComponentRegistry.Instance().connect(this);
188         fInputContextManager = createInputContextManager();
189     }
190     
191     /**
192      * We must override nested site creation so that we properly pass the source
193      * editor contributor when asked.
194      */

195     protected IEditorSite createSite(IEditorPart editor) {
196         return new PDEMultiPageEditorSite(this, editor);
197     }
198     public IProject getCommonProject() {
199         return fInputContextManager.getCommonProject();
200     }
201     public IBaseModel getAggregateModel() {
202         if (fInputContextManager != null)
203             return fInputContextManager.getAggregateModel();
204         return null;
205     }
206     protected abstract InputContextManager createInputContextManager();
207     /**
208      * Tests whether this editor has a context with a provided id. The test can
209      * be used to check whether to add certain pages.
210      *
211      * @param contextId
212      * @return <code>true</code> if provided context is present,
213      * <code>false</code> otherwise.
214      */

215     public boolean hasInputContext(String JavaDoc contextId) {
216         return fInputContextManager.hasContext(contextId);
217     }
218     public InputContextManager getContextManager() {
219         return fInputContextManager;
220     }
221     protected void createInputContexts(InputContextManager contextManager) {
222         IEditorInput input = getEditorInput();
223         if (input instanceof IFileEditorInput) {
224             // resource - find the project
225
createResourceContexts(contextManager, (IFileEditorInput) input);
226         } else if (input instanceof SystemFileEditorInput) {
227             // system file - find the file system folder
228
createSystemFileContexts(contextManager,
229                     (SystemFileEditorInput) input);
230         } else if (input instanceof IStorageEditorInput) {
231             createStorageContexts(contextManager, (IStorageEditorInput) input);
232         } else if (input instanceof IURIEditorInput) {
233             IURIEditorInput uriEditorInput= (IURIEditorInput) input;
234             try {
235                 IFileStore store= EFS.getStore(uriEditorInput.getURI());
236                 if (!EFS.SCHEME_FILE.equals(store.getFileSystem().getScheme()))
237                     return;
238             } catch (CoreException e) {
239                 return;
240             }
241             File JavaDoc file = new File JavaDoc(uriEditorInput.getURI());
242             SystemFileEditorInput sinput = new SystemFileEditorInput(file);
243             createSystemFileContexts(contextManager, sinput);
244         }
245     }
246     protected abstract void createResourceContexts(
247             InputContextManager contexts, IFileEditorInput input);
248     protected abstract void createSystemFileContexts(
249             InputContextManager contexts, SystemFileEditorInput input);
250     protected abstract void createStorageContexts(InputContextManager contexts,
251             IStorageEditorInput input);
252     /*
253      * (non-Javadoc)
254      *
255      * @see org.eclipse.ui.forms.editor.FormEditor#createToolkit(org.eclipse.swt.widgets.Display)
256      */

257     protected FormToolkit createToolkit(Display display) {
258         // Create a toolkit that shares colors between editors.
259
return new FormToolkit(PDEPlugin.getDefault().getFormColors(display));
260     }
261     /*
262      * When subclassed, don't forget to call 'super'
263      */

264     protected void createPages() {
265         clipboard = new Clipboard(getContainer().getDisplay());
266         MenuManager manager = new MenuManager();
267         IMenuListener listener = new IMenuListener() {
268             public void menuAboutToShow(IMenuManager manager) {
269                 contextMenuAboutToShow(manager);
270             }
271         };
272         manager.setRemoveAllWhenShown(true);
273         manager.addMenuListener(listener);
274         fContextMenu = manager.createContextMenu(getContainer());
275         getContainer().setMenu(fContextMenu);
276         createInputContexts(fInputContextManager);
277         super.createPages();
278         fInputContextManager.addInputContextListener(this);
279         String JavaDoc pageToShow = computeInitialPageId();
280         if (pageToShow != null)
281             setActivePage(pageToShow);
282         updateTitle();
283         PDEModelUtility.connect(this);
284     }
285     
286     /* (non-Javadoc)
287      * @see org.eclipse.ui.forms.editor.FormEditor#pageChange(int)
288      */

289     protected void pageChange(int newPageIndex) {
290         super.pageChange(newPageIndex);
291         IFormPage page = getActivePageInstance();
292         updateContentOutline(page);
293         if (page != null) {
294             fLastActivePageId = page.getId();
295         }
296     }
297     
298     /* (non-Javadoc)
299      * @see org.eclipse.ui.part.MultiPageEditorPart#setFocus()
300      */

301     public void setFocus() {
302         super.setFocus();
303         IFormPage page = getActivePageInstance();
304         // Could be done on setActive in PDEFormPage;
305
// but setActive only handles page switches and not focus events
306
if ((page != null) &&
307                 (page instanceof PDEFormPage)) {
308             ((PDEFormPage)page).updateFormSelection();
309         }
310     }
311     
312     public Clipboard getClipboard() {
313         return clipboard;
314     }
315     protected void contextMenuAboutToShow(IMenuManager manager) {
316         PDEFormEditorContributor contributor = getContributor();
317         IFormPage page = getActivePageInstance();
318         if (page instanceof PDEFormPage)
319             ((PDEFormPage) page).contextMenuAboutToShow(manager);
320         if (contributor != null)
321             contributor.contextMenuAboutToShow(manager);
322     }
323     
324     public PDEFormEditorContributor getContributor() {
325         return (PDEFormEditorContributor) getEditorSite().getActionBarContributor();
326     }
327     
328     protected String JavaDoc computeInitialPageId() {
329         String JavaDoc firstPageId = null;
330         String JavaDoc storedFirstPageId = loadDefaultPage();
331         if (storedFirstPageId != null)
332             firstPageId = storedFirstPageId;
333         // Regardless what is the stored value,
334
// use source page if model is not valid
335
String JavaDoc invalidContextId = getFirstInvalidContextId();
336         if (invalidContextId != null)
337             return invalidContextId;
338         return firstPageId;
339     }
340
341     private String JavaDoc getFirstInvalidContextId() {
342         InputContext[] invalidContexts = fInputContextManager
343                 .getInvalidContexts();
344         if (invalidContexts.length == 0)
345             return null;
346         // If primary context is among the invalid ones, return that.
347
for (int i = 0; i < invalidContexts.length; i++) {
348             if (invalidContexts[i].isPrimary())
349                 return invalidContexts[i].getId();
350         }
351         // Return the first one
352
return invalidContexts[0].getId();
353     }
354
355     public String JavaDoc getTitle() {
356         if (fInputContextManager == null)
357             return super.getTitle();
358         InputContext context = fInputContextManager.getPrimaryContext();
359         if (context == null)
360             return super.getTitle();
361         return context.getInput().getName();
362     }
363     
364     public void updateTitle() {
365         firePropertyChange(IWorkbenchPart.PROP_TITLE);
366     }
367
368     public String JavaDoc getTitleProperty() {
369         return ""; //$NON-NLS-1$
370
}
371
372     /*
373      * (non-Javadoc)
374      *
375      * @see org.eclipse.ui.ISaveablePart#doSave(org.eclipse.core.runtime.IProgressMonitor)
376      */

377     public void doSave(IProgressMonitor monitor) {
378         commitPages(true);
379         fInputContextManager.save(monitor);
380         editorDirtyStateChanged();
381     }
382     
383     /**
384      *
385      */

386     public void doRevert() {
387         IFormPage formPage = getActivePageInstance();
388         // If the active page is a form page, commit all of its dirty field
389
// values to the model
390
if ((formPage != null) &&
391                 (formPage instanceof PDEFormPage)) {
392             formPage.getManagedForm().commit(true);
393         }
394         // If the editor has source pages, revert them
395
// Reverting the source page fires events to the associated form pages
396
// which will cause all their values to be updated
397
boolean reverted = doRevertSourcePages();
398         // If the editor does not have any source pages, revert the form pages
399
// by directly reloading the underlying model.
400
// Reloading the model fires a world changed event to all form pages
401
// causing them to update their values
402
if (reverted == false) {
403             reverted = doRevertFormPage();
404         }
405         // If the revert operation was performed disable the revert action and
406
// fire the dirty event
407
if (reverted) {
408             editorDirtyStateChanged();
409         }
410     }
411     
412     /**
413      * @return
414      */

415     private boolean doRevertFormPage() {
416         boolean reverted = false;
417         IBaseModel model = getAggregateModel();
418         if (model instanceof IWorkspaceModel) {
419             IWorkspaceModel workspaceModel = (IWorkspaceModel)model;
420             workspaceModel.reload();
421             reverted = true;
422         }
423         return reverted;
424     }
425     
426     /**
427      * @return
428      */

429     private boolean doRevertSourcePages() {
430         boolean reverted = false;
431         IFormPage[] pages = getPages();
432         for (int i = 0; i < pages.length; i++) {
433             if (pages[i] instanceof PDESourcePage) {
434                 PDESourcePage sourcePage = (PDESourcePage)pages[i];
435                 // Flush any pending editor operations into the document
436
// so that the revert operation executes (revert operation is
437
// aborted if the current document has not changed)
438
// This happens when a form page field is modified.
439
// The source page is not updated until a source operation is
440
// performed or the source page is made active and possibly
441
// in some other cases.
442
sourcePage.getInputContext().flushEditorInput();
443                 // Revert the source page to the contents of the last save to file
444
sourcePage.doRevertToSaved();
445                 reverted = true;
446             }
447         }
448         return reverted;
449     }
450
451     public void doRevert(IEditorInput input) {
452         IFormPage currentPage = getActivePageInstance();
453         if (currentPage != null && currentPage instanceof PDEFormPage)
454             ((PDEFormPage) currentPage).cancelEdit();
455         InputContext context = fInputContextManager.getContext(input);
456         IFormPage page = findPage(context.getId());
457         if (page!=null && page instanceof PDESourcePage) {
458             PDESourcePage spage = (PDESourcePage) page;
459             spage.doRevertToSaved();
460         }
461         editorDirtyStateChanged();
462     }
463     
464     /**
465      * @return
466      */

467     public String JavaDoc getContextIDForSaveAs() {
468         // Sub-classes must override this method and the isSaveAsAllowed
469
// method to perform save as operations
470
return null;
471     }
472     
473     /*
474      * (non-Javadoc)
475      *
476      * @see org.eclipse.ui.ISaveablePart#doSaveAs()
477      */

478     public void doSaveAs() {
479         try {
480             // Get the context for which the save as operation should be
481
// performed
482
String JavaDoc contextID = getContextIDForSaveAs();
483             // Perform the same as operation
484
getContextManager().saveAs(getProgressMonitor(),
485                     contextID);
486             // Get the new editor input
487
IEditorInput input =
488                 getContextManager().findContext(
489                         contextID).getInput();
490             // Store the new editor input
491
setInputWithNotify(input);
492             // Update the title of the editor using the name of the new editor
493
// input
494
setPartName(input.getName());
495             // Fire a property change accordingly
496
firePropertyChange(PROP_DIRTY);
497         } catch (InterruptedException JavaDoc e) {
498             // Ignore
499
} catch (Exception JavaDoc e) {
500             String JavaDoc title = PDEUIMessages.PDEFormEditor_errorTitleProblemSaveAs;
501             String JavaDoc message = PDEUIMessages.PDEFormEditor_errorMessageSaveNotCompleted;
502             if (e.getMessage() != null) {
503                 message = message + ' ' + e.getMessage();
504             }
505             PDEPlugin.logException(e, title, message);
506         }
507     }
508     
509     /*
510      * (non-Javadoc)
511      *
512      * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed()
513      */

514     public boolean isSaveAsAllowed() {
515         return false;
516     }
517
518     /**
519      *
520      */

521     private void storeDefaultPage() {
522         IEditorInput input = getEditorInput();
523         String JavaDoc pageId = fLastActivePageId;
524         if (pageId == null)
525             return;
526         if (input instanceof IFileEditorInput) {
527             // Triggered by opening a file in the workspace
528
// e.g. From the Package Explorer View
529
setPropertyEditorPageKey((IFileEditorInput)input, pageId);
530         } else if (input instanceof IStorageEditorInput) {
531             // Triggered by opening a file NOT in the workspace
532
// e.g. From the Plug-in View
533
setDialogEditorPageKey(pageId);
534         }
535     }
536
537     /**
538      * @param pageID
539      */

540     protected void setDialogEditorPageKey(String JavaDoc pageID) {
541         // Use one global setting for all files belonging to a given editor
542
// type. Use the editor ID as the key.
543
// Could use the storage editor input to get the underlying file
544
// and use it as a unique key; but, the dialog settings file will
545
// grow out of control and we do not need that level of granularity
546
IDialogSettings section = getSettingsSection();
547         section.put(getEditorID(), pageID);
548     }
549     
550     /**
551      *
552      */

553     protected String JavaDoc getDialogEditorPageKey() {
554         // Use one global setting for all files belonging to a given editor
555
// type. Use the editor ID as the key.
556
// Could use the storage editor input to get the underlying file
557
// and use it as a unique key; but, the dialog settings file will
558
// grow out of control and we do not need that level of granularity
559
IDialogSettings section = getSettingsSection();
560         return section.get(getEditorID());
561     }
562     
563     /**
564      * @return
565      */

566     protected abstract String JavaDoc getEditorID();
567     
568     /**
569      * @param input
570      * @param pageId
571      */

572     protected void setPropertyEditorPageKey(IFileEditorInput input, String JavaDoc pageId) {
573         // We are using the file itself to persist the editor page key property
574
// The value persists even after the editor is closed
575
IFile file = input.getFile();
576         try {
577             // Set the editor page ID as a persistent property on the file
578
file.setPersistentProperty(
579                     IPDEUIConstants.PROPERTY_EDITOR_PAGE_KEY,
580                     pageId);
581         } catch (CoreException e) {
582             // Ignore
583
}
584     }
585     
586     /**
587      * @return
588      */

589     private String JavaDoc loadDefaultPage() {
590         IEditorInput input = getEditorInput();
591         if (input instanceof IFileEditorInput) {
592             // Triggered by opening a file in the workspace
593
// e.g. From the Package Explorer View
594
return getPropertyEditorPageKey((IFileEditorInput)input);
595         } else if (input instanceof IStorageEditorInput) {
596             // Triggered by opening a file NOT in the workspace
597
// e.g. From the Plug-in View
598
return getDialogEditorPageKey();
599         }
600         return null;
601     }
602
603     /**
604      * @param input
605      * @return
606      */

607     protected String JavaDoc getPropertyEditorPageKey(IFileEditorInput input) {
608         // We are using the file itself to persist the editor page key property
609
// The value persists even after the editor is closed
610
IFile file = input.getFile();
611         // Get the persistent editor page key from the file
612
try {
613             return file.getPersistentProperty(
614                     IPDEUIConstants.PROPERTY_EDITOR_PAGE_KEY);
615         } catch (CoreException e) {
616             return null;
617         }
618     }
619     
620     public void dispose() {
621         storeDefaultPage();
622         if (fEditorSelectionChangedListener != null) {
623             fEditorSelectionChangedListener.uninstall(getSite().getSelectionProvider());
624             fEditorSelectionChangedListener= null;
625         }
626         //setSelection(new StructuredSelection());
627
PDEPlugin.getDefault().getLabelProvider().disconnect(this);
628         XMLComponentRegistry.Instance().disconnect(this);
629         PDEModelUtility.disconnect(this);
630         if (clipboard != null) {
631             clipboard.dispose();
632             clipboard = null;
633         }
634         super.dispose();
635         fInputContextManager.dispose();
636         fInputContextManager = null;
637     }
638     public boolean isDirty() {
639         fLastDirtyState = computeDirtyState();
640         return fLastDirtyState;
641     }
642     
643     private boolean computeDirtyState() {
644         IFormPage page = getActivePageInstance();
645         if ((page != null && page.isDirty())
646                 || (fInputContextManager != null && fInputContextManager.isDirty()))
647             return true;
648         return super.isDirty();
649     }
650     
651     public boolean getLastDirtyState() {
652         return fLastDirtyState;
653     }
654
655     public void fireSaveNeeded(String JavaDoc contextId, boolean notify) {
656         if (contextId == null)
657             return;
658         InputContext context = fInputContextManager.findContext(contextId);
659         if (context != null)
660             fireSaveNeeded(context.getInput(), notify);
661     }
662     public void fireSaveNeeded(IEditorInput input, boolean notify) {
663         if (notify)
664             editorDirtyStateChanged();
665         if (isDirty())
666             validateEdit(input);
667     }
668     public void editorDirtyStateChanged() {
669         super.editorDirtyStateChanged();
670         PDEFormEditorContributor contributor = getContributor();
671         if (contributor != null)
672             contributor.updateActions();
673     }
674     private void validateEdit(IEditorInput input) {
675         final InputContext context = fInputContextManager.getContext(input);
676         if (!context.validateEdit()) {
677             getSite().getShell().getDisplay().asyncExec(new Runnable JavaDoc() {
678                 public void run() {
679                     doRevert(context.getInput());
680                     context.setValidated(false);
681                 }
682             });
683         }
684     }
685     
686     /**
687      * @return
688      */

689     private IDialogSettings getSettingsSection() {
690         // Store global settings that will persist when the editor is closed
691
// in the dialog settings (This is cheating)
692
// Get the dialog settings
693
IDialogSettings root = PDEPlugin.getDefault().getDialogSettings();
694         // Get the dialog section reserved for PDE form editors
695
IDialogSettings section = root.getSection(F_DIALOG_EDITOR_SECTION_KEY);
696         // If the section is not defined, define it
697
if (section == null) {
698             section = root.addNewSection(F_DIALOG_EDITOR_SECTION_KEY);
699         }
700         return section;
701     }
702     
703     public void gotoMarker(IMarker marker) {
704         IResource resource = marker.getResource();
705         InputContext context = fInputContextManager.findContext(resource);
706         if (context == null)
707             return;
708         IFormPage page = getActivePageInstance();
709         if (!context.getId().equals(page.getId()))
710             page = setActivePage(context.getId());
711         IDE.gotoMarker(page, marker);
712     }
713     
714     public void openToSourcePage(Object JavaDoc object, int offset, int length) {
715         InputContext context = getInputContext(object);
716         if (context != null) {
717             PDESourcePage page = (PDESourcePage)setActivePage(context.getId());
718             if (page != null)
719                 page.selectAndReveal(offset, length);
720         }
721     }
722
723     public void setSelection(ISelection selection) {
724         getSite().getSelectionProvider().setSelection(selection);
725         getContributor().updateSelectableActions(selection);
726     }
727     public ISelection getSelection() {
728         return getSite().getSelectionProvider().getSelection();
729     }
730     public Object JavaDoc getAdapter(Class JavaDoc key) {
731         if (key.equals(IContentOutlinePage.class)) {
732             return getContentOutline();
733         }
734         if (key.equals(IGotoMarker.class)) {
735             return this;
736         }
737         if (key.equals(ISearchEditorAccess.class)) {
738             return this;
739         }
740         return super.getAdapter(key);
741     }
742     public Menu getContextMenu() {
743         return fContextMenu;
744     }
745     public PDEMultiPageContentOutline getContentOutline() {
746         if (fContentOutline == null || fContentOutline.isDisposed()) {
747             fContentOutline = new PDEMultiPageContentOutline(this);
748             updateContentOutline(getActivePageInstance());
749         }
750         return fContentOutline;
751     }
752
753     /**
754      *
755      * @return outline page or null
756      */

757     protected ISortableContentOutlinePage getFormOutline() {
758         if (fFormOutline == null) {
759             fFormOutline = createContentOutline();
760             if (fFormOutline != null) {
761                 fEditorSelectionChangedListener = new PDEFormEditorChangeListener();
762                 fEditorSelectionChangedListener.install(getSite()
763                         .getSelectionProvider());
764             }
765         }
766         return fFormOutline;
767     }
768     abstract protected ISortableContentOutlinePage createContentOutline();
769     
770     private void updateContentOutline(IFormPage page) {
771         if (fContentOutline == null)
772             return;
773         ISortableContentOutlinePage outline = null;
774         if (page instanceof PDESourcePage) {
775             outline = ((PDESourcePage) page).getContentOutline();
776         } else {
777             outline = getFormOutline();
778             if (outline != null && outline instanceof FormOutlinePage)
779                 ((FormOutlinePage) outline).refresh();
780         }
781         fContentOutline.setPageActive(outline);
782     }
783     
784     /* (non-Javadoc)
785      * @see org.eclipse.ui.forms.editor.FormEditor#setActivePage(java.lang.String)
786      */

787     public IFormPage setActivePage(String JavaDoc pageId) {
788         IFormPage page = super.setActivePage(pageId);
789         if (page != null)
790             updateContentOutline(page);
791         return page;
792     }
793
794     /* package */IFormPage[] getPages() {
795         ArrayList JavaDoc formPages = new ArrayList JavaDoc();
796         for (int i = 0; i < pages.size(); i++) {
797             Object JavaDoc page = pages.get(i);
798             if (page instanceof IFormPage)
799                 formPages.add(page);
800         }
801         return (IFormPage[]) formPages.toArray(new IFormPage[formPages.size()]);
802     }
803     protected void performGlobalAction(String JavaDoc id) {
804         // preserve selection
805
ISelection selection = getSelection();
806         boolean handled = ((PDEFormPage) getActivePageInstance())
807                 .performGlobalAction(id);
808         if (!handled) {
809             IFormPage page = getActivePageInstance();
810             if (page instanceof PDEFormPage) {
811                 if (id.equals(ActionFactory.UNDO.getId())) {
812                     fInputContextManager.undo();
813                     return;
814                 }
815                 if (id.equals(ActionFactory.REDO.getId())) {
816                     fInputContextManager.redo();
817                     return;
818                 }
819                 if (id.equals(ActionFactory.CUT.getId())
820                         || id.equals(ActionFactory.COPY.getId())) {
821                     copyToClipboard(selection);
822                     return;
823                 }
824             }
825         }
826     }
827     
828     /**
829      * @param selection
830      */

831     private void copyToClipboard(ISelection selection) {
832         Object JavaDoc[] objects = null;
833         String JavaDoc textVersion = null;
834         if (selection instanceof IStructuredSelection) {
835             IStructuredSelection ssel = (IStructuredSelection) selection;
836             if (ssel == null || ssel.size() == 0)
837                 return;
838             objects = ssel.toArray();
839             StringWriter JavaDoc writer = new StringWriter JavaDoc();
840             PrintWriter JavaDoc pwriter = new PrintWriter JavaDoc(writer);
841             Class JavaDoc objClass = null;
842             for (int i = 0; i < objects.length; i++) {
843                 Object JavaDoc obj = objects[i];
844                 if (objClass == null)
845                     objClass = obj.getClass();
846                 else if (objClass.equals(obj.getClass()) == false)
847                     return;
848                 if (obj instanceof IWritable) {
849                     // Add a customized delimiter in between all serialized
850
// objects to format the text representation
851
if ((i != 0) &&
852                             (obj instanceof IWritableDelimiter)) {
853                         ((IWritableDelimiter)obj).writeDelimeter(pwriter);
854                     }
855                     ((IWritable) obj).write("", pwriter); //$NON-NLS-1$
856
} else if (obj instanceof String JavaDoc) {
857                     // Delimiter is always a newline
858
pwriter.println((String JavaDoc)obj);
859                 }
860             }
861             pwriter.flush();
862             textVersion = writer.toString();
863             try {
864                 pwriter.close();
865                 writer.close();
866             } catch (IOException JavaDoc e) {
867             }
868         } else if (selection instanceof ITextSelection) {
869             textVersion = ((ITextSelection) selection).getText();
870         }
871         if ((textVersion == null || textVersion.length() == 0) && objects == null)
872             return;
873         // set the clipboard contents
874
Object JavaDoc[]o = null;
875         Transfer[] t = null;
876         if (objects == null ) {
877             o = new Object JavaDoc[] {textVersion};
878             t = new Transfer[] {TextTransfer.getInstance()};
879         } else if (textVersion == null || textVersion.length() == 0) {
880             o = new Object JavaDoc[] {objects};
881             t = new Transfer[] {ModelDataTransfer.getInstance()};
882         } else {
883             o = new Object JavaDoc[] {objects, textVersion};
884             t = new Transfer[] {ModelDataTransfer.getInstance(), TextTransfer.getInstance()};
885         }
886         clipboard.setContents(o, t);
887     }
888     public boolean canPasteFromClipboard() {
889         IFormPage page = getActivePageInstance();
890         if (page instanceof PDEFormPage) {
891             return ((PDEFormPage) page).canPaste(getClipboard());
892         }
893         return false;
894     }
895     public boolean canCopy(ISelection selection) {
896         if (selection == null)
897             return false;
898         if (selection instanceof IStructuredSelection)
899             return !selection.isEmpty();
900         if (selection instanceof ITextSelection) {
901             ITextSelection textSelection = (ITextSelection) selection;
902             return textSelection.getLength() > 0;
903         }
904         return false;
905     }
906     void updateUndo(IAction undoAction, IAction redoAction) {
907         IModelUndoManager undoManager = fInputContextManager.getUndoManager();
908         if (undoManager != null)
909             undoManager.setActions(undoAction, redoAction);
910     }
911     
912     /**
913      * Triggered by toggling the 'Link with Editor' button in the outline view
914      */

915     public void synchronizeOutlinePage() {
916         // Get current page
917
IFormPage page = getActivePageInstance();
918
919         if (page instanceof PDESourcePage) {
920             // Synchronize with current source page
921
((PDESourcePage) page).synchronizeOutlinePage();
922         } else {
923             // Synchronize with current form page
924
// This currently does not work
925
// TODO: Fix 'Link with Editor' functionality for form pages
926
if (getFormOutline() != null) {
927                 getFormOutline().setSelection(getSelection());
928             }
929         }
930     }
931     
932     /* (non-Javadoc)
933      * @see org.eclipse.search.ui.text.ISearchEditorAccess#getDocument(org.eclipse.search.ui.text.Match)
934      */

935     public IDocument getDocument(Match match) {
936         InputContext context = getInputContext(match.getElement());
937         return context == null ? null : context.getDocumentProvider().getDocument(context.getInput());
938     }
939
940     /* (non-Javadoc)
941      * @see org.eclipse.search.ui.text.ISearchEditorAccess#getAnnotationModel(org.eclipse.search.ui.text.Match)
942      */

943     public IAnnotationModel getAnnotationModel(Match match) {
944         InputContext context = getInputContext(match.getElement());
945         return context == null ? null : context.getDocumentProvider().getAnnotationModel(context.getInput());
946     }
947     
948     protected abstract InputContext getInputContext(Object JavaDoc object);
949     
950     protected final void addPages() {
951         fError = getAggregateModel() == null;
952         if (fError) {
953             try {
954                 addPage(new MissingResourcePage(this));
955             } catch (PartInitException e) {
956                 PDEPlugin.logException(e);
957             }
958         } else
959             addEditorPages();
960     }
961     
962     protected abstract void addEditorPages();
963     
964     public final void contextAdded(InputContext context) {
965         if (fError) {
966             removePage(0);
967             addPages();
968             if (!fError)
969                 setActivePage(OverviewPage.PAGE_ID);
970         } else
971             editorContextAdded(context);
972     }
973     
974     public abstract void editorContextAdded(InputContext context);
975     
976     /**
977      * @return
978      */

979     protected IProgressMonitor getProgressMonitor() {
980         IProgressMonitor monitor = null;
981         IStatusLineManager manager = getStatusLineManager();
982         if (manager != null) {
983             monitor = manager.getProgressMonitor();
984         }
985         if (monitor == null) {
986             monitor = new NullProgressMonitor();
987         }
988         return monitor;
989     }
990
991     /**
992      * @return
993      */

994     protected IStatusLineManager getStatusLineManager() {
995         return getEditorSite().getActionBars().getStatusLineManager();
996     }
997
998 }
999
Popular Tags