KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > team > internal > ccvs > ui > HistoryView


1 /*******************************************************************************
2  * Copyright (c) 2000, 2005 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.team.internal.ccvs.ui;
12
13  
14 import java.io.InputStream JavaDoc;
15 import java.lang.reflect.InvocationTargetException JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.Iterator JavaDoc;
18
19 import org.eclipse.core.resources.*;
20 import org.eclipse.core.runtime.*;
21 import org.eclipse.core.runtime.jobs.Job;
22 import org.eclipse.jface.action.*;
23 import org.eclipse.jface.dialogs.IDialogConstants;
24 import org.eclipse.jface.dialogs.MessageDialog;
25 import org.eclipse.jface.operation.IRunnableWithProgress;
26 import org.eclipse.jface.preference.IPreferenceStore;
27 import org.eclipse.jface.text.*;
28 import org.eclipse.jface.viewers.*;
29 import org.eclipse.osgi.util.NLS;
30 import org.eclipse.swt.SWT;
31 import org.eclipse.swt.custom.*;
32 import org.eclipse.swt.dnd.DND;
33 import org.eclipse.swt.dnd.Transfer;
34 import org.eclipse.swt.graphics.Image;
35 import org.eclipse.swt.layout.GridData;
36 import org.eclipse.swt.widgets.*;
37 import org.eclipse.team.core.RepositoryProvider;
38 import org.eclipse.team.core.TeamException;
39 import org.eclipse.team.core.synchronize.SyncInfo;
40 import org.eclipse.team.internal.ccvs.core.*;
41 import org.eclipse.team.internal.ccvs.core.client.Command;
42 import org.eclipse.team.internal.ccvs.core.client.Update;
43 import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot;
44 import org.eclipse.team.internal.ccvs.ui.actions.*;
45 import org.eclipse.team.internal.ccvs.ui.operations.*;
46 import org.eclipse.team.internal.ui.Utils;
47 import org.eclipse.team.ui.synchronize.SyncInfoCompareInput;
48 import org.eclipse.ui.*;
49 import org.eclipse.ui.ide.ResourceUtil;
50 import org.eclipse.ui.part.ResourceTransfer;
51 import org.eclipse.ui.part.ViewPart;
52 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
53
54 /**
55  * The history view allows browsing of an array of resource revisions
56  */

57 public class HistoryView extends ViewPart {
58     private IFile file;
59     // cached for efficiency
60
private ILogEntry[] entries;
61     
62     private HistoryTableProvider historyTableProvider;
63     
64     private TableViewer tableViewer;
65     private TextViewer textViewer;
66     private TableViewer tagViewer;
67     
68     private OpenLogEntryAction openAction;
69     private IAction toggleTextAction;
70     private IAction toggleTextWrapAction;
71     private IAction toggleListAction;
72     private TextViewerAction copyAction;
73     private TextViewerAction selectAllAction;
74     private Action getContentsAction;
75     private Action getRevisionAction;
76     private Action refreshAction;
77     private Action tagWithExistingAction;
78     private Action linkWithEditorAction;
79     
80     private SashForm sashForm;
81     private SashForm innerSashForm;
82
83     private Image branchImage;
84     private Image versionImage;
85     
86     private ILogEntry currentSelection;
87     private boolean linkingEnabled;
88     
89     private IPreferenceStore settings;
90     
91     private FetchLogEntriesJob fetchLogEntriesJob;
92     
93     private boolean shutdown = false;
94     
95     public static final String JavaDoc VIEW_ID = "org.eclipse.team.ccvs.ui.HistoryView"; //$NON-NLS-1$
96

97     private IPartListener partListener = new IPartListener() {
98         public void partActivated(IWorkbenchPart part) {
99             if (part instanceof IEditorPart)
100                 editorActivated((IEditorPart) part);
101         }
102         public void partBroughtToTop(IWorkbenchPart part) {
103             if(part == HistoryView.this)
104                 editorActivated(getViewSite().getPage().getActiveEditor());
105         }
106         public void partOpened(IWorkbenchPart part) {
107             if(part == HistoryView.this)
108                 editorActivated(getViewSite().getPage().getActiveEditor());
109         }
110         public void partClosed(IWorkbenchPart part) {
111         }
112         public void partDeactivated(IWorkbenchPart part) {
113         }
114     };
115     
116     private IPartListener2 partListener2 = new IPartListener2() {
117         public void partActivated(IWorkbenchPartReference ref) {
118         }
119         public void partBroughtToTop(IWorkbenchPartReference ref) {
120         }
121         public void partClosed(IWorkbenchPartReference ref) {
122         }
123         public void partDeactivated(IWorkbenchPartReference ref) {
124         }
125         public void partOpened(IWorkbenchPartReference ref) {
126         }
127         public void partHidden(IWorkbenchPartReference ref) {
128         }
129         public void partVisible(IWorkbenchPartReference ref) {
130             if(ref.getPart(true) == HistoryView.this)
131                 editorActivated(getViewSite().getPage().getActiveEditor());
132         }
133         public void partInputChanged(IWorkbenchPartReference ref) {
134         }
135     };
136
137
138     private class FetchLogEntriesJob extends Job {
139         public ICVSRemoteFile remoteFile;
140         public FetchLogEntriesJob() {
141             super(CVSUIMessages.HistoryView_fetchHistoryJob); //$NON-NLS-1$;
142
}
143         public void setRemoteFile(ICVSRemoteFile file) {
144             this.remoteFile = file;
145         }
146         public IStatus run(IProgressMonitor monitor) {
147             try {
148                 if(remoteFile != null && !shutdown) {
149                     entries = remoteFile.getLogEntries(monitor);
150                     final String JavaDoc revisionId = remoteFile.getRevision();
151                     getSite().getShell().getDisplay().asyncExec(new Runnable JavaDoc() {
152                         public void run() {
153                             if(entries != null && tableViewer != null && ! tableViewer.getTable().isDisposed()) {
154                                 tableViewer.refresh();
155                                 selectRevision(revisionId);
156                             }
157                         }
158                     });
159                 }
160                 return Status.OK_STATUS;
161             } catch (TeamException e) {
162                 return e.getStatus();
163             }
164         }
165         public ICVSRemoteFile getRemoteFile() {
166             return this.remoteFile;
167         }
168     };
169     
170     /**
171      * Adds the action contributions for this view.
172      */

173     protected void contributeActions() {
174         // Refresh (toolbar)
175
CVSUIPlugin plugin = CVSUIPlugin.getPlugin();
176         refreshAction = new Action(CVSUIMessages.HistoryView_refreshLabel, plugin.getImageDescriptor(ICVSUIConstants.IMG_REFRESH_ENABLED)) { //$NON-NLS-1$
177
public void run() {
178                 refresh();
179             }
180         };
181         refreshAction.setToolTipText(CVSUIMessages.HistoryView_refresh); //$NON-NLS-1$
182
refreshAction.setDisabledImageDescriptor(plugin.getImageDescriptor(ICVSUIConstants.IMG_REFRESH_DISABLED));
183         refreshAction.setHoverImageDescriptor(plugin.getImageDescriptor(ICVSUIConstants.IMG_REFRESH));
184         
185         // Link with Editor (toolbar)
186
linkWithEditorAction = new Action(CVSUIMessages.HistoryView_linkWithLabel, plugin.getImageDescriptor(ICVSUIConstants.IMG_LINK_WITH_EDITOR_ENABLED)) { //$NON-NLS-1$
187
public void run() {
188                  setLinkingEnabled(isChecked());
189              }
190          };
191         linkWithEditorAction.setToolTipText(CVSUIMessages.HistoryView_linkWithLabel); //$NON-NLS-1$
192
linkWithEditorAction.setHoverImageDescriptor(plugin.getImageDescriptor(ICVSUIConstants.IMG_LINK_WITH_EDITOR));
193         linkWithEditorAction.setChecked(isLinkingEnabled());
194         
195         // Double click open action
196
openAction = new OpenLogEntryAction();
197         tableViewer.getTable().addListener(SWT.DefaultSelection, new Listener() {
198             public void handleEvent(Event e) {
199                 openAction.selectionChanged(null, tableViewer.getSelection());
200                 openAction.run(null);
201             }
202         });
203
204         getContentsAction = getContextMenuAction(CVSUIMessages.HistoryView_getContentsAction, true /* needs progress */, new IWorkspaceRunnable() { //$NON-NLS-1$
205
public void run(IProgressMonitor monitor) throws CoreException {
206                 ICVSRemoteFile remoteFile = currentSelection.getRemoteFile();
207                 monitor.beginTask(null, 100);
208                 try {
209                     if(confirmOverwrite()) {
210                         InputStream JavaDoc in = remoteFile.getContents(new SubProgressMonitor(monitor, 50));
211                         file.setContents(in, false, true, new SubProgressMonitor(monitor, 50));
212                     }
213                 } catch (TeamException e) {
214                     throw new CoreException(e.getStatus());
215                 } finally {
216                     monitor.done();
217                 }
218             }
219         });
220         PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, IHelpContextIds.GET_FILE_CONTENTS_ACTION);
221
222         getRevisionAction = getContextMenuAction(CVSUIMessages.HistoryView_getRevisionAction, true /* needs progress */, new IWorkspaceRunnable() { //$NON-NLS-1$
223
public void run(IProgressMonitor monitor) throws CoreException {
224                 ICVSRemoteFile remoteFile = currentSelection.getRemoteFile();
225                 try {
226                     if(confirmOverwrite()) {
227                         CVSTag revisionTag = new CVSTag(remoteFile.getRevision(), CVSTag.VERSION);
228                         
229                         if(CVSAction.checkForMixingTags(getSite().getShell(), new IResource[] {file}, revisionTag)) {
230                             new UpdateOperation(
231                                     null,
232                                     new IResource[] {file},
233                                     new Command.LocalOption[] {Update.IGNORE_LOCAL_CHANGES},
234                                     revisionTag)
235                                         .run(monitor);
236                             historyTableProvider.setFile(remoteFile);
237                             Display.getDefault().asyncExec(new Runnable JavaDoc() {
238                                 public void run() {
239                                     tableViewer.refresh();
240                                 }
241                             });
242                         }
243                     }
244                 } catch (InvocationTargetException JavaDoc e) {
245                     CVSException.wrapException(e);
246                 } catch (InterruptedException JavaDoc e) {
247                     // Cancelled by user
248
}
249             }
250         });
251         PlatformUI.getWorkbench().getHelpSystem().setHelp(getRevisionAction, IHelpContextIds.GET_FILE_REVISION_ACTION);
252
253         // Override MoveRemoteTagAction to work for log entries
254
final IActionDelegate tagActionDelegate = new MoveRemoteTagAction() {
255             protected ICVSResource[] getSelectedCVSResources() {
256                 ICVSResource[] resources = super.getSelectedCVSResources();
257                 if (resources == null || resources.length == 0) {
258                     ArrayList JavaDoc logEntrieFiles = null;
259                     if (!selection.isEmpty()) {
260                         logEntrieFiles = new ArrayList JavaDoc();
261                         Iterator JavaDoc elements = selection.iterator();
262                         while (elements.hasNext()) {
263                             Object JavaDoc next = elements.next();
264                             if (next instanceof ILogEntry) {
265                                 logEntrieFiles.add(((ILogEntry)next).getRemoteFile());
266                                 continue;
267                             }
268                             if (next instanceof IAdaptable) {
269                                 IAdaptable a = (IAdaptable) next;
270                                 Object JavaDoc adapter = a.getAdapter(ICVSResource.class);
271                                 if (adapter instanceof ICVSResource) {
272                                     logEntrieFiles.add(((ILogEntry)adapter).getRemoteFile());
273                                     continue;
274                                 }
275                             }
276                         }
277                     }
278                     if (logEntrieFiles != null && !logEntrieFiles.isEmpty()) {
279                         return (ICVSResource[])logEntrieFiles.toArray(new ICVSResource[logEntrieFiles.size()]);
280                     }
281                 }
282                 return resources;
283             }
284             /*
285              * Override the creation of the tag operation in order to support
286              * the refresh of the view after the tag operation completes
287              */

288             protected ITagOperation createTagOperation() {
289                 return new TagInRepositoryOperation(getTargetPart(), getSelectedRemoteResources()) {
290                     public void execute(IProgressMonitor monitor) throws CVSException, InterruptedException JavaDoc {
291                         super.execute(monitor);
292                         Display.getDefault().asyncExec(new Runnable JavaDoc() {
293                             public void run() {
294                                 if( ! wasCancelled()) {
295                                     refresh();
296                                 }
297                             }
298                         });
299                     };
300                 };
301             }
302         };
303         tagWithExistingAction = getContextMenuAction(CVSUIMessages.HistoryView_tagWithExistingAction, false /* no progress */, new IWorkspaceRunnable() { //$NON-NLS-1$
304
public void run(IProgressMonitor monitor) throws CoreException {
305                 tagActionDelegate.selectionChanged(tagWithExistingAction, tableViewer.getSelection());
306                 tagActionDelegate.run(tagWithExistingAction);
307             }
308         });
309         PlatformUI.getWorkbench().getHelpSystem().setHelp(getRevisionAction, IHelpContextIds.TAG_WITH_EXISTING_ACTION);
310                 
311         // Toggle text visible action
312
final IPreferenceStore store = CVSUIPlugin.getPlugin().getPreferenceStore();
313         toggleTextAction = new Action(CVSUIMessages.HistoryView_showComment) { //$NON-NLS-1$
314
public void run() {
315                 setViewerVisibility();
316                 store.setValue(ICVSUIConstants.PREF_SHOW_COMMENTS, toggleTextAction.isChecked());
317             }
318         };
319         toggleTextAction.setChecked(store.getBoolean(ICVSUIConstants.PREF_SHOW_COMMENTS));
320         PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleTextAction, IHelpContextIds.SHOW_COMMENT_IN_HISTORY_ACTION);
321
322         // Toggle wrap comments action
323
toggleTextWrapAction = new Action(CVSUIMessages.HistoryView_wrapComment) { //$NON-NLS-1$
324
public void run() {
325             setViewerVisibility();
326             store.setValue(ICVSUIConstants.PREF_WRAP_COMMENTS, toggleTextWrapAction.isChecked());
327           }
328         };
329         toggleTextWrapAction.setChecked(store.getBoolean(ICVSUIConstants.PREF_WRAP_COMMENTS));
330         //PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleTextWrapAction, IHelpContextIds.SHOW_TAGS_IN_HISTORY_ACTION);
331

332         // Toggle list visible action
333
toggleListAction = new Action(CVSUIMessages.HistoryView_showTags) { //$NON-NLS-1$
334
public void run() {
335                 setViewerVisibility();
336                 store.setValue(ICVSUIConstants.PREF_SHOW_TAGS, toggleListAction.isChecked());
337             }
338         };
339         toggleListAction.setChecked(store.getBoolean(ICVSUIConstants.PREF_SHOW_TAGS));
340         PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleListAction, IHelpContextIds.SHOW_TAGS_IN_HISTORY_ACTION);
341         
342         // Contribute actions to popup menu
343
MenuManager menuMgr = new MenuManager();
344         Menu menu = menuMgr.createContextMenu(tableViewer.getTable());
345         menuMgr.addMenuListener(new IMenuListener() {
346             public void menuAboutToShow(IMenuManager menuMgr) {
347                 fillTableMenu(menuMgr);
348             }
349         });
350         menuMgr.setRemoveAllWhenShown(true);
351         tableViewer.getTable().setMenu(menu);
352         getSite().registerContextMenu(menuMgr, tableViewer);
353
354         // Contribute toggle text visible to the toolbar drop-down
355
IActionBars actionBars = getViewSite().getActionBars();
356         IMenuManager actionBarsMenu = actionBars.getMenuManager();
357         actionBarsMenu.add(toggleTextWrapAction);
358         actionBarsMenu.add(new Separator());
359         actionBarsMenu.add(toggleTextAction);
360         actionBarsMenu.add(toggleListAction);
361
362         // Create the local tool bar
363
IToolBarManager tbm = getViewSite().getActionBars().getToolBarManager();
364         tbm.add(refreshAction);
365         tbm.add(linkWithEditorAction);
366         tbm.update(false);
367     
368         // Create actions for the text editor
369
copyAction = new TextViewerAction(textViewer, ITextOperationTarget.COPY);
370         copyAction.setText(CVSUIMessages.HistoryView_copy); //$NON-NLS-1$
371
actionBars.setGlobalActionHandler(ITextEditorActionConstants.COPY, copyAction);
372         
373         selectAllAction = new TextViewerAction(textViewer, ITextOperationTarget.SELECT_ALL);
374         selectAllAction.setText(CVSUIMessages.HistoryView_selectAll); //$NON-NLS-1$
375
actionBars.setGlobalActionHandler(ITextEditorActionConstants.SELECT_ALL, selectAllAction);
376
377         actionBars.updateActionBars();
378
379         menuMgr = new MenuManager();
380         menuMgr.setRemoveAllWhenShown(true);
381         menuMgr.addMenuListener(new IMenuListener() {
382             public void menuAboutToShow(IMenuManager menuMgr) {
383                 fillTextMenu(menuMgr);
384             }
385         });
386         StyledText text = textViewer.getTextWidget();
387         menu = menuMgr.createContextMenu(text);
388         text.setMenu(menu);
389     }
390     private void setViewerVisibility() {
391         boolean showText = toggleTextAction.isChecked();
392         boolean showList = toggleListAction.isChecked();
393         if (showText && showList) {
394             sashForm.setMaximizedControl(null);
395             innerSashForm.setMaximizedControl(null);
396         } else if (showText) {
397             sashForm.setMaximizedControl(null);
398             innerSashForm.setMaximizedControl(textViewer.getTextWidget());
399         } else if (showList) {
400             sashForm.setMaximizedControl(null);
401             innerSashForm.setMaximizedControl(tagViewer.getTable());
402         } else {
403             sashForm.setMaximizedControl(tableViewer.getControl());
404         }
405         
406         boolean wrapText = toggleTextWrapAction.isChecked();
407         textViewer.getTextWidget().setWordWrap(wrapText);
408     }
409     /*
410      * Method declared on IWorkbenchPart
411      */

412     public void createPartControl(Composite parent) {
413         settings = CVSUIPlugin.getPlugin().getPreferenceStore();
414         this.linkingEnabled = settings.getBoolean(ICVSUIConstants.PREF_HISTORY_VIEW_EDITOR_LINKING);
415
416         initializeImages();
417         
418         sashForm = new SashForm(parent, SWT.VERTICAL);
419         sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
420         
421         tableViewer = createTable(sashForm);
422         innerSashForm = new SashForm(sashForm, SWT.HORIZONTAL);
423         tagViewer = createTagTable(innerSashForm);
424         textViewer = createText(innerSashForm);
425         sashForm.setWeights(new int[] { 70, 30 });
426         innerSashForm.setWeights(new int[] { 50, 50 });
427         
428         contributeActions();
429         
430         setViewerVisibility();
431         
432         // set F1 help
433
PlatformUI.getWorkbench().getHelpSystem().setHelp(sashForm, IHelpContextIds.RESOURCE_HISTORY_VIEW);
434         initDragAndDrop();
435          
436         // add listener for editor page activation - this is to support editor linking
437
getSite().getPage().addPartListener(partListener);
438         getSite().getPage().addPartListener(partListener2);
439     }
440     private void initializeImages() {
441         CVSUIPlugin plugin = CVSUIPlugin.getPlugin();
442         versionImage = plugin.getImageDescriptor(ICVSUIConstants.IMG_PROJECT_VERSION).createImage();
443         branchImage = plugin.getImageDescriptor(ICVSUIConstants.IMG_TAG).createImage();
444     }
445     /**
446      * Creates the group that displays lists of the available repositories
447      * and team streams.
448      *
449      * @param the parent composite to contain the group
450      * @return the group control
451      */

452     protected TableViewer createTable(Composite parent) {
453         
454         historyTableProvider = new HistoryTableProvider();
455         TableViewer viewer = historyTableProvider.createTable(parent);
456         
457         viewer.setContentProvider(new IStructuredContentProvider() {
458             public Object JavaDoc[] getElements(Object JavaDoc inputElement) {
459                 
460                 // The entries of already been fetch so return them
461
if (entries != null) return entries;
462                 
463                 // The entries need to be fetch (or are being fetched)
464
if (!(inputElement instanceof ICVSRemoteFile)) return null;
465                 final ICVSRemoteFile remoteFile = (ICVSRemoteFile)inputElement;
466                 if(fetchLogEntriesJob == null) {
467                     fetchLogEntriesJob = new FetchLogEntriesJob();
468                 }
469                 ICVSRemoteFile file = fetchLogEntriesJob.getRemoteFile();
470                 if (file == null || !file.equals(remoteFile)) {
471                     // The resource has changed so stop the currently running job
472
if(fetchLogEntriesJob.getState() != Job.NONE) {
473                         fetchLogEntriesJob.cancel();
474                         try {
475                             fetchLogEntriesJob.join();
476                         } catch (InterruptedException JavaDoc e) {
477                             CVSUIPlugin.log(new CVSException(NLS.bind(CVSUIMessages.HistoryView_errorFetchingEntries, new String JavaDoc[] { remoteFile.getName() }), e)); //$NON-NLS-1$
478
}
479                     }
480                     fetchLogEntriesJob.setRemoteFile(remoteFile);
481                 }
482                 // Schedule the job even if it is already running
483
Utils.schedule(fetchLogEntriesJob, getViewSite());
484                 return new Object JavaDoc[0];
485             }
486             public void dispose() {
487             }
488             public void inputChanged(Viewer viewer, Object JavaDoc oldInput, Object JavaDoc newInput) {
489                 entries = null;
490             }
491         });
492         
493         viewer.addSelectionChangedListener(new ISelectionChangedListener() {
494             public void selectionChanged(SelectionChangedEvent event) {
495                 ISelection selection = event.getSelection();
496                 if (selection == null || !(selection instanceof IStructuredSelection)) {
497                     textViewer.setDocument(new Document("")); //$NON-NLS-1$
498
tagViewer.setInput(null);
499                     return;
500                 }
501                 IStructuredSelection ss = (IStructuredSelection)selection;
502                 if (ss.size() != 1) {
503                     textViewer.setDocument(new Document("")); //$NON-NLS-1$
504
tagViewer.setInput(null);
505                     return;
506                 }
507                 ILogEntry entry = (ILogEntry)ss.getFirstElement();
508                 textViewer.setDocument(new Document(entry.getComment()));
509                 tagViewer.setInput(entry.getTags());
510             }
511         });
512         
513         return viewer;
514     }
515
516     private TableViewer createTagTable(Composite parent) {
517         Table table = new Table(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
518         TableViewer result = new TableViewer(table);
519         TableLayout layout = new TableLayout();
520         layout.addColumnData(new ColumnWeightData(100));
521         table.setLayout(layout);
522         result.setContentProvider(new SimpleContentProvider() {
523             public Object JavaDoc[] getElements(Object JavaDoc inputElement) {
524                 if (inputElement == null) return new Object JavaDoc[0];
525                 CVSTag[] tags = (CVSTag[])inputElement;
526                 return tags;
527             }
528         });
529         result.setLabelProvider(new LabelProvider() {
530             public Image getImage(Object JavaDoc element) {
531                 if (element == null) return null;
532                 CVSTag tag = (CVSTag)element;
533                 switch (tag.getType()) {
534                     case CVSTag.BRANCH:
535                     case CVSTag.HEAD:
536                         return branchImage;
537                     case CVSTag.VERSION:
538                         return versionImage;
539                 }
540                 return null;
541             }
542             public String JavaDoc getText(Object JavaDoc element) {
543                 return ((CVSTag)element).getName();
544             }
545         });
546         result.setSorter(new ViewerSorter() {
547             public int compare(Viewer viewer, Object JavaDoc e1, Object JavaDoc e2) {
548                 if (!(e1 instanceof CVSTag) || !(e2 instanceof CVSTag)) return super.compare(viewer, e1, e2);
549                 CVSTag tag1 = (CVSTag)e1;
550                 CVSTag tag2 = (CVSTag)e2;
551                 int type1 = tag1.getType();
552                 int type2 = tag2.getType();
553                 if (type1 != type2) {
554                     return type2 - type1;
555                 }
556                 return super.compare(viewer, tag1, tag2);
557             }
558         });
559         return result;
560     }
561     protected TextViewer createText(Composite parent) {
562         TextViewer result = new TextViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.READ_ONLY);
563         result.addSelectionChangedListener(new ISelectionChangedListener() {
564             public void selectionChanged(SelectionChangedEvent event) {
565                 copyAction.update();
566             }
567         });
568         return result;
569     }
570     public void dispose() {
571         shutdown = true;
572         if (branchImage != null) {
573             branchImage.dispose();
574             branchImage = null;
575         }
576         if (versionImage != null) {
577             versionImage.dispose();
578             versionImage = null;
579         }
580         
581         if(fetchLogEntriesJob != null) {
582             if(fetchLogEntriesJob.getState() != Job.NONE) {
583                 fetchLogEntriesJob.cancel();
584                 try {
585                     fetchLogEntriesJob.join();
586                 } catch (InterruptedException JavaDoc e) {
587                     CVSUIPlugin.log(new CVSException(NLS.bind(CVSUIMessages.HistoryView_errorFetchingEntries, new String JavaDoc[] { "" }), e)); //$NON-NLS-1$ //$NON-NLS-2$
588
}
589             }
590         }
591         getSite().getPage().removePartListener(partListener);
592         getSite().getPage().removePartListener(partListener2);
593     }
594     /**
595      * Returns the table viewer contained in this view.
596      */

597     protected TableViewer getViewer() {
598         return tableViewer;
599     }
600     /**
601      * Adds drag and drop support to the history view.
602      */

603     void initDragAndDrop() {
604         int ops = DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
605         Transfer[] transfers = new Transfer[] {ResourceTransfer.getInstance(), CVSResourceTransfer.getInstance()};
606         tableViewer.addDropSupport(ops, transfers, new HistoryDropAdapter(tableViewer, this));
607     }
608     private void fillTableMenu(IMenuManager manager) {
609         // file actions go first (view file)
610
manager.add(new Separator(IWorkbenchActionConstants.GROUP_FILE));
611         if (file != null) {
612             // Add the "Add to Workspace" action if 1 revision is selected.
613
ISelection sel = tableViewer.getSelection();
614             if (!sel.isEmpty()) {
615                 if (sel instanceof IStructuredSelection) {
616                     if (((IStructuredSelection)sel).size() == 1) {
617                         manager.add(getContentsAction);
618                         manager.add(getRevisionAction);
619                         manager.add(new Separator());
620                         manager.add(tagWithExistingAction);
621                     }
622                 }
623             }
624         }
625         manager.add(new Separator("additions")); //$NON-NLS-1$
626
manager.add(refreshAction);
627         manager.add(new Separator("additions-end")); //$NON-NLS-1$
628
}
629     private void fillTextMenu(IMenuManager manager) {
630         manager.add(copyAction);
631         manager.add(selectAllAction);
632     }
633
634     /** (Non-javadoc)
635      * Method declared on IWorkbenchPart
636      */

637     public void setFocus() {
638         if (tableViewer != null) {
639             Table control = tableViewer.getTable();
640             if (control != null && !control.isDisposed()) {
641                 control.setFocus();
642             }
643         }
644     }
645     
646     /**
647      * Shows the history for the given IResource in the view.
648      *
649      * Only files are supported for now.
650      */

651     public void showHistory(IResource resource, boolean refetch) {
652         if (resource instanceof IFile) {
653             IFile newfile = (IFile)resource;
654             if(!refetch && this.file != null && newfile.equals(this.file)) {
655                 return;
656             }
657             this.file = newfile;
658             RepositoryProvider teamProvider = RepositoryProvider.getProvider(file.getProject(), CVSProviderPlugin.getTypeId());
659             if (teamProvider != null) {
660                 try {
661                     // for a file this will return the base
662
ICVSRemoteFile remoteFile = (ICVSRemoteFile)CVSWorkspaceRoot.getRemoteResourceFor(file);
663                     if(remoteFile != null) {
664                         historyTableProvider.setFile(remoteFile);
665                         // input is set asynchronously so we can't assume that the view
666
// has been populated until the job that queries for the history
667
// has completed.
668
tableViewer.setInput(remoteFile);
669                         setContentDescription(remoteFile.getName());
670                         setTitleToolTip(resource.getFullPath().toString());
671                     }
672                 } catch (TeamException e) {
673                     CVSUIPlugin.openError(getViewSite().getShell(), null, null, e);
674                 }
675             }
676         } else {
677             this.file = null;
678             tableViewer.setInput(null);
679             setContentDescription(""); //$NON-NLS-1$
680
setTitleToolTip(""); //$NON-NLS-1$
681
}
682     }
683     
684     /**
685      * An editor has been activated. Fetch the history if it is shared with CVS and the history view
686      * is visible in the current page.
687      *
688      * @param editor the active editor
689      * @since 3.0
690      */

691     protected void editorActivated(IEditorPart editor) {
692         // Only fetch contents if the view is shown in the current page.
693
if (editor == null || !isLinkingEnabled() || !checkIfPageIsVisible()) {
694             return;
695         }
696         IEditorInput input = editor.getEditorInput();
697         // Handle compare editors opened from the Synchronize View
698
if (input instanceof SyncInfoCompareInput) {
699             SyncInfoCompareInput syncInput = (SyncInfoCompareInput) input;
700             SyncInfo info = syncInput.getSyncInfo();
701             if(info instanceof CVSSyncInfo && info.getLocal().getType() == IResource.FILE) {
702                 // Highlight the loaded versions unless there isn't one
703
ICVSRemoteFile loaded;
704                 try {
705                     loaded = (ICVSRemoteFile)CVSWorkspaceRoot.getRemoteResourceFor(info.getLocal());
706                 } catch (CVSException e) {
707                     CVSUIPlugin.log(e);
708                     loaded = null;
709                 }
710                 if (loaded != null) {
711                     showHistory(loaded, false);
712                 } else {
713                     ICVSRemoteFile remote = (ICVSRemoteFile)info.getRemote();
714                     ICVSRemoteFile base = (ICVSRemoteFile)info.getBase();
715                     if(remote != null) {
716                         showHistory(remote, false);
717                     } else if(base != null) {
718                         showHistory(base, false);
719                     }
720                 }
721             }
722         // Handle editors opened on remote files
723
} else if(input instanceof RemoteFileEditorInput) {
724             ICVSRemoteFile remote = ((RemoteFileEditorInput)input).getCVSRemoteFile();
725             if(remote != null) {
726                 showHistory(remote, false);
727             }
728         // Handle regular file editors
729
} else {
730             IFile file = ResourceUtil.getFile(input);
731             if(file != null) {
732                 showHistory(file, false /* don't fetch if already cached */);
733             }
734         }
735     }
736     
737     private boolean checkIfPageIsVisible() {
738         return getViewSite().getPage().isPartVisible(this);
739     }
740     /**
741      * Shows the history for the given ICVSRemoteFile in the view.
742      */

743     public void showHistory(ICVSRemoteFile remoteFile, boolean refetch) {
744         try {
745             if (remoteFile == null) {
746                 tableViewer.setInput(null);
747                 setContentDescription(""); //$NON-NLS-1$
748
setTitleToolTip(""); //$NON-NLS-1$
749
return;
750             }
751             ICVSFile existingFile = historyTableProvider.getICVSFile();
752             if(!refetch && existingFile != null && existingFile.equals(remoteFile)) return;
753             this.file = null;
754             historyTableProvider.setFile(remoteFile);
755             tableViewer.setInput(remoteFile);
756             setContentDescription(remoteFile.getName());
757             setTitleToolTip(remoteFile.getRepositoryRelativePath());
758         } catch (TeamException e) {
759             CVSUIPlugin.openError(getViewSite().getShell(), null, null, e);
760         }
761     }
762     
763     private Action getContextMenuAction(String JavaDoc title, final boolean needsProgressDialog, final IWorkspaceRunnable action) {
764             return new Action(title) {
765             public void run() {
766                 try {
767                     if (file == null) return;
768                     ISelection selection = tableViewer.getSelection();
769                     if (!(selection instanceof IStructuredSelection)) return;
770                     IStructuredSelection ss = (IStructuredSelection)selection;
771                     Object JavaDoc o = ss.getFirstElement();
772                     currentSelection = (ILogEntry)o;
773                     if(needsProgressDialog) {
774                         PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
775                             public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
776                                 try {
777                                     action.run(monitor);
778                                 } catch (CoreException e) {
779                                     throw new InvocationTargetException JavaDoc(e);
780                                 }
781                             }
782                         });
783                     } else {
784                         try {
785                             action.run(null);
786                         } catch (CoreException e) {
787                             throw new InvocationTargetException JavaDoc(e);
788                         }
789                     }
790                 } catch (InvocationTargetException JavaDoc e) {
791                     CVSUIPlugin.openError(getViewSite().getShell(), null, null, e, CVSUIPlugin.LOG_NONTEAM_EXCEPTIONS);
792                 } catch (InterruptedException JavaDoc e) {
793                     // Do nothing
794
}
795             }
796             
797             public boolean isEnabled() {
798                 ISelection selection = tableViewer.getSelection();
799                 if (!(selection instanceof IStructuredSelection)) return false;
800                 IStructuredSelection ss = (IStructuredSelection)selection;
801                 if(ss.size() != 1) return false;
802                 return true;
803             }
804         };
805     }
806     
807     private boolean confirmOverwrite() {
808         if (file!=null && file.exists()) {
809             ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(file);
810             try {
811                 if(cvsFile.isModified(null)) {
812                     String JavaDoc title = CVSUIMessages.HistoryView_overwriteTitle; //$NON-NLS-1$
813
String JavaDoc msg = CVSUIMessages.HistoryView_overwriteMsg; //$NON-NLS-1$
814
final MessageDialog dialog = new MessageDialog(getViewSite().getShell(), title, null, msg, MessageDialog.QUESTION, new String JavaDoc[] { IDialogConstants.YES_LABEL, IDialogConstants.CANCEL_LABEL }, 0);
815                     final int[] result = new int[1];
816                     getViewSite().getShell().getDisplay().syncExec(new Runnable JavaDoc() {
817                     public void run() {
818                         result[0] = dialog.open();
819                     }});
820                     if (result[0] != 0) {
821                         // cancel
822
return false;
823                     }
824                 }
825             } catch(CVSException e) {
826                 CVSUIPlugin.log(e);
827             }
828         }
829         return true;
830     }
831     
832     /*
833      * Refresh the view by refetching the log entries for the remote file
834      */

835     private void refresh() {
836         entries = null;
837         BusyIndicator.showWhile(tableViewer.getTable().getDisplay(), new Runnable JavaDoc() {
838             public void run() {
839                 // if a local file was fed to the history view then we will have to refetch the handle
840
// to properly display the current revision marker.
841
if(file != null) {
842                      ICVSRemoteFile remoteFile;
843                     try {
844                         remoteFile = (ICVSRemoteFile) CVSWorkspaceRoot.getRemoteResourceFor(file);
845                         historyTableProvider.setFile(remoteFile);
846                     } catch (CVSException e) {
847                         // use previously fetched remote file, but log error
848
CVSUIPlugin.log(e);
849                     }
850                 }
851                 tableViewer.refresh();
852             }
853         });
854     }
855     
856     /**
857      * Select the revision in the receiver.
858      */

859     public void selectRevision(String JavaDoc revision) {
860         if (entries == null) {
861             return;
862         }
863     
864         ILogEntry entry = null;
865         for (int i = 0; i < entries.length; i++) {
866             if (entries[i].getRevision().equals(revision)) {
867                 entry = entries[i];
868                 break;
869             }
870         }
871     
872         if (entry != null) {
873             IStructuredSelection selection = new StructuredSelection(entry);
874             tableViewer.setSelection(selection, true);
875         }
876     }
877     
878     /**
879      * Enabled linking to the active editor
880      * @since 3.0
881      */

882     public void setLinkingEnabled(boolean enabled) {
883         this.linkingEnabled = enabled;
884
885         // remember the last setting in the dialog settings
886
settings.setValue(ICVSUIConstants.PREF_HISTORY_VIEW_EDITOR_LINKING, enabled);
887     
888         // if turning linking on, update the selection to correspond to the active editor
889
if (enabled) {
890             editorActivated(getSite().getPage().getActiveEditor());
891         }
892     }
893     
894     /**
895      * Returns if linking to the ative editor is enabled or disabled.
896      * @return boolean indicating state of editor linking.
897      */

898     private boolean isLinkingEnabled() {
899         return linkingEnabled;
900     }
901     
902     /*
903      * Flatten the text in the multiline comment
904      */

905     public static String JavaDoc flattenText(String JavaDoc string) {
906         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(string.length() + 20);
907         boolean skipAdjacentLineSeparator = true;
908         for (int i = 0; i < string.length(); i++) {
909             char c = string.charAt(i);
910             if (c == '\r' || c == '\n') {
911                 if (!skipAdjacentLineSeparator)
912                     buffer.append(CVSUIMessages.separator); //$NON-NLS-1$
913
skipAdjacentLineSeparator = true;
914             } else {
915                 buffer.append(c);
916                 skipAdjacentLineSeparator = false;
917             }
918         }
919         return buffer.toString();
920     }
921 }
922
Popular Tags