KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > team > internal > ui > history > LocalHistoryPage


1 /*******************************************************************************
2  * Copyright (c) 2006, 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.team.internal.ui.history;
12
13 import java.io.InputStream JavaDoc;
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.*;
16
17 import org.eclipse.compare.CompareConfiguration;
18 import org.eclipse.compare.ITypedElement;
19 import org.eclipse.compare.structuremergeviewer.DiffNode;
20 import org.eclipse.compare.structuremergeviewer.ICompareInput;
21 import org.eclipse.core.resources.*;
22 import org.eclipse.core.runtime.*;
23 import org.eclipse.core.runtime.jobs.Job;
24 import org.eclipse.jface.action.*;
25 import org.eclipse.jface.dialogs.IDialogConstants;
26 import org.eclipse.jface.dialogs.MessageDialog;
27 import org.eclipse.jface.operation.IRunnableWithProgress;
28 import org.eclipse.jface.preference.IPreferenceStore;
29 import org.eclipse.jface.util.IOpenEventListener;
30 import org.eclipse.jface.util.OpenStrategy;
31 import org.eclipse.jface.viewers.*;
32 import org.eclipse.osgi.util.NLS;
33 import org.eclipse.swt.SWT;
34 import org.eclipse.swt.events.SelectionAdapter;
35 import org.eclipse.swt.events.SelectionEvent;
36 import org.eclipse.swt.graphics.Image;
37 import org.eclipse.swt.layout.GridData;
38 import org.eclipse.swt.layout.GridLayout;
39 import org.eclipse.swt.widgets.*;
40 import org.eclipse.team.core.TeamException;
41 import org.eclipse.team.core.TeamStatus;
42 import org.eclipse.team.core.history.IFileHistory;
43 import org.eclipse.team.core.history.IFileRevision;
44 import org.eclipse.team.internal.core.history.LocalFileHistory;
45 import org.eclipse.team.internal.core.history.LocalFileRevision;
46 import org.eclipse.team.internal.ui.*;
47 import org.eclipse.team.internal.ui.actions.CompareRevisionAction;
48 import org.eclipse.team.internal.ui.actions.OpenRevisionAction;
49 import org.eclipse.team.internal.ui.synchronize.LocalResourceTypedElement;
50 import org.eclipse.team.ui.history.*;
51 import org.eclipse.team.ui.synchronize.SaveableCompareEditorInput;
52 import org.eclipse.ui.*;
53 import org.eclipse.ui.part.IPageSite;
54 import org.eclipse.ui.progress.IProgressConstants;
55
56 import com.ibm.icu.util.Calendar;
57
58 public class LocalHistoryPage extends HistoryPage implements IHistoryCompareAdapter {
59     
60     public static final int ON = 1;
61     public static final int OFF = 2;
62     public static final int ALWAYS = 4;
63     
64     /* private */ IFile file;
65     /* private */ IFileRevision currentFileRevision;
66     
67     // cached for efficiency
68
/* private */ LocalFileHistory localFileHistory;
69     
70     /* private */ TreeViewer treeViewer;
71     
72     /* private */boolean shutdown = false;
73     
74     //grouping on
75
private boolean groupingOn = true;
76
77     //toggle constants for default click action
78
private int compareMode = OFF;
79     
80     protected LocalFileHistoryTableProvider historyTableProvider;
81     private RefreshFileHistory refreshFileHistoryJob;
82     private Composite localComposite;
83     private Action groupByDateMode;
84     private Action collapseAll;
85     private Action compareModeAction;
86     private Action getContentsAction;
87     private CompareRevisionAction compareAction;
88     private OpenRevisionAction openAction;
89     
90     private HistoryResourceListener resourceListener;
91     
92     private IFileRevision currentSelection;
93     
94     private final class LocalHistoryContentProvider implements ITreeContentProvider {
95         public Object JavaDoc[] getElements(Object JavaDoc inputElement) {
96             if (inputElement instanceof IFileHistory) {
97                 // The entries of already been fetch so return them
98
IFileHistory fileHistory = (IFileHistory) inputElement;
99                 return fileHistory.getFileRevisions();
100             }
101             if (inputElement instanceof IFileRevision[]) {
102                 return (IFileRevision[]) inputElement;
103             }
104             if (inputElement instanceof AbstractHistoryCategory[]){
105                 return (AbstractHistoryCategory[]) inputElement;
106             }
107             return new Object JavaDoc[0];
108         }
109
110         public void dispose() {
111             // Nothing to do
112
}
113
114         public void inputChanged(Viewer viewer, Object JavaDoc oldInput, Object JavaDoc newInput) {
115             // Nothing to do
116
}
117
118         public Object JavaDoc[] getChildren(Object JavaDoc parentElement) {
119             if (parentElement instanceof AbstractHistoryCategory){
120                 return ((AbstractHistoryCategory) parentElement).getRevisions();
121             }
122             
123             return new Object JavaDoc[0];
124         }
125
126         public Object JavaDoc getParent(Object JavaDoc element) {
127             return null;
128         }
129
130         public boolean hasChildren(Object JavaDoc element) {
131             if (element instanceof AbstractHistoryCategory){
132                 return ((AbstractHistoryCategory) element).hasRevisions();
133             }
134             return false;
135         }
136     }
137
138     private class LocalFileHistoryTableProvider extends LocalHistoryTableProvider {
139         protected IFileRevision adaptToFileRevision(Object JavaDoc element) {
140             // Get the log entry for the provided object
141
IFileRevision entry = null;
142             if (element instanceof IFileRevision) {
143                 entry = (IFileRevision) element;
144             } else if (element instanceof IAdaptable) {
145                 entry = (IFileRevision) ((IAdaptable) element).getAdapter(IFileRevision.class);
146             } else if (element instanceof AbstractHistoryCategory){
147                 IFileRevision[] revisions = ((AbstractHistoryCategory) element).getRevisions();
148                 if (revisions.length > 0)
149                     entry = revisions[0];
150             }
151             return entry;
152         }
153         private long getCurrentRevision() {
154             if (file != null) {
155                 return file.getLocalTimeStamp();
156             }
157             return -1;
158         }
159         
160         protected long getModificationDate(Object JavaDoc element) {
161             IFileRevision entry = adaptToFileRevision(element);
162             if (entry != null)
163                 return entry.getTimestamp();
164             return -1;
165         }
166         
167         protected boolean isCurrentEdition(Object JavaDoc element) {
168             IFileRevision entry = adaptToFileRevision(element);
169             if (entry == null)
170                 return false;
171             long timestamp = entry.getTimestamp();
172             long tempCurrentTimeStamp = getCurrentRevision();
173             return (tempCurrentTimeStamp != -1 && tempCurrentTimeStamp==timestamp);
174         }
175         
176         protected boolean isDeletedEdition(Object JavaDoc element) {
177             IFileRevision entry = adaptToFileRevision(element);
178             return (!entry.exists());
179         }
180     }
181     
182     private class RefreshFileHistory extends Job {
183         public RefreshFileHistory() {
184             super(TeamUIMessages.LocalHistoryPage_FetchLocalHistoryMessage);
185         }
186         public IStatus run(IProgressMonitor monitor) {
187             try {
188                 IStatus status = Status.OK_STATUS;
189                 // Assign the instance variable to a local so it does not get cleared well we are refreshing
190
LocalFileHistory fileHistory = localFileHistory;
191                 if (fileHistory == null || shutdown)
192                     return status;
193                 try {
194                     fileHistory.refresh(Policy.subMonitorFor(monitor, 50));
195                 } catch (CoreException ex) {
196                     status = new TeamStatus(ex.getStatus().getSeverity(), TeamUIPlugin.ID, ex.getStatus().getCode(), ex.getMessage(), ex, file);
197                 }
198     
199                 update(fileHistory.getFileRevisions(), Policy.subMonitorFor(monitor, 50));
200     
201                 if (status != Status.OK_STATUS ) {
202                     this.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
203                     this.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE);
204                 }
205                 
206                 return status;
207             } finally {
208                 monitor.done();
209             }
210         }
211     }
212     
213     private class HistoryResourceListener implements IResourceChangeListener {
214         public void resourceChanged(IResourceChangeEvent event) {
215             IResourceDelta root = event.getDelta();
216         
217             if (file == null)
218                  return;
219             
220             IResourceDelta resourceDelta = root.findMember(file.getFullPath());
221             if (resourceDelta != null){
222                 Display.getDefault().asyncExec(new Runnable JavaDoc() {
223                     public void run() {
224                         refresh();
225                     }
226                 });
227             }
228         }
229     }
230     
231     public LocalHistoryPage(int compareMode) {
232         super();
233         this.compareMode = compareMode;
234     }
235     
236     public LocalHistoryPage() {
237         super();
238     }
239     
240     public boolean inputSet() {
241         currentFileRevision = null;
242         IFile tempFile = getFile();
243         this.file = tempFile;
244         if (tempFile == null)
245             return false;
246         
247         //blank current input only after we're sure that we have a file
248
//to fetch history for
249
this.treeViewer.setInput(null);
250         
251         localFileHistory = new LocalFileHistory(file, !getHistoryPageSite().isModal());
252         
253         if (refreshFileHistoryJob == null)
254             refreshFileHistoryJob = new RefreshFileHistory();
255         
256         //always refresh the history if the input gets set
257
refreshHistory(true);
258         return true;
259     }
260
261     protected IFile getFile() {
262         return LocalHistoryPageSource.getFile(getInput());
263     }
264
265     private void refreshHistory(boolean refetch) {
266         if (refreshFileHistoryJob.getState() != Job.NONE){
267             refreshFileHistoryJob.cancel();
268         }
269         IHistoryPageSite parentSite = getHistoryPageSite();
270         Utils.schedule(refreshFileHistoryJob, getWorkbenchSite(parentSite));
271     }
272
273     private IWorkbenchPartSite getWorkbenchSite(IHistoryPageSite parentSite) {
274         IWorkbenchPart part = parentSite.getPart();
275         if (part != null)
276             return part.getSite();
277         return null;
278     }
279     
280     public void createControl(Composite parent) {
281
282         localComposite = new Composite(parent, SWT.NONE);
283         GridLayout layout = new GridLayout();
284         layout.marginHeight = 0;
285         layout.marginWidth = 0;
286         localComposite.setLayout(layout);
287         GridData data = new GridData(GridData.FILL_BOTH);
288         data.grabExcessVerticalSpace = true;
289         localComposite.setLayoutData(data);
290         
291         treeViewer = createTree(localComposite);
292         
293         contributeActions();
294         
295         IHistoryPageSite parentSite = getHistoryPageSite();
296         if (parentSite != null && parentSite instanceof DialogHistoryPageSite && treeViewer != null)
297             parentSite.setSelectionProvider(treeViewer);
298         
299         resourceListener = new HistoryResourceListener();
300         ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener, IResourceChangeEvent.POST_CHANGE);
301         
302         PlatformUI.getWorkbench().getHelpSystem().setHelp(localComposite, IHelpContextIds.LOCAL_HISTORY_PAGE);
303     }
304
305     private void contributeActions() {
306         final IPreferenceStore store = TeamUIPlugin.getPlugin().getPreferenceStore();
307         //Group by Date
308
groupByDateMode = new Action(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)){
309             public void run() {
310                 groupingOn = !groupingOn;
311                 store.setValue(IPreferenceIds.PREF_GROUPBYDATE_MODE, groupingOn);
312                 refreshHistory(false);
313             }
314         };
315         groupingOn = store.getBoolean(IPreferenceIds.PREF_GROUPBYDATE_MODE);
316         groupByDateMode.setChecked(groupingOn);
317         groupByDateMode.setToolTipText(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateTip);
318         groupByDateMode.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY));
319         groupByDateMode.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY));
320         
321         //Collapse All
322
collapseAll = new Action(TeamUIMessages.LocalHistoryPage_CollapseAllAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)) {
323             public void run() {
324                 treeViewer.collapseAll();
325             }
326         };
327         collapseAll.setToolTipText(TeamUIMessages.LocalHistoryPage_CollapseAllTip);
328         collapseAll.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL));
329         collapseAll.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL));
330         
331         IHistoryPageSite historyPageSite = getHistoryPageSite();
332         if (!historyPageSite.isModal()) {
333             //Compare Mode Action
334
if ((compareMode & ALWAYS) == 0) {
335                 compareModeAction = new Action(TeamUIMessages.LocalHistoryPage_CompareModeAction,TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)) {
336                     public void run() {
337                         // switch the mode
338
compareMode = compareMode == ON ? OFF : ON;
339                         compareModeAction.setChecked(compareMode == ON);
340                     }
341                 };
342                 compareModeAction.setToolTipText(TeamUIMessages.LocalHistoryPage_CompareModeTip);
343                 compareModeAction.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW));
344                 compareModeAction.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW));
345                 compareModeAction.setChecked(compareMode == ON);
346                 
347                 getContentsAction = getContextMenuAction(TeamUIMessages.LocalHistoryPage_GetContents, true /* needs progress */, new IWorkspaceRunnable() {
348                     public void run(IProgressMonitor monitor) throws CoreException {
349                         monitor.beginTask(null, 100);
350                         try {
351                             if(confirmOverwrite()) {
352                                 IStorage currentStorage = currentSelection.getStorage(new SubProgressMonitor(monitor, 50));
353                                 InputStream JavaDoc in = currentStorage.getContents();
354                                 (file).setContents(in, false, true, new SubProgressMonitor(monitor, 50));
355                             }
356                         } catch (TeamException e) {
357                             throw new CoreException(e.getStatus());
358                         } finally {
359                             monitor.done();
360                         }
361                     }
362                 });
363             }
364             
365             //TODO: Doc help
366
//PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, );
367

368             // Click Compare action
369
compareAction = createCompareAction();
370             treeViewer.getTree().addSelectionListener(new SelectionAdapter(){
371                 public void widgetSelected(SelectionEvent e) {
372                     compareAction.setCurrentFileRevision(getCurrentFileRevision());
373                     compareAction.selectionChanged((IStructuredSelection) treeViewer.getSelection());
374                 }
375             });
376             compareAction.setPage(this);
377             
378             // Only add the open action if compare mode is not always on
379
if (!((compareMode & (ALWAYS | ON)) == (ALWAYS | ON))) {
380                 openAction = new OpenRevisionAction(TeamUIMessages.LocalHistoryPage_OpenAction);
381                 treeViewer.getTree().addSelectionListener(new SelectionAdapter(){
382                     public void widgetSelected(SelectionEvent e) {
383                         openAction.selectionChanged((IStructuredSelection) treeViewer.getSelection());
384                     }
385                 });
386                 openAction.setPage(this);
387             }
388             
389             OpenStrategy handler = new OpenStrategy(treeViewer.getTree());
390             handler.addOpenListener(new IOpenEventListener() {
391                 public void handleOpen(SelectionEvent e) {
392                     if (getSite() != null) {
393                         StructuredSelection tableStructuredSelection = (StructuredSelection) treeViewer.getSelection();
394                         if ((compareMode & ON) > 0){
395                             StructuredSelection sel = new StructuredSelection(new Object JavaDoc[] {getCurrentFileRevision(), tableStructuredSelection.getFirstElement()});
396                             compareAction.selectionChanged(sel);
397                             compareAction.run();
398                         } else {
399                             //Pass in the entire structured selection to allow for multiple editor openings
400
StructuredSelection sel = tableStructuredSelection;
401                             if (openAction != null) {
402                                 openAction.selectionChanged(sel);
403                                 openAction.run();
404                             }
405                         }
406                     }
407                 }
408             });
409             
410             //Contribute actions to popup menu
411
MenuManager menuMgr = new MenuManager();
412             Menu menu = menuMgr.createContextMenu(treeViewer.getTree());
413             menuMgr.addMenuListener(new IMenuListener() {
414                 public void menuAboutToShow(IMenuManager menuMgr) {
415                     fillTableMenu(menuMgr);
416                 }
417             });
418             menuMgr.setRemoveAllWhenShown(true);
419             treeViewer.getTree().setMenu(menu);
420             
421             //Don't add the object contribution menu items if this page is hosted in a dialog
422
IWorkbenchPart part = historyPageSite.getPart();
423             if (part != null) {
424                 IWorkbenchPartSite workbenchPartSite = part.getSite();
425                 workbenchPartSite.registerContextMenu(menuMgr, treeViewer);
426             }
427             IPageSite pageSite = historyPageSite.getWorkbenchPageSite();
428             if (pageSite != null) {
429                 IActionBars actionBars = pageSite.getActionBars();
430                 // Contribute toggle text visible to the toolbar drop-down
431
IMenuManager actionBarsMenu = actionBars.getMenuManager();
432                 if (actionBarsMenu != null){
433                     actionBarsMenu.removeAll();
434                 }
435                 actionBars.updateActionBars();
436             }
437         }
438
439         //Create the local tool bar
440
IToolBarManager tbm = historyPageSite.getToolBarManager();
441         if (tbm != null) {
442             String JavaDoc fileNameQualifier = getFileNameQualifier();
443             //Add groups
444
tbm.add(new Separator(fileNameQualifier+"grouping")); //$NON-NLS-1$
445
tbm.appendToGroup(fileNameQualifier+"grouping", groupByDateMode); //$NON-NLS-1$
446
tbm.add(new Separator(fileNameQualifier+"collapse")); //$NON-NLS-1$
447
tbm.appendToGroup(fileNameQualifier+"collapse", collapseAll); //$NON-NLS-1$
448
if (compareModeAction != null)
449                 tbm.appendToGroup(fileNameQualifier+"collapse", compareModeAction); //$NON-NLS-1$
450
tbm.update(false);
451         }
452         
453     }
454
455     protected CompareRevisionAction createCompareAction() {
456         return new CompareRevisionAction();
457     }
458
459     private String JavaDoc getFileNameQualifier() {
460         if (file != null)
461             return file.getFullPath().toString();
462         
463         return ""; //$NON-NLS-1$
464
}
465
466     protected void fillTableMenu(IMenuManager manager) {
467         // file actions go first (view file)
468
IHistoryPageSite parentSite = getHistoryPageSite();
469         manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
470         
471         if (file != null && !parentSite.isModal()){
472             if (openAction != null)
473                 manager.add(openAction);
474             if (compareAction != null)
475                 manager.add(compareAction);
476             if (getContentsAction != null) {
477                 ISelection sel = treeViewer.getSelection();
478                 if (!sel.isEmpty()) {
479                     if (sel instanceof IStructuredSelection) {
480                         IStructuredSelection tempSelection = (IStructuredSelection) sel;
481                         if (tempSelection.size() == 1) {
482                             manager.add(new Separator("getContents")); //$NON-NLS-1$
483
manager.add(getContentsAction);
484                         }
485                     }
486                 }
487             }
488         }
489     }
490
491     /**
492      * Creates the tree that displays the local file revisions
493      *
494      * @param parent the parent composite to contain the group
495      * @return the group control
496      */

497     protected TreeViewer createTree(Composite parent) {
498         historyTableProvider = new LocalFileHistoryTableProvider();
499         TreeViewer viewer = historyTableProvider.createTree(parent);
500         viewer.setContentProvider(new LocalHistoryContentProvider());
501         return viewer;
502     }
503
504     public Control getControl() {
505         return localComposite;
506     }
507
508     public void setFocus() {
509         localComposite.setFocus();
510     }
511
512     public String JavaDoc getDescription() {
513         if (getFile() != null)
514             return getFile().getFullPath().toString();
515         return null;
516     }
517
518     public String JavaDoc getName() {
519         if (getFile() != null)
520             return getFile().getName();
521         return ""; //$NON-NLS-1$
522
}
523
524     public boolean isValidInput(Object JavaDoc object) {
525         return (object instanceof IFile);
526     }
527
528     public void refresh() {
529         refreshHistory(true);
530     }
531
532     public Object JavaDoc getAdapter(Class JavaDoc adapter) {
533         if(adapter == IHistoryCompareAdapter.class) {
534             return this;
535         }
536         return null;
537     }
538
539     public void dispose() {
540         shutdown = true;
541
542         if (resourceListener != null){
543             ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener);
544             resourceListener = null;
545         }
546         
547         //Cancel any incoming
548
if (refreshFileHistoryJob != null) {
549             if (refreshFileHistoryJob.getState() != Job.NONE) {
550                 refreshFileHistoryJob.cancel();
551             }
552         }
553     }
554     
555     public IFileRevision getCurrentFileRevision() {
556         if (currentFileRevision != null)
557             return currentFileRevision;
558         
559         if (file != null)
560             currentFileRevision = new LocalFileRevision(file);
561         
562         return currentFileRevision;
563     }
564     
565     private Action getContextMenuAction(String JavaDoc title, final boolean needsProgressDialog, final IWorkspaceRunnable action) {
566         return new Action(title) {
567             public void run() {
568                 try {
569                     if (file == null) return;
570                     ISelection selection = treeViewer.getSelection();
571                     if (!(selection instanceof IStructuredSelection)) return;
572                     IStructuredSelection ss = (IStructuredSelection)selection;
573                     Object JavaDoc o = ss.getFirstElement();
574                     
575                     if (o instanceof AbstractHistoryCategory)
576                         return;
577                     
578                     currentSelection = (IFileRevision)o;
579                     if(needsProgressDialog) {
580                         PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
581                             public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
582                                 try {
583                                     action.run(monitor);
584                                 } catch (CoreException e) {
585                                     throw new InvocationTargetException JavaDoc(e);
586                                 }
587                             }
588                         });
589                     } else {
590                         try {
591                             action.run(null);
592                         } catch (CoreException e) {
593                             throw new InvocationTargetException JavaDoc(e);
594                         }
595                     }
596                 } catch (InvocationTargetException JavaDoc e) {
597                     IHistoryPageSite parentSite = getHistoryPageSite();
598                     Utils.handleError(parentSite.getShell(), e, null, null);
599                 } catch (InterruptedException JavaDoc e) {
600                     // Do nothing
601
}
602             }
603             
604             public boolean isEnabled() {
605                 ISelection selection = treeViewer.getSelection();
606                 if (!(selection instanceof IStructuredSelection)) return false;
607                 IStructuredSelection ss = (IStructuredSelection)selection;
608                 if(ss.size() != 1) return false;
609                 return true;
610             }
611         };
612     }
613
614     private boolean confirmOverwrite() {
615         if (file != null && file.exists()) {
616             String JavaDoc title = TeamUIMessages.LocalHistoryPage_OverwriteTitle;
617             String JavaDoc msg = TeamUIMessages.LocalHistoryPage_OverwriteMessage;
618             IHistoryPageSite parentSite = getHistoryPageSite();
619             final MessageDialog dialog = new MessageDialog(parentSite.getShell(), title, null, msg, MessageDialog.QUESTION, new String JavaDoc[] {IDialogConstants.YES_LABEL, IDialogConstants.CANCEL_LABEL}, 0);
620             final int[] result = new int[1];
621             parentSite.getShell().getDisplay().syncExec(new Runnable JavaDoc() {
622                 public void run() {
623                     result[0] = dialog.open();
624                 }
625             });
626             if (result[0] != 0) {
627                 // cancel
628
return false;
629             }
630         }
631         return true;
632     }
633     
634     public void setClickAction(boolean compare) {
635         compareMode = compare ? ON : OFF;
636         if (compareModeAction != null)
637             compareModeAction.setChecked(compareMode == ON);
638     }
639
640     public ICompareInput getCompareInput(Object JavaDoc object) {
641         if (object instanceof IFileRevision){
642             IFileRevision selectedFileRevision = (IFileRevision)object;
643             ITypedElement fileElement = SaveableCompareEditorInput.createFileElement((IFile) file);
644             FileRevisionTypedElement right = new FileRevisionTypedElement(selectedFileRevision);
645             DiffNode node = new DiffNode(fileElement, right);
646             return node;
647         }
648         return null;
649     }
650
651     /* (non-Javadoc)
652      * @see org.eclipse.team.ui.history.IHistoryCompareAdapter#prepareInput(org.eclipse.compare.structuremergeviewer.ICompareInput, org.eclipse.compare.CompareConfiguration, org.eclipse.core.runtime.IProgressMonitor)
653      */

654     public void prepareInput(ICompareInput input, CompareConfiguration configuration, IProgressMonitor monitor) {
655         Object JavaDoc right = input.getRight();
656         if (right != null) {
657             String JavaDoc label = getLabel(right);
658             if (label != null)
659                 configuration.setRightLabel(label);
660             Image image = getImage(right);
661             if (image != null)
662                 configuration.setRightImage(image);
663         }
664         Object JavaDoc left = input.getLeft();
665         if (left != null) {
666             String JavaDoc label = getLabel(left);
667             if (label != null)
668                 configuration.setLeftLabel(label);
669             Image image = getImage(left);
670             if (image != null)
671                 configuration.setLeftImage(image);
672         }
673     }
674
675     protected Image getImage(Object JavaDoc right) {
676         if (right instanceof FileRevisionTypedElement || right instanceof LocalFileRevision || right instanceof IFileRevision) {
677             return historyTableProvider.getRevisionImage();
678         }
679         if (right instanceof ITypedElement) {
680             ITypedElement te = (ITypedElement) right;
681             return te.getImage();
682         }
683         return null;
684     }
685
686     protected String JavaDoc getLabel(Object JavaDoc object) {
687         if (object instanceof IFileRevision) {
688             IFileRevision revision = (IFileRevision) object;
689             long timestamp = revision.getTimestamp();
690             if (timestamp > 0)
691             return NLS.bind(TeamUIMessages.LocalHistoryPage_0, historyTableProvider.getDateFormat().format(new Date(timestamp)));
692         }
693         if (object instanceof FileRevisionTypedElement) {
694             FileRevisionTypedElement e = (FileRevisionTypedElement) object;
695             return getLabel(e.getRevision());
696         }
697         if (object instanceof LocalResourceTypedElement) {
698             return TeamUIMessages.LocalHistoryPage_1;
699         }
700         return null;
701     }
702
703     /**
704      * Method invoked from a background thread to update the viewer with the given revisions.
705      * @param revisions the revisions for the file
706      * @param monitor a progress monitor
707      */

708     protected void update(final IFileRevision[] revisions, IProgressMonitor monitor) {
709         // Group the revisions (if appropriate) before running in the UI thread
710
final AbstractHistoryCategory[] categories = groupRevisions(revisions, monitor);
711         // Update the tree in the UI thread
712
Utils.asyncExec(new Runnable JavaDoc() {
713             public void run() {
714                 if (categories != null) {
715                     Object JavaDoc[] elementsToExpand = mapExpandedElements(categories, treeViewer.getExpandedElements());
716                     treeViewer.getTree().setRedraw(false);
717                     treeViewer.setInput(categories);
718                     //if user is switching modes and already has expanded elements
719
//selected try to expand those, else expand all
720
if (elementsToExpand.length > 0)
721                         treeViewer.setExpandedElements(elementsToExpand);
722                     else {
723                         treeViewer.expandAll();
724                         Object JavaDoc[] el = treeViewer.getExpandedElements();
725                         if (el != null && el.length > 0) {
726                             treeViewer.setSelection(new StructuredSelection(el[0]));
727                             treeViewer.getTree().deselectAll();
728                         }
729                     }
730                     treeViewer.getTree().setRedraw(true);
731                 } else {
732                     if (revisions.length > 0) {
733                         treeViewer.setInput(revisions);
734                     } else {
735                         treeViewer.setInput(new AbstractHistoryCategory[] {getErrorMessage()});
736                     }
737                 }
738             }
739         }, treeViewer);
740     }
741
742     private AbstractHistoryCategory[] groupRevisions(IFileRevision[] revisions, IProgressMonitor monitor) {
743         if (groupingOn)
744             return sortRevisions(revisions, monitor);
745         return null;
746     }
747     
748     private Object JavaDoc[] mapExpandedElements(AbstractHistoryCategory[] categories, Object JavaDoc[] expandedElements) {
749         //store the names of the currently expanded categories in a map
750
HashMap elementMap = new HashMap();
751         for (int i=0; i<expandedElements.length; i++){
752             elementMap.put(((DateHistoryCategory)expandedElements[i]).getName(), null);
753         }
754         
755         //Go through the new categories and keep track of the previously expanded ones
756
ArrayList expandable = new ArrayList();
757         for (int i = 0; i<categories.length; i++){
758             //check to see if this category is currently expanded
759
if (elementMap.containsKey(categories[i].getName())){
760                 expandable.add(categories[i]);
761             }
762         }
763         return (Object JavaDoc[]) expandable.toArray(new Object JavaDoc[expandable.size()]);
764     }
765
766     private AbstractHistoryCategory[] sortRevisions(IFileRevision[] revisions, IProgressMonitor monitor) {
767         
768         try {
769             monitor.beginTask(null, 100);
770             //Create the 4 categories
771
DateHistoryCategory[] tempCategories = new DateHistoryCategory[4];
772             //Get a calendar instance initialized to the current time
773
Calendar currentCal = Calendar.getInstance();
774             tempCategories[0] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Today, currentCal, null);
775             //Get yesterday
776
Calendar yesterdayCal = Calendar.getInstance();
777             yesterdayCal.roll(Calendar.DAY_OF_YEAR, -1);
778             tempCategories[1] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Yesterday, yesterdayCal, null);
779             //Get this month
780
Calendar monthCal = Calendar.getInstance();
781             monthCal.set(Calendar.DAY_OF_MONTH, 1);
782             tempCategories[2] = new DateHistoryCategory(TeamUIMessages.HistoryPage_ThisMonth, monthCal, yesterdayCal);
783             //Everything before after week is previous
784
tempCategories[3] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Previous, null, monthCal);
785         
786             ArrayList finalCategories = new ArrayList();
787             for (int i = 0; i<tempCategories.length; i++){
788                 tempCategories[i].collectFileRevisions(revisions, false);
789                 if (tempCategories[i].hasRevisions())
790                     finalCategories.add(tempCategories[i]);
791             }
792             
793             if (finalCategories.size() == 0){
794                 //no revisions found for the current mode, so add a message category
795
finalCategories.add(getErrorMessage());
796             }
797             
798             return (AbstractHistoryCategory[])finalCategories.toArray(new AbstractHistoryCategory[finalCategories.size()]);
799         } finally {
800             monitor.done();
801         }
802     }
803     
804     private MessageHistoryCategory getErrorMessage(){
805         MessageHistoryCategory messageCategory = new MessageHistoryCategory(getNoChangesMessage());
806         return messageCategory;
807     }
808
809     protected String JavaDoc getNoChangesMessage() {
810         return TeamUIMessages.LocalHistoryPage_NoRevisionsFound;
811     }
812 }
813
Popular Tags