KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > views > tasklist > TaskList


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 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  * Cagatay Kavukcuoglu <cagatayk@acm.org> - Filter for markers in same project
11  * Sebastian Davids <sdavids@gmx.de> - Reordered menu items
12  *******************************************************************************/

13
14 package org.eclipse.ui.views.tasklist;
15
16 import java.util.ArrayList JavaDoc;
17 import java.util.Arrays JavaDoc;
18 import java.util.Iterator JavaDoc;
19
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.resources.IWorkspace;
25 import org.eclipse.core.resources.IWorkspaceRoot;
26 import org.eclipse.core.resources.ResourcesPlugin;
27 import org.eclipse.core.runtime.Assert;
28 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.IAdaptable;
30 import org.eclipse.core.runtime.Platform;
31 import org.eclipse.jface.action.Action;
32 import org.eclipse.jface.action.IMenuListener;
33 import org.eclipse.jface.action.IMenuManager;
34 import org.eclipse.jface.action.IToolBarManager;
35 import org.eclipse.jface.action.MenuManager;
36 import org.eclipse.jface.action.Separator;
37 import org.eclipse.jface.dialogs.ErrorDialog;
38 import org.eclipse.jface.dialogs.IDialogSettings;
39 import org.eclipse.jface.viewers.CellEditor;
40 import org.eclipse.jface.viewers.CheckboxCellEditor;
41 import org.eclipse.jface.viewers.ColumnLayoutData;
42 import org.eclipse.jface.viewers.ColumnPixelData;
43 import org.eclipse.jface.viewers.ColumnWeightData;
44 import org.eclipse.jface.viewers.ComboBoxCellEditor;
45 import org.eclipse.jface.viewers.IBasicPropertyConstants;
46 import org.eclipse.jface.viewers.ICellModifier;
47 import org.eclipse.jface.viewers.IOpenListener;
48 import org.eclipse.jface.viewers.ISelection;
49 import org.eclipse.jface.viewers.ISelectionChangedListener;
50 import org.eclipse.jface.viewers.ISelectionProvider;
51 import org.eclipse.jface.viewers.IStructuredSelection;
52 import org.eclipse.jface.viewers.ITableLabelProvider;
53 import org.eclipse.jface.viewers.LabelProvider;
54 import org.eclipse.jface.viewers.OpenEvent;
55 import org.eclipse.jface.viewers.SelectionChangedEvent;
56 import org.eclipse.jface.viewers.StructuredSelection;
57 import org.eclipse.jface.viewers.TableLayout;
58 import org.eclipse.jface.viewers.TableViewer;
59 import org.eclipse.jface.viewers.TextCellEditor;
60 import org.eclipse.swt.SWT;
61 import org.eclipse.swt.accessibility.ACC;
62 import org.eclipse.swt.accessibility.AccessibleControlAdapter;
63 import org.eclipse.swt.accessibility.AccessibleControlEvent;
64 import org.eclipse.swt.custom.BusyIndicator;
65 import org.eclipse.swt.custom.StackLayout;
66 import org.eclipse.swt.custom.TableEditor;
67 import org.eclipse.swt.dnd.Clipboard;
68 import org.eclipse.swt.dnd.DND;
69 import org.eclipse.swt.dnd.DragSourceAdapter;
70 import org.eclipse.swt.dnd.DragSourceEvent;
71 import org.eclipse.swt.dnd.DragSourceListener;
72 import org.eclipse.swt.dnd.TextTransfer;
73 import org.eclipse.swt.dnd.Transfer;
74 import org.eclipse.swt.events.HelpEvent;
75 import org.eclipse.swt.events.HelpListener;
76 import org.eclipse.swt.events.KeyAdapter;
77 import org.eclipse.swt.events.KeyEvent;
78 import org.eclipse.swt.events.SelectionAdapter;
79 import org.eclipse.swt.events.SelectionEvent;
80 import org.eclipse.swt.events.SelectionListener;
81 import org.eclipse.swt.graphics.Image;
82 import org.eclipse.swt.layout.GridLayout;
83 import org.eclipse.swt.widgets.Composite;
84 import org.eclipse.swt.widgets.Control;
85 import org.eclipse.swt.widgets.Item;
86 import org.eclipse.swt.widgets.Label;
87 import org.eclipse.swt.widgets.Menu;
88 import org.eclipse.swt.widgets.Table;
89 import org.eclipse.swt.widgets.TableColumn;
90 import org.eclipse.ui.IActionBars;
91 import org.eclipse.ui.IEditorInput;
92 import org.eclipse.ui.IEditorPart;
93 import org.eclipse.ui.IMemento;
94 import org.eclipse.ui.IPageLayout;
95 import org.eclipse.ui.IPartListener;
96 import org.eclipse.ui.ISharedImages;
97 import org.eclipse.ui.IViewSite;
98 import org.eclipse.ui.IWorkbenchActionConstants;
99 import org.eclipse.ui.IWorkbenchPart;
100 import org.eclipse.ui.PartInitException;
101 import org.eclipse.ui.PlatformUI;
102 import org.eclipse.ui.actions.ActionFactory;
103 import org.eclipse.ui.ide.IDE;
104 import org.eclipse.ui.ide.ResourceUtil;
105 import org.eclipse.ui.internal.views.tasklist.TaskListMessages;
106 import org.eclipse.ui.part.CellEditorActionHandler;
107 import org.eclipse.ui.part.IShowInSource;
108 import org.eclipse.ui.part.IShowInTargetList;
109 import org.eclipse.ui.part.MarkerTransfer;
110 import org.eclipse.ui.part.ShowInContext;
111 import org.eclipse.ui.part.ViewPart;
112 import org.eclipse.ui.plugin.AbstractUIPlugin;
113
114 /**
115  * Main class for the Task List view for displaying tasks and problem annotations
116  * on resources, and for opening an editor on the resource when the user commands.
117  * <p>
118  * This standard view has id <code>"org.eclipse.ui.views.TaskList"</code>.
119  * </p>
120  * <p>
121  * The workbench will automatically instantiate this class when a Task List
122  * view is needed for a workbench window. This class is not intended
123  * to be instantiated or subclassed by clients.
124  * </p>
125  */

126 public class TaskList extends ViewPart {
127
128     private Table table;
129
130     private TaskSorter comparator;
131
132     private CellEditor descriptionEditor;
133
134     private TableViewer viewer;
135
136     private TasksFilter filter = new TasksFilter();
137
138     private IMemento memento;
139
140     private boolean markerLimitExceeded;
141
142     private Composite parent;
143
144     private StackLayout stackLayout = new StackLayout();
145
146     private Composite compositeMarkerLimitExceeded;
147
148     private CellEditorActionHandler editorActionHandler;
149
150     private TaskAction newTaskAction;
151
152     private TaskAction copyTaskAction;
153
154     private TaskAction pasteTaskAction;
155
156     private TaskAction removeTaskAction;
157
158     private TaskAction purgeCompletedAction;
159
160     private TaskAction gotoTaskAction;
161
162     private TaskAction selectAllAction;
163
164     private ResolveMarkerAction resolveMarkerAction;
165
166     private TaskAction filtersAction;
167
168     private MarkCompletedAction markCompletedAction;
169
170     private TaskAction propertiesAction;
171
172     //sort by action
173
private Action sortByCategoryAction;
174
175     private Action sortByCompletedAction;
176
177     private Action sortByPriorityAction;
178
179     private Action sortByDescriptionAction;
180
181     private Action sortByResourceAction;
182
183     private Action sortByContainerAction;
184
185     private Action sortByLocationAction;
186
187     private Action sortByCreationTimeAction;
188
189     private Action sortAscendingAction;
190
191     private Action sortDescendingAction;
192
193     private Clipboard clipboard;
194
195     private static String JavaDoc[] tableColumnProperties = {
196             IBasicPropertyConstants.P_IMAGE, IMarker.DONE, IMarker.PRIORITY,
197             IMarker.MESSAGE, IMarkerConstants.P_RESOURCE_NAME,
198             IMarkerConstants.P_CONTAINER_NAME,
199             IMarkerConstants.P_LINE_AND_LOCATION };
200
201     // Persistance tags.
202
private static final String JavaDoc TAG_COLUMN = "column"; //$NON-NLS-1$
203

204     private static final String JavaDoc TAG_NUMBER = "number"; //$NON-NLS-1$
205

206     private static final String JavaDoc TAG_WIDTH = "width"; //$NON-NLS-1$
207

208     private static final String JavaDoc TAG_FILTER = "filter"; //$NON-NLS-1$
209

210     private static final String JavaDoc TAG_SELECTION = "selection"; //$NON-NLS-1$
211

212     private static final String JavaDoc TAG_ID = "id"; //$NON-NLS-1$
213

214     private static final String JavaDoc TAG_MARKER = "marker"; //$NON-NLS-1$
215

216     private static final String JavaDoc TAG_RESOURCE = "resource"; //$NON-NLS-1$
217

218     private static final String JavaDoc TAG_TOP_INDEX = "topIndex"; //$NON-NLS-1$
219

220     private static final String JavaDoc TAG_SORT_SECTION = "TaskListSortState"; //$NON-NLS-1$
221

222     static class TaskListLabelProvider extends LabelProvider implements
223             ITableLabelProvider {
224
225         private static String JavaDoc[] keys = { IBasicPropertyConstants.P_IMAGE,
226                 IMarkerConstants.P_COMPLETE_IMAGE,
227                 IMarkerConstants.P_PRIORITY_IMAGE, IMarker.MESSAGE,
228                 IMarkerConstants.P_RESOURCE_NAME,
229                 IMarkerConstants.P_CONTAINER_NAME,
230                 IMarkerConstants.P_LINE_AND_LOCATION };
231
232         public String JavaDoc getColumnText(Object JavaDoc element, int columnIndex) {
233             if (columnIndex >= 3 && columnIndex <= 6) {
234                 return (String JavaDoc) MarkerUtil.getProperty(element,
235                         keys[columnIndex]);
236             }
237             return ""; //$NON-NLS-1$
238
}
239
240         public Image getColumnImage(Object JavaDoc element, int columnIndex) {
241             if (columnIndex >= 0 && columnIndex <= 2) {
242                 return (Image) MarkerUtil.getProperty(element,
243                         keys[columnIndex]);
244             }
245             return null;
246         }
247     }
248
249     class SortByAction extends Action {
250
251         private int column;
252
253         /**
254          * @param column
255          */

256         public SortByAction(int column) {
257             this.column = column;
258         }
259
260         public void run() {
261             comparator.setTopPriority(column);
262             updateSortingState();
263             viewer.refresh();
264             IDialogSettings workbenchSettings = getPlugin().getDialogSettings();
265             IDialogSettings settings = workbenchSettings
266                     .getSection(TAG_SORT_SECTION);
267             if (settings == null) {
268                 settings = workbenchSettings.addNewSection(TAG_SORT_SECTION);
269             }
270             comparator.saveState(settings);
271         }
272     }
273
274     class SortDirectionAction extends Action {
275
276         private int direction;
277
278         /**
279          * @param direction
280          */

281         public SortDirectionAction(int direction) {
282             this.direction = direction;
283         }
284
285         public void run() {
286             comparator.setTopPriorityDirection(direction);
287             updateSortingState();
288             viewer.refresh();
289             IDialogSettings workbenchSettings = getPlugin().getDialogSettings();
290             IDialogSettings settings = workbenchSettings
291                     .getSection(TAG_SORT_SECTION);
292             if (settings == null) {
293                 settings = workbenchSettings.addNewSection(TAG_SORT_SECTION);
294             }
295             comparator.saveState(settings);
296         }
297     }
298
299     private String JavaDoc columnHeaders[] = {
300             TaskListMessages.TaskList_headerIcon,
301             TaskListMessages.TaskList_headerCompleted,
302             TaskListMessages.TaskList_headerPriority,
303             TaskListMessages.TaskList_headerDescription,
304             TaskListMessages.TaskList_headerResource,
305             TaskListMessages.TaskList_headerFolder,
306             TaskListMessages.TaskList_headerLocation
307     };
308
309     private ColumnLayoutData columnLayouts[] = {
310             new ColumnPixelData(16, false, true), new ColumnPixelData(16, false, true),
311             new ColumnPixelData(16, false, true), new ColumnWeightData(200),
312             new ColumnWeightData(75), new ColumnWeightData(150),
313             new ColumnWeightData(60) };
314
315     private IPartListener partListener = new IPartListener() {
316         public void partActivated(IWorkbenchPart part) {
317             TaskList.this.partActivated(part);
318         }
319
320         public void partBroughtToTop(IWorkbenchPart part) {
321         }
322
323         public void partClosed(IWorkbenchPart part) {
324             TaskList.this.partClosed(part);
325         }
326
327         public void partDeactivated(IWorkbenchPart part) {
328         }
329
330         public void partOpened(IWorkbenchPart part) {
331         }
332     };
333
334     private ISelectionChangedListener focusSelectionChangedListener = new ISelectionChangedListener() {
335         public void selectionChanged(SelectionChangedEvent event) {
336             TaskList.this.focusSelectionChanged(event);
337         }
338     };
339
340     private IResource[] focusResources;
341
342     private IWorkbenchPart focusPart;
343
344     private ISelectionProvider focusSelectionProvider;
345
346     private ICellModifier cellModifier = new ICellModifier() {
347         public Object JavaDoc getValue(Object JavaDoc element, String JavaDoc property) {
348             return MarkerUtil.getProperty(element, property);
349         }
350
351         public boolean canModify(Object JavaDoc element, String JavaDoc property) {
352             return MarkerUtil.isEditable((IMarker) element);
353         }
354
355         /**
356          * Modifies a marker as a result of a successfully completed direct editing.
357          */

358         public void modify(Object JavaDoc element, String JavaDoc property, Object JavaDoc value) {
359             Item item = (Item) element;
360             IMarker marker = (IMarker) item.getData();
361             setProperty(marker, property, value);
362         }
363     };
364
365     /**
366      * Creates a new task list view.
367      */

368     public TaskList() {
369         super();
370     }
371
372     /**
373      * @param control
374      */

375     void addDragSupport(Control control) {
376
377         int operations = DND.DROP_COPY;
378         Transfer[] transferTypes = new Transfer[] {
379                 MarkerTransfer.getInstance(), TextTransfer.getInstance() };
380         DragSourceListener listener = new DragSourceAdapter() {
381             public void dragSetData(DragSourceEvent event) {
382                 performDragSetData(event);
383             }
384
385             public void dragFinished(DragSourceEvent event) {
386             }
387         };
388         viewer.addDragSupport(operations, transferTypes, listener);
389     }
390
391     void cancelEditing() {
392         getTableViewer().cancelEditing();
393     }
394
395     void createColumns() {
396         /**
397          * This class handles selections of the column headers.
398          * Selection of the column header will cause resorting
399          * of the shown tasks using that column's sorter.
400          * Repeated selection of the header will toggle
401          * sorting order (ascending versus descending).
402          */

403         SelectionListener headerListener = new SelectionAdapter() {
404             /**
405              * Handles the case of user selecting the
406              * header area.
407              * <p>If the column has not been selected previously,
408              * it will set the sorter of that column to be
409              * the current tasklist sorter. Repeated
410              * presses on the same column header will
411              * toggle sorting order (ascending/descending).
412              */

413             public void widgetSelected(SelectionEvent e) {
414                 // column selected - need to sort
415
int column = table.indexOf((TableColumn) e.widget);
416                 if (column == comparator.getTopPriority()) {
417                     comparator.reverseTopPriority();
418                 } else {
419                     comparator.setTopPriority(column);
420                 }
421                 updateSortingState();
422                 viewer.refresh();
423                 IDialogSettings workbenchSettings = getPlugin()
424                         .getDialogSettings();
425                 IDialogSettings settings = workbenchSettings
426                         .getSection(TAG_SORT_SECTION);
427                 if (settings == null) {
428                     settings = workbenchSettings
429                             .addNewSection(TAG_SORT_SECTION);
430                 }
431                 comparator.saveState(settings);
432             }
433         };
434
435         if (memento != null) {
436             //restore columns width
437
IMemento children[] = memento.getChildren(TAG_COLUMN);
438             if (children != null) {
439                 for (int i = 0; i < children.length; i++) {
440                     Integer JavaDoc val = children[i].getInteger(TAG_NUMBER);
441                     if (val != null) {
442                         int index = val.intValue();
443                         val = children[i].getInteger(TAG_WIDTH);
444                         if (val != null) {
445                             columnLayouts[index] = new ColumnPixelData(val
446                                     .intValue(), true);
447                         }
448                     }
449                 }
450             }
451         }
452
453         boolean text = "carbon".equals(SWT.getPlatform()); //$NON-NLS-1$
454
TableLayout layout = new TableLayout();
455         table.setLayout(layout);
456         table.setHeaderVisible(true);
457
458         for (int i = 0; i < columnHeaders.length; i++) {
459             TableColumn tc = new TableColumn(table, SWT.NONE, i);
460
461             if (!text && i == 1) {
462                 tc.setImage(MarkerUtil.getImage("header_complete")); //$NON-NLS-1$
463
} else if (!text && i == 2) {
464                 tc.setImage(MarkerUtil.getImage("header_priority")); //$NON-NLS-1$
465
} else {
466                 tc.setText(columnHeaders[i]);
467             }
468
469             if (text && (i == 1 || i == 2)) {
470                 tc.pack();
471                 columnLayouts[i] = new ColumnPixelData(Math.max(16, tc
472                         .getWidth()), false, true);
473             }
474
475             tc.setResizable(columnLayouts[i].resizable);
476             layout.addColumnData(columnLayouts[i]);
477             tc.addSelectionListener(headerListener);
478         }
479     }
480
481     /**
482      * Returns a string that summarizes the contents of the
483      * given markers.
484      */

485     static String JavaDoc createMarkerReport(IMarker[] markers) {
486         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
487         // Create the header
488
buf.append(TaskListMessages.TaskList_reportKind);
489         buf.append("\t"); //$NON-NLS-1$
490
buf.append(TaskListMessages.TaskList_reportStatus);
491         buf.append("\t"); //$NON-NLS-1$
492
buf.append(TaskListMessages.TaskList_reportPriority);
493         buf.append("\t"); //$NON-NLS-1$
494
buf.append(TaskListMessages.TaskList_headerDescription);
495         buf.append("\t"); //$NON-NLS-1$
496
buf.append(TaskListMessages.TaskList_headerResource);
497         buf.append("\t"); //$NON-NLS-1$
498
buf.append(TaskListMessages.TaskList_headerFolder);
499         buf.append("\t"); //$NON-NLS-1$
500
buf.append(TaskListMessages.TaskList_headerLocation);
501         buf.append(System.getProperty("line.separator")); //$NON-NLS-1$
502

503         // Create the report for the markers
504
for (int i = 0; i < markers.length; i++) {
505             writeMarker(buf, markers[i]);
506         }
507         return buf.toString();
508     }
509
510     /**
511      * Writes a string representation of the given marker to the buffer.
512      */

513     static void writeMarker(StringBuffer JavaDoc buf, IMarker marker) {
514         buf.append(MarkerUtil.getKindText(marker));
515         buf.append("\t"); //$NON-NLS-1$
516
buf.append(MarkerUtil.getCompleteText(marker));
517         buf.append("\t"); //$NON-NLS-1$
518
buf.append(MarkerUtil.getPriorityText(marker));
519         buf.append("\t"); //$NON-NLS-1$
520
buf.append(MarkerUtil.getMessage(marker));
521         buf.append("\t"); //$NON-NLS-1$
522
buf.append(MarkerUtil.getResourceName(marker));
523         buf.append("\t"); //$NON-NLS-1$
524
buf.append(MarkerUtil.getContainerName(marker));
525         buf.append("\t"); //$NON-NLS-1$
526
buf.append(MarkerUtil.getLineAndLocation(marker));
527         buf.append(System.getProperty("line.separator")); //$NON-NLS-1$
528
}
529
530     /* package */
531     boolean isMarkerLimitExceeded() {
532         return markerLimitExceeded;
533     }
534
535     /* package */
536     void setMarkerLimitExceeded(boolean markerLimitExceeded) {
537         this.markerLimitExceeded = markerLimitExceeded;
538
539         if (markerLimitExceeded) {
540             stackLayout.topControl = compositeMarkerLimitExceeded;
541         } else {
542             stackLayout.topControl = table;
543         }
544
545         parent.layout();
546     }
547
548     /* (non-Javadoc)
549      * Method declared on IWorkbenchPart.
550      */

551     public void createPartControl(Composite parent) {
552         // long t = System.currentTimeMillis();
553
createPartControl0(parent);
554         // t = System.currentTimeMillis() - t;
555
// System.out.println("TaskList.createPartControl: " + t + "ms");
556
}
557
558     private void createPartControl0(Composite parent) {
559         this.parent = parent;
560         clipboard = new Clipboard(parent.getDisplay());
561         createTable(parent);
562         viewer = new TableViewer(table);
563         viewer.setUseHashlookup(true);
564         createColumns();
565         makeActions();
566         fillActionBars();
567         addDragSupport(table);
568
569         compositeMarkerLimitExceeded = new Composite(parent, SWT.NONE);
570         compositeMarkerLimitExceeded.setLayout(new GridLayout());
571         Label labelMarkerLimitExceeded = new Label(
572                 compositeMarkerLimitExceeded, SWT.WRAP);
573         labelMarkerLimitExceeded.setText(TaskListMessages.TaskList_markerLimitExceeded);
574         parent.setLayout(stackLayout);
575         setMarkerLimitExceeded(false);
576
577         viewer.setContentProvider(new TaskListContentProvider(this));
578         viewer.setLabelProvider(new TaskListLabelProvider());
579         if (memento != null) {
580             //restore filter
581
IMemento filterMem = memento.getChild(TAG_FILTER);
582             if (filterMem != null) {
583                 getFilter().restoreState(filterMem);
584             }
585         }
586
587         comparator = new TaskSorter();
588         IDialogSettings workbenchSettings = getPlugin().getDialogSettings();
589         IDialogSettings settings = workbenchSettings
590                 .getSection(TAG_SORT_SECTION);
591         comparator.restoreState(settings);
592         viewer.setComparator(comparator);
593
594         //update the menu to indicate how task are currently sorted
595
updateSortingState();
596         viewer.setInput(getWorkspace().getRoot());
597         viewer.addSelectionChangedListener(new ISelectionChangedListener() {
598             public void selectionChanged(SelectionChangedEvent event) {
599                 TaskList.this.selectionChanged(event);
600             }
601         });
602         viewer.addOpenListener(new IOpenListener() {
603             public void open(OpenEvent event) {
604                 gotoTaskAction.run();
605             }
606         });
607         viewer.getControl().addKeyListener(new KeyAdapter() {
608             public void keyPressed(KeyEvent e) {
609                 handleKeyPressed(e);
610             }
611         });
612
613         //Add in some accessibility support to supplement the description that we already
614
//get from the SWT table.
615
viewer.getControl().getAccessible().addAccessibleControlListener(
616                 new AccessibleControlAdapter() {
617
618                     /* (non-Javadoc)
619                      * @see org.eclipse.swt.accessibility.AccessibleControlListener#getValue(org.eclipse.swt.accessibility.AccessibleControlEvent)
620                      */

621                     public void getValue(AccessibleControlEvent e) {
622
623                         int childIndex = e.childID;
624
625                         if (childIndex == ACC.CHILDID_SELF) {
626                             super.getValue(e);
627                             return;
628                         }
629                         Object JavaDoc item = viewer.getElementAt(childIndex);
630                         if (item instanceof IMarker) {
631                             IMarker marker = (IMarker) item;
632
633                             //If it is editable all we need is completeness
634
// the rest is found by the table accessibility
635
if (MarkerUtil.isEditable(marker)) {
636                                 e.result = MarkerUtil.getCompleteText(marker);
637                             } else {
638                                 //Otherwise all it needs is severity
639
e.result = MarkerUtil.getKindText(marker);
640                             }
641
642                         } else {
643                             super.getValue(e);
644                             return;
645                         }
646
647                     }
648
649                 });
650
651         CellEditor editors[] = new CellEditor[columnHeaders.length];
652         editors[1] = new CheckboxCellEditor(table);
653         String JavaDoc[] priorities = new String JavaDoc[] {
654                 TaskListMessages.TaskList_high,
655                 TaskListMessages.TaskList_normal,
656                 TaskListMessages.TaskList_low
657         };
658         editors[2] = new ComboBoxCellEditor(table, priorities, SWT.READ_ONLY);
659         editors[3] = descriptionEditor = new TextCellEditor(table);
660         viewer.setCellEditors(editors);
661         viewer.setCellModifier(cellModifier);
662         viewer.setColumnProperties(tableColumnProperties);
663
664         // Configure the context menu to be lazily populated on each pop-up.
665
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
666
menuMgr.setRemoveAllWhenShown(true);
667         menuMgr.addMenuListener(new IMenuListener() {
668             public void menuAboutToShow(IMenuManager manager) {
669                 TaskList.this.fillContextMenu(manager);
670             }
671         });
672         Menu menu = menuMgr.createContextMenu(table);
673         table.setMenu(menu);
674         // Be sure to register it so that other plug-ins can add actions.
675
getSite().registerContextMenu(menuMgr, viewer);
676
677         // Track selection in the page.
678
getSite().getPage().addPartListener(partListener);
679
680         // Add global action handlers.
681
editorActionHandler = new CellEditorActionHandler(getViewSite()
682                 .getActionBars());
683         editorActionHandler.addCellEditor(descriptionEditor);
684         editorActionHandler.setCopyAction(copyTaskAction);
685         editorActionHandler.setPasteAction(pasteTaskAction);
686         editorActionHandler.setDeleteAction(removeTaskAction);
687         editorActionHandler.setSelectAllAction(selectAllAction);
688
689         getViewSite().getActionBars().setGlobalActionHandler(
690                 ActionFactory.PROPERTIES.getId(), propertiesAction);
691
692         getSite().setSelectionProvider(viewer);
693
694         if (memento != null) {
695             restoreState(memento);
696         }
697         memento = null;
698
699         // Set help on the view itself
700
viewer.getControl().addHelpListener(new HelpListener() {
701             /*
702              * @see HelpListener#helpRequested(HelpEvent)
703              */

704             public void helpRequested(HelpEvent e) {
705                 String JavaDoc contextId = null;
706                 // See if there is a context registered for the current selection
707
IMarker marker = (IMarker) ((IStructuredSelection) getSelection())
708                         .getFirstElement();
709                 if (marker != null) {
710                     contextId = IDE.getMarkerHelpRegistry().getHelp(marker);
711                 }
712
713                 if (contextId == null) {
714                     contextId = ITaskListHelpContextIds.TASK_LIST_VIEW;
715                 }
716
717                 getSite().getWorkbenchWindow().getWorkbench().getHelpSystem()
718                         .displayHelp(contextId);
719             }
720         });
721
722         // Prime the status line and title.
723
updateStatusMessage();
724         updateTitle();
725     }
726
727     /**
728      * Creates the table control.
729      */

730     void createTable(Composite parent) {
731         table = new Table(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI
732                 | SWT.FULL_SELECTION);
733         table.setLinesVisible(true);
734         //table.setLayout(new TableLayout());
735

736         new TableEditor(table);
737     }
738
739     /* (non-Javadoc)
740      * Method declared on IWorkbenchPart.
741      */

742     public void dispose() {
743         super.dispose();
744         getSite().getPage().removePartListener(partListener);
745         if (focusSelectionProvider != null) {
746             focusSelectionProvider
747                     .removeSelectionChangedListener(focusSelectionChangedListener);
748             focusSelectionProvider = null;
749         }
750         focusPart = null;
751         if (editorActionHandler != null) {
752             editorActionHandler.dispose();
753             editorActionHandler = null;
754         }
755         if (clipboard != null) {
756             clipboard.dispose();
757         }
758     }
759
760     /**
761      * Activates the editor on the given marker.
762      *
763      * @param marker the marker to edit
764      */

765     public void edit(IMarker marker) {
766         viewer.editElement(marker, 3);
767     }
768
769     /**
770      * Fills the local tool bar and menu manager with actions.
771      */

772     void fillActionBars() {
773         IActionBars actionBars = getViewSite().getActionBars();
774         IMenuManager menu = actionBars.getMenuManager();
775         IMenuManager submenu = new MenuManager(TaskListMessages.SortByMenu_text);
776
777         menu.add(submenu);
778         submenu.add(sortByCategoryAction);
779         submenu.add(sortByCompletedAction);
780         submenu.add(sortByPriorityAction);
781         submenu.add(sortByDescriptionAction);
782         submenu.add(sortByResourceAction);
783         submenu.add(sortByContainerAction);
784         submenu.add(sortByLocationAction);
785         submenu.add(sortByCreationTimeAction);
786         submenu.add(new Separator());
787         submenu.add(sortAscendingAction);
788         submenu.add(sortDescendingAction);
789
790         menu.add(filtersAction);
791
792         IToolBarManager toolBar = actionBars.getToolBarManager();
793         toolBar.add(newTaskAction);
794         toolBar.add(removeTaskAction);
795         toolBar.add(filtersAction);
796     }
797
798     /**
799      * Contributes actions to the pop-up menu.
800      */

801     void fillContextMenu(IMenuManager menu) {
802         // update enabled state for actions that aren't updated in selectionChanged
803
IStructuredSelection selection = (IStructuredSelection) getSelection();
804         markCompletedAction.setEnabled(markCompletedAction
805                 .shouldEnable(selection));
806         resolveMarkerAction.setEnabled(resolveMarkerAction
807                 .shouldEnable(selection));
808
809         // add the actions to the menu
810
menu.add(newTaskAction);
811         menu.add(gotoTaskAction);
812         menu.add(new Separator());
813         menu.add(copyTaskAction);
814         menu.add(pasteTaskAction);
815         menu.add(removeTaskAction);
816         menu.add(new Separator());
817         menu.add(markCompletedAction);
818         menu.add(purgeCompletedAction);
819         menu.add(new Separator());
820         menu.add(resolveMarkerAction);
821         menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
822         menu
823                 .add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS
824                         + "-end")); //$NON-NLS-1$
825
menu.add(propertiesAction);
826     }
827
828     /**
829      * The filter settings have changed.
830      * Refreshes the viewer and title bar.
831      */

832     void filterChanged() {
833
834         BusyIndicator.showWhile(viewer.getControl().getShell().getDisplay(),
835                 new Runnable JavaDoc() {
836                     public void run() {
837                         // Filter has already been updated by dialog; just refresh.
838
// Don't need to update labels for existing elements
839
// since changes to filter settings don't affect them.
840
viewer.getControl().setRedraw(false);
841                         viewer.refresh(false);
842                         viewer.getControl().setRedraw(true);
843                         // update after refresh since the content provider caches summary info
844
updateStatusMessage();
845                         updateTitle();
846                     }
847                 });
848
849     }
850
851     void focusSelectionChanged(SelectionChangedEvent event) {
852         updateFocusResource(event.getSelection());
853     }
854
855     /* (non-Javadoc)
856      * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
857      */

858     public Object JavaDoc getAdapter(Class JavaDoc adapter) {
859         if (adapter == IShowInSource.class) {
860             return new IShowInSource() {
861                 public ShowInContext getShowInContext() {
862                     return new ShowInContext(null, getSelection());
863                 }
864             };
865         }
866         if (adapter == IShowInTargetList.class) {
867             return new IShowInTargetList() {
868                 public String JavaDoc[] getShowInTargetIds() {
869                     return new String JavaDoc[] { IPageLayout.ID_RES_NAV };
870                 }
871
872             };
873         }
874         return super.getAdapter(adapter);
875     }
876
877     /**
878      * Returns a clipboard for cut/copy/paste actions.
879      * <p>
880      * May only be called after this part's viewer has been created.
881      * The clipboard is disposed when this part is disposed.
882      * </p>
883      * @return a clipboard
884      * @since 2.0
885      */

886     /*package*/
887     Clipboard getClipboard() {
888         return clipboard;
889     }
890
891     /**
892      * Returns the filter for the viewer.
893      */

894     TasksFilter getFilter() {
895         return filter;
896     }
897
898     /**
899      * Returns the UI plugin for the task list.
900      */

901     static AbstractUIPlugin getPlugin() {
902         return (AbstractUIPlugin) Platform.getPlugin(PlatformUI.PLUGIN_ID);
903     }
904
905     /**
906      * Returns the resource for which the task list is showing tasks.
907      *
908      * @return the resource, possibly the workspace root
909      */

910     public IResource getResource() {
911         if (showSelections()) {
912             if (focusResources != null && focusResources.length >= 1
913                     && focusResources[0] != null) {
914                 return focusResources[0];
915             }
916         }
917
918         return getWorkspace().getRoot();
919     }
920
921     /**
922      * Get the resources.
923      *
924      * @return the resources
925      */

926     public IResource[] getResources() {
927         if (showSelections()) {
928             if (focusResources != null) {
929                 return focusResources;
930             }
931         }
932
933         return new IResource[] { getWorkspace().getRoot() };
934     }
935
936     /**
937      * Returns the resource depth which the task list is using to show tasks.
938      *
939      * @return an <code>IResource.DEPTH_*</code> constant
940      */

941     int getResourceDepth() {
942         if (showSelections() && !showChildrenHierarchy()) {
943             return IResource.DEPTH_ZERO;
944         }
945
946         return IResource.DEPTH_INFINITE;
947     }
948
949     /**
950      * API method which returns the current selection.
951      *
952      * @return the current selection (element type: <code>IMarker</code>)
953      */

954     public ISelection getSelection() {
955         return viewer.getSelection();
956     }
957
958     /**
959      * Returns the message to display in the status line.
960      */

961     String JavaDoc getStatusMessage(IStructuredSelection selection) {
962         if (selection != null && selection.size() == 1) {
963             IMarker marker = (IMarker) selection.getFirstElement();
964             return MarkerUtil.getMessage(marker);
965         }
966
967         TaskListContentProvider provider = (TaskListContentProvider) viewer
968                 .getContentProvider();
969
970         if (selection != null && selection.size() > 1) {
971             return provider.getStatusSummarySelected(selection);
972         }
973         return provider.getStatusSummaryVisible();
974     }
975
976     /**
977      * When created, new task instance is cached in
978      * order to keep it at the top of the list until
979      * first edited. This method returns it, or
980      * null if there is no task instance pending
981      * for first editing.
982      */

983     TableViewer getTableViewer() {
984         return viewer;
985     }
986
987     /**
988      * Returns the workspace.
989      */

990     IWorkspace getWorkspace() {
991         return ResourcesPlugin.getWorkspace();
992     }
993
994     /**
995      * Handles key events in viewer.
996      */

997     void handleKeyPressed(KeyEvent event) {
998         if (event.character == SWT.DEL && event.stateMask == 0
999                 && removeTaskAction.isEnabled()) {
1000            removeTaskAction.run();
1001        }
1002    }
1003
1004    /* (non-Javadoc)
1005     * Method declared on IViewPart.
1006     */

1007    public void init(IViewSite site, IMemento memento) throws PartInitException {
1008        super.init(site, memento);
1009        this.memento = memento;
1010    }
1011
1012    /**
1013     * Returns whether we are interested in markers on the given resource.
1014     */

1015    boolean checkResource(IResource resource) {
1016        if (!showSelections()) {
1017            return true;
1018        }
1019
1020        IResource[] resources = getResources();
1021        IResource resource2;
1022
1023        if (showOwnerProject()) {
1024            IProject project;
1025
1026            for (int i = 0, l = resources.length; i < l; i++) {
1027                resource2 = resources[i];
1028
1029                if (resource2 == null) {
1030                    return true;
1031                }
1032                project = resource2.getProject();
1033
1034                if (project == null
1035                        || project.equals(resource.getProject())) {
1036                    return true;
1037                }
1038            }
1039        }
1040
1041        if (showChildrenHierarchy()) {
1042            for (int i = 0, l = resources.length; i < l; i++) {
1043                resource2 = resources[i];
1044
1045                if (resource2 != null
1046                        && resource2.getFullPath().isPrefixOf(
1047                                resource.getFullPath())) {
1048                    return true;
1049                }
1050            }
1051        } else {
1052            for (int i = 0, l = resources.length; i < l; i++) {
1053                resource2 = resources[i];
1054
1055                if (resource.equals(resource2)) {
1056                    return true;
1057                }
1058            }
1059        }
1060
1061        return false;
1062    }
1063
1064    /**
1065     * Returns whether the given marker should be shown,
1066     * given the current filter settings.
1067     */

1068    boolean shouldShow(IMarker marker) {
1069        return checkResource(marker.getResource())
1070                && getFilter().select(marker);
1071    }
1072
1073    /**
1074     * Makes actions used in the local tool bar and
1075     * popup menu.
1076     */

1077    void makeActions() {
1078        ISharedImages sharedImages = PlatformUI.getWorkbench()
1079                .getSharedImages();
1080
1081        // goto
1082
gotoTaskAction = new GotoTaskAction(this, "gotoFile"); //$NON-NLS-1$
1083
gotoTaskAction.setText(TaskListMessages.GotoTask_text);
1084        gotoTaskAction.setToolTipText(TaskListMessages.GotoTask_tooltip);
1085        gotoTaskAction.setImageDescriptor(MarkerUtil
1086                .getImageDescriptor("gotoobj")); //$NON-NLS-1$
1087
gotoTaskAction.setEnabled(false);
1088
1089        // new task
1090
newTaskAction = new NewTaskAction(this, "newTask"); //$NON-NLS-1$
1091
newTaskAction.setText(TaskListMessages.NewTask_text);
1092        newTaskAction.setToolTipText(TaskListMessages.NewTask_tooltip);
1093        newTaskAction.setImageDescriptor(MarkerUtil
1094                .getImageDescriptor("addtsk")); //$NON-NLS-1$
1095
newTaskAction.setDisabledImageDescriptor(MarkerUtil
1096                .getImageDescriptor("addtsk_disabled")); //$NON-NLS-1$
1097

1098        // copy task
1099
copyTaskAction = new CopyTaskAction(this, "copy"); //$NON-NLS-1$
1100
copyTaskAction.setText(TaskListMessages.CopyTask_text);
1101        copyTaskAction.setToolTipText(TaskListMessages.CopyTask_tooltip);
1102        copyTaskAction.setEnabled(false);
1103
1104        // paste task
1105
pasteTaskAction = new PasteTaskAction(this, "paste"); //$NON-NLS-1$
1106
pasteTaskAction.setText(TaskListMessages.PasteTask_text);
1107        pasteTaskAction.setToolTipText(TaskListMessages.PasteTask_tooltip);
1108        pasteTaskAction.setEnabled(false);
1109
1110        // remove task
1111
removeTaskAction = new RemoveTaskAction(this, "delete"); //$NON-NLS-1$
1112
removeTaskAction.setText(TaskListMessages.RemoveTask_text);
1113        removeTaskAction.setToolTipText(TaskListMessages.RemoveTask_tooltip);
1114        removeTaskAction.setImageDescriptor(sharedImages
1115                .getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
1116        removeTaskAction.setDisabledImageDescriptor(sharedImages
1117                .getImageDescriptor(ISharedImages.IMG_TOOL_DELETE_DISABLED));
1118        removeTaskAction.setEnabled(false);
1119
1120        //mark completed task
1121
markCompletedAction = new MarkCompletedAction(this, "markCompleted"); //$NON-NLS-1$
1122
markCompletedAction.setText(TaskListMessages.MarkCompleted_text);
1123        markCompletedAction.setToolTipText(TaskListMessages.MarkCompleted_tooltip);
1124        markCompletedAction.setEnabled(false);
1125
1126        //delete completed task
1127
purgeCompletedAction = new PurgeCompletedAction(this, "deleteCompleted"); //$NON-NLS-1$
1128
purgeCompletedAction.setText(TaskListMessages.PurgeCompleted_text);
1129        purgeCompletedAction.setToolTipText(TaskListMessages.PurgeCompleted_tooltip);
1130        purgeCompletedAction.setImageDescriptor(sharedImages
1131                .getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
1132        purgeCompletedAction.setEnabled(true);
1133
1134        // select all
1135
selectAllAction = new SelectAllTasksAction(this, "selectAll"); //$NON-NLS-1$
1136
selectAllAction.setText(TaskListMessages.SelectAll_text);
1137        selectAllAction.setToolTipText(TaskListMessages.SelectAll_tooltip);
1138
1139        // resolutions
1140
resolveMarkerAction = new ResolveMarkerAction(this, "resolve"); //$NON-NLS-1$
1141
resolveMarkerAction.setText(TaskListMessages.Resolve_text);
1142        resolveMarkerAction.setToolTipText(TaskListMessages.Resolve_tooltip);
1143        resolveMarkerAction.setEnabled(false);
1144
1145        // Sort by ->
1146
sortByCategoryAction = new SortByAction(TaskSorter.TYPE);
1147        sortByCategoryAction.setText(TaskListMessages.SortByCategory_text);
1148        sortByCategoryAction.setToolTipText(TaskListMessages.SortByCategory_tooltip);
1149        PlatformUI.getWorkbench().getHelpSystem().setHelp(sortByCategoryAction,
1150                ITaskListHelpContextIds.TASK_SORT_TYPE_ACTION);
1151
1152        sortByCompletedAction = new SortByAction(TaskSorter.COMPLETION);
1153        sortByCompletedAction.setText(TaskListMessages.SortByCompleted_text);
1154        sortByCompletedAction.setToolTipText(TaskListMessages.SortByCompleted_tooltip);
1155        PlatformUI.getWorkbench().getHelpSystem().setHelp(
1156                sortByCompletedAction,
1157                ITaskListHelpContextIds.TASK_SORT_COMPLETED_ACTION);
1158
1159        sortByPriorityAction = new SortByAction(TaskSorter.PRIORITY);
1160        sortByPriorityAction.setText(TaskListMessages.SortByPriority_text);
1161        sortByPriorityAction.setToolTipText(TaskListMessages.SortByPriority_tooltip);
1162        PlatformUI.getWorkbench().getHelpSystem().setHelp(sortByPriorityAction,
1163                ITaskListHelpContextIds.TASK_SORT_PRIORITY_ACTION);
1164
1165        sortByDescriptionAction = new SortByAction(TaskSorter.DESCRIPTION);
1166        sortByDescriptionAction.setText(TaskListMessages.SortByDescription_text);
1167        sortByDescriptionAction.setToolTipText(TaskListMessages.SortByDescription_tooltip);
1168        PlatformUI.getWorkbench().getHelpSystem().setHelp(
1169                sortByDescriptionAction,
1170                ITaskListHelpContextIds.TASK_SORT_DESCRIPTION_ACTION);
1171
1172        sortByResourceAction = new SortByAction(TaskSorter.RESOURCE);
1173        sortByResourceAction.setText(TaskListMessages.SortByResource_text);
1174        sortByResourceAction.setToolTipText(TaskListMessages.SortByResource_tooltip);
1175        PlatformUI.getWorkbench().getHelpSystem().setHelp(sortByResourceAction,
1176                ITaskListHelpContextIds.TASK_SORT_RESOURCE_ACTION);
1177
1178        sortByContainerAction = new SortByAction(TaskSorter.FOLDER);
1179        sortByContainerAction.setText(TaskListMessages.SortByContainer_text);
1180        sortByContainerAction.setToolTipText(TaskListMessages.SortByContainer_tooltip);
1181        PlatformUI.getWorkbench().getHelpSystem().setHelp(
1182                sortByContainerAction,
1183                ITaskListHelpContextIds.TASK_SORT_FOLDER_ACTION);
1184
1185        sortByLocationAction = new SortByAction(TaskSorter.LOCATION);
1186        sortByLocationAction.setText(TaskListMessages.SortByLocation_text);
1187        sortByLocationAction.setToolTipText(TaskListMessages.SortByLocation_tooltip);
1188        PlatformUI.getWorkbench().getHelpSystem().setHelp(sortByLocationAction,
1189                ITaskListHelpContextIds.TASK_SORT_LOCATION_ACTION);
1190
1191        sortByCreationTimeAction = new SortByAction(TaskSorter.CREATION_TIME);
1192        sortByCreationTimeAction.setText(TaskListMessages.SortByCreationTime_text);
1193        sortByCreationTimeAction.setToolTipText(TaskListMessages.SortByCreationTime_tooltip);
1194        PlatformUI.getWorkbench().getHelpSystem().setHelp(
1195                sortByCreationTimeAction,
1196                ITaskListHelpContextIds.TASK_SORT_CREATION_TIME_ACTION);
1197
1198        sortAscendingAction = new SortDirectionAction(TaskSorter.ASCENDING);
1199        sortAscendingAction.setText(TaskListMessages.SortAscending_text);
1200        sortAscendingAction.setToolTipText(TaskListMessages.SortAscending_tooltip);
1201        PlatformUI.getWorkbench().getHelpSystem().setHelp(sortAscendingAction,
1202                ITaskListHelpContextIds.TASK_SORT_ASCENDING_ACTION);
1203
1204        sortDescendingAction = new SortDirectionAction(TaskSorter.DESCENDING);
1205        sortDescendingAction.setText(TaskListMessages.SortDescending_text);
1206        sortDescendingAction.setToolTipText(TaskListMessages.SortDescending_tooltip);
1207        PlatformUI.getWorkbench().getHelpSystem().setHelp(sortDescendingAction,
1208                ITaskListHelpContextIds.TASK_SORT_DESCENDING_ACTION);
1209
1210        // filters...
1211
filtersAction = new FiltersAction(this, "filter"); //$NON-NLS-1$
1212
filtersAction.setText(TaskListMessages.Filters_text);
1213        filtersAction.setToolTipText(TaskListMessages.Filters_tooltip);
1214        filtersAction.setImageDescriptor(MarkerUtil
1215                .getImageDescriptor("filter")); //$NON-NLS-1$
1216

1217        // properties
1218
propertiesAction = new TaskPropertiesAction(this, "properties"); //$NON-NLS-1$
1219
propertiesAction.setText(TaskListMessages.Properties_text);
1220        propertiesAction.setToolTipText(TaskListMessages.Properties_tooltip);
1221        propertiesAction.setEnabled(false);
1222    }
1223
1224    /**
1225     * The markers have changed. Update the status line and title bar.
1226     */

1227    void markersChanged() {
1228        updateStatusMessage();
1229        updateTitle();
1230    }
1231
1232    void partActivated(IWorkbenchPart part) {
1233        if (part == focusPart) {
1234            return;
1235        }
1236
1237        if (focusSelectionProvider != null) {
1238            focusSelectionProvider
1239                    .removeSelectionChangedListener(focusSelectionChangedListener);
1240            focusSelectionProvider = null;
1241        }
1242
1243        focusPart = part;
1244        if (focusPart != null) {
1245            focusSelectionProvider = focusPart.getSite().getSelectionProvider();
1246            if (focusSelectionProvider != null) {
1247                focusSelectionProvider
1248                        .addSelectionChangedListener(focusSelectionChangedListener);
1249                updateFocusResource(focusSelectionProvider.getSelection());
1250            } else {
1251                updateFocusResource(null);
1252            }
1253        }
1254
1255    }
1256
1257    void partClosed(IWorkbenchPart part) {
1258        if (part != focusPart) {
1259            return;
1260        }
1261        if (focusSelectionProvider != null) {
1262            focusSelectionProvider
1263                    .removeSelectionChangedListener(focusSelectionChangedListener);
1264            focusSelectionProvider = null;
1265        }
1266        focusPart = null;
1267    }
1268
1269    /**
1270     * The user is attempting to drag marker data. Add the appropriate
1271     * data to the event depending on the transfer type.
1272     */

1273    void performDragSetData(DragSourceEvent event) {
1274        if (MarkerTransfer.getInstance().isSupportedType(event.dataType)) {
1275            event.data = ((IStructuredSelection) viewer.getSelection())
1276                    .toArray();
1277            return;
1278        }
1279        if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
1280            Object JavaDoc[] data = ((IStructuredSelection) viewer.getSelection())
1281                    .toArray();
1282            if (data != null) {
1283                IMarker[] markers = new IMarker[data.length];
1284                for (int i = 0; i < markers.length; i++) {
1285                    markers[i] = (IMarker) data[i];
1286                }
1287                event.data = createMarkerReport(markers);
1288            }
1289            return;
1290        }
1291    }
1292
1293    void restoreState(IMemento memento) {
1294        //restore selection
1295
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
1296        IMemento selectionMem = memento.getChild(TAG_SELECTION);
1297        if (selectionMem != null) {
1298            ArrayList JavaDoc selectionList = new ArrayList JavaDoc();
1299            IMemento markerMems[] = selectionMem.getChildren(TAG_MARKER);
1300            for (int i = 0; i < markerMems.length; i++) {
1301                try {
1302                    long id = Long.parseLong(markerMems[i].getString(TAG_ID));
1303                    IResource resource = root.findMember(markerMems[i]
1304                            .getString(TAG_RESOURCE));
1305                    if (resource != null) {
1306                        IMarker marker = resource.findMarker(id);
1307                        if (marker != null) {
1308                            selectionList.add(marker);
1309                        }
1310                    }
1311                } catch (NumberFormatException JavaDoc e) {
1312                } catch (CoreException e) {
1313                }
1314
1315            }
1316            viewer.setSelection(new StructuredSelection(selectionList));
1317        }
1318
1319        Table table = viewer.getTable();
1320        //restore vertical position
1321
try {
1322            String JavaDoc topIndexStr = memento.getString(TAG_TOP_INDEX);
1323            table.setTopIndex(Integer.parseInt(topIndexStr));
1324        } catch (NumberFormatException JavaDoc e) {
1325        }
1326    }
1327
1328    /* (non-Javadoc)
1329     * Method declared on IViewPart.
1330     */

1331    public void saveState(IMemento memento) {
1332        if (viewer == null) {
1333            if (this.memento != null) {
1334                memento.putMemento(this.memento);
1335            }
1336            return;
1337        }
1338
1339        //save filter
1340
getFilter().saveState(memento.createChild(TAG_FILTER));
1341
1342        //save columns width
1343
Table table = viewer.getTable();
1344        TableColumn columns[] = table.getColumns();
1345        //check whether it has ever been layed out
1346
//workaround for 1GDTU19: ITPUI:WIN2000 - Task list columns "collapsed" left
1347
boolean shouldSave = false;
1348        for (int i = 0; i < columns.length; i++) {
1349            if (columnLayouts[i].resizable && columns[i].getWidth() != 0) {
1350                shouldSave = true;
1351                break;
1352            }
1353        }
1354        if (shouldSave) {
1355            for (int i = 0; i < columns.length; i++) {
1356                if (columnLayouts[i].resizable) {
1357                    IMemento child = memento.createChild(TAG_COLUMN);
1358                    child.putInteger(TAG_NUMBER, i);
1359                    child.putInteger(TAG_WIDTH, columns[i].getWidth());
1360                }
1361            }
1362        }
1363
1364        //save selection
1365
Object JavaDoc markers[] = ((IStructuredSelection) viewer.getSelection())
1366                .toArray();
1367        if (markers.length > 0) {
1368            IMemento selectionMem = memento.createChild(TAG_SELECTION);
1369            for (int i = 0; i < markers.length; i++) {
1370                IMemento elementMem = selectionMem.createChild(TAG_MARKER);
1371                IMarker marker = (IMarker) markers[i];
1372                elementMem.putString(TAG_RESOURCE, marker.getResource()
1373                        .getFullPath().toString());
1374                elementMem.putString(TAG_ID, String.valueOf(marker.getId()));
1375            }
1376        }
1377
1378        //save vertical position
1379
int topIndex = table.getTopIndex();
1380        memento.putString(TAG_TOP_INDEX, String.valueOf(topIndex));
1381    }
1382
1383    /**
1384     * Handles marker selection change in the task list by updating availability of
1385     * the actions in the local tool bar.
1386     */

1387    void selectionChanged(SelectionChangedEvent event) {
1388        IStructuredSelection selection = (IStructuredSelection) event
1389                .getSelection();
1390        updateStatusMessage(selection);
1391        updateTitle();
1392
1393        updatePasteEnablement();
1394
1395        // If selection is empty, then disable copy, remove and goto.
1396
if (selection.isEmpty()) {
1397            copyTaskAction.setEnabled(false);
1398            removeTaskAction.setEnabled(false);
1399            gotoTaskAction.setEnabled(false);
1400            propertiesAction.setEnabled(false);
1401            return;
1402        }
1403        
1404
1405        // Can only open properties for a single task at a time
1406
propertiesAction.setEnabled(selection.size() == 1);
1407
1408        // Can always copy
1409
copyTaskAction.setEnabled(true);
1410
1411        // Determine if goto should be enabled
1412
IMarker selectedMarker = (IMarker) selection.getFirstElement();
1413        boolean canJump = selection.size() == 1
1414                && selectedMarker.getResource().getType() == IResource.FILE;
1415        gotoTaskAction.setEnabled(canJump);
1416
1417        // Determine if remove should be enabled
1418
boolean canRemove = true;
1419        for (Iterator JavaDoc markers = selection.iterator(); markers.hasNext();) {
1420            IMarker m = (IMarker) markers.next();
1421            if (!MarkerUtil.isEditable(m)) {
1422                canRemove = false;
1423                break;
1424            }
1425        }
1426        removeTaskAction.setEnabled(canRemove);
1427
1428        // if there is an active editor on the selection's input, tell
1429
// the editor to goto the marker
1430
if (canJump) {
1431            IEditorPart editor = getSite().getPage().getActiveEditor();
1432            if (editor != null) {
1433                IFile file = ResourceUtil.getFile(editor.getEditorInput());
1434                if (file != null) {
1435                    if (selectedMarker.getResource().equals(file)) {
1436                        IDE.gotoMarker(editor, selectedMarker);
1437                    }
1438                }
1439            }
1440        }
1441    }
1442
1443    /* (non-Javadoc)
1444     * Method declared on IWorkbenchPart.
1445     */

1446    public void setFocus() {
1447        viewer.getControl().setFocus();
1448    }
1449
1450    /**
1451     * Sets the property on a marker to the given value.
1452     */

1453    void setProperty(IMarker marker, String JavaDoc property, Object JavaDoc value) {
1454        if (MarkerUtil.getProperty(marker, property).equals(value)) {
1455            return;
1456        }
1457        try {
1458            if (property == tableColumnProperties[1]) { // Completed
1459
marker.setAttribute(IMarker.DONE, value);
1460            } else if (property == tableColumnProperties[2]) { // Priority
1461
// this property is used only by cell editor, where order is High, Normal, Low
1462
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH
1463                        - ((Integer JavaDoc) value).intValue());
1464            } else if (property == tableColumnProperties[3]) { // Description
1465
marker.setAttribute(IMarker.MESSAGE, value);
1466                // Let's not refilter too lightly - see if it is needed
1467
// TaskSorter sorter = (TaskSorter) viewer.getSorter();
1468
// if (sorter != null && sorter.getColumnNumber() == 3) {
1469
// viewer.refresh();
1470
// }
1471
}
1472        } catch (CoreException e) {
1473            String JavaDoc msg = TaskListMessages.TaskList_errorModifyingTask;
1474            ErrorDialog.openError(getSite().getShell(), msg, null, e
1475                    .getStatus());
1476        }
1477    }
1478
1479    /**
1480     * API method which sets the current selection of this viewer.
1481     *
1482     * @param selection a structured selection of <code>IMarker</code> objects
1483     * @param reveal <code>true</code> to reveal the selection, <false> otherwise
1484     */

1485    public void setSelection(ISelection selection, boolean reveal) {
1486        Assert.isTrue(selection instanceof IStructuredSelection);
1487        IStructuredSelection ssel = (IStructuredSelection) selection;
1488
1489        for (Iterator JavaDoc i = ssel.iterator(); i.hasNext();) {
1490            Assert.isTrue(i.next() instanceof IMarker);
1491        }
1492
1493        if (viewer != null) {
1494            viewer.setSelection(selection, reveal);
1495        }
1496    }
1497
1498    boolean showChildrenHierarchy() {
1499        switch (getFilter().onResource) {
1500        case TasksFilter.ON_ANY_RESOURCE:
1501        case TasksFilter.ON_SELECTED_RESOURCE_AND_CHILDREN:
1502        case TasksFilter.ON_ANY_RESOURCE_OF_SAME_PROJECT:
1503        // added by cagatayk@acm.org
1504
case TasksFilter.ON_WORKING_SET:
1505        default:
1506            return true;
1507        case TasksFilter.ON_SELECTED_RESOURCE_ONLY:
1508            return false;
1509        }
1510    }
1511
1512    boolean showSelections() {
1513        switch (getFilter().onResource) {
1514        case TasksFilter.ON_SELECTED_RESOURCE_ONLY:
1515        case TasksFilter.ON_SELECTED_RESOURCE_AND_CHILDREN:
1516        case TasksFilter.ON_ANY_RESOURCE_OF_SAME_PROJECT:
1517            // added by cagatayk@acm.org
1518
return true;
1519        case TasksFilter.ON_ANY_RESOURCE:
1520        case TasksFilter.ON_WORKING_SET:
1521        default:
1522            return false;
1523        }
1524    }
1525
1526    // showOwnerProject() added by cagatayk@acm.org
1527
boolean showOwnerProject() {
1528        return getFilter().onResource == TasksFilter.ON_ANY_RESOURCE_OF_SAME_PROJECT;
1529    }
1530
1531    /**
1532     * Processes state change of the 'showSelections' switch.
1533     * If true, it will resync with the saved input element.
1534     * Otherwise, it will reconfigure to show all the
1535     * problems/tasks in the workbench.
1536     *
1537     * @param value the value
1538     */

1539    void toggleInputSelection(boolean value) {
1540        /*
1541         if (value) {
1542         handleInput(inputSelection, false);
1543         } else {
1544         // detach from input and link to the workbench object
1545         handleInput(WorkbenchPlugin.getPluginWorkbench(), true);
1546         }
1547         updateTitle();
1548         */

1549    }
1550
1551    /**
1552     * If true, current input will be
1553     * remembered and further selections will be
1554     * ignored.
1555     *
1556     * @param value the value
1557     */

1558    void toggleLockInput(boolean value) {
1559        /*
1560         if (!value) {
1561         handleInput(inputSelection, false);
1562         lockedInput = null;
1563         } else {
1564         lockedInput = (IElement) getInput();
1565         }
1566         String lockedInputPath = "";
1567         if (lockedInput != null && lockedInput instanceof IResource) {
1568         IResource resource = (IResource) lockedInput;
1569         lockedInputPath = resource.getFullPath().toString();
1570         }
1571         IDialogStore store = WorkbenchPlugin.getDefault().getDialogStore();
1572         store.put(STORE_LOCKED_INPUT, lockedInputPath);
1573         updateTitle();
1574         */

1575    }
1576
1577    /**
1578     * Updates the focus resource, and refreshes if we're showing only tasks for the focus resource.
1579     */

1580    void updateFocusResource(ISelection selection) {
1581        ArrayList JavaDoc list = new ArrayList JavaDoc();
1582
1583        if (selection instanceof IStructuredSelection) {
1584            Iterator JavaDoc iterator = ((IStructuredSelection) selection).iterator();
1585            while (iterator.hasNext()) {
1586                Object JavaDoc object = iterator.next();
1587
1588                if (object instanceof IAdaptable) {
1589                    ITaskListResourceAdapter taskListResourceAdapter;
1590                    Object JavaDoc adapter = ((IAdaptable) object)
1591                            .getAdapter(ITaskListResourceAdapter.class);
1592                    if (adapter != null
1593                            && adapter instanceof ITaskListResourceAdapter) {
1594                        taskListResourceAdapter = (ITaskListResourceAdapter) adapter;
1595                    } else {
1596                        taskListResourceAdapter = DefaultTaskListResourceAdapter
1597                                .getDefault();
1598                    }
1599
1600                    IResource resource = taskListResourceAdapter
1601                            .getAffectedResource((IAdaptable) object);
1602                    if (resource != null) {
1603                        list.add(resource);
1604                    }
1605                }
1606            }
1607        }
1608
1609        if (list.size() == 0 && focusPart instanceof IEditorPart) {
1610            IEditorInput input = ((IEditorPart) focusPart).getEditorInput();
1611            if (input != null) {
1612                IResource resource = ResourceUtil.getResource(input);
1613                if (resource != null) {
1614                    list.add(resource);
1615                }
1616            }
1617        }
1618
1619        int l = list.size();
1620        if (l < 1) {
1621            return; // required to achieve lazy update behavior.
1622
}
1623
1624        IResource[] resources = (IResource[]) list.toArray(new IResource[l]);
1625        for (int i = 0; i < l; i++) {
1626            Assert.isNotNull(resources[i]);
1627        }
1628
1629        if (!Arrays.equals(resources, focusResources)) {
1630            boolean updateNeeded = false;
1631
1632            if (showOwnerProject()) {
1633                int m = focusResources == null ? 0 : focusResources.length;
1634                if (l != m) {
1635                    updateNeeded = true;
1636                } else {
1637                    for (int i = 0; i < l; i++) {
1638                        IProject oldProject = m < 1 ? null : focusResources[0]
1639                                .getProject();
1640                        IProject newProject = resources[0].getProject();
1641                        boolean projectsEqual = (oldProject == null ? newProject == null
1642                                : oldProject.equals(newProject));
1643                        if (!projectsEqual) {
1644                            updateNeeded = true;
1645                            break;
1646                        }
1647                    }
1648                }
1649            } else if (showSelections()) {
1650                updateNeeded = true;
1651            }
1652
1653            // remember the focus resources even if update is not needed,
1654
// so that we know them if the filter settings change
1655
focusResources = resources;
1656
1657            if (updateNeeded) {
1658                viewer.getControl().setRedraw(false);
1659                viewer.refresh();
1660                viewer.getControl().setRedraw(true);
1661                updateStatusMessage();
1662                updateTitle();
1663            }
1664        }
1665    }
1666
1667    /**
1668     * Updates the enablement of the paste action
1669     */

1670    void updatePasteEnablement() {
1671        // Paste if clipboard contains tasks
1672
MarkerTransfer transfer = MarkerTransfer.getInstance();
1673        IMarker[] markerData = (IMarker[]) getClipboard().getContents(transfer);
1674        boolean canPaste = false;
1675        if (markerData != null) {
1676            for (int i = 0; i < markerData.length; i++) {
1677                if (MarkerUtil.isMarkerType(markerData[i], IMarker.TASK)) {
1678                    canPaste = true;
1679                    break;
1680                }
1681            }
1682        }
1683        pasteTaskAction.setEnabled(canPaste);
1684    }
1685
1686    /**
1687     * Updates that message displayed in the status line.
1688     */

1689    void updateStatusMessage() {
1690        ISelection selection = viewer.getSelection();
1691
1692        if (selection instanceof IStructuredSelection) {
1693            updateStatusMessage((IStructuredSelection) selection);
1694        } else {
1695            updateStatusMessage(null);
1696        }
1697    }
1698
1699    /**
1700     * Updates that message displayed in the status line.
1701     */

1702    void updateStatusMessage(IStructuredSelection selection) {
1703        String JavaDoc message = getStatusMessage(selection);
1704        getViewSite().getActionBars().getStatusLineManager()
1705                .setMessage(message);
1706    }
1707
1708    /**
1709     * Updates the title of the view. Should be called when filters change.
1710     */

1711    void updateTitle() {
1712        TaskListContentProvider provider = (TaskListContentProvider) getTableViewer()
1713                .getContentProvider();
1714        String JavaDoc summary = provider.getTitleSummary();
1715        setContentDescription(summary);
1716    }
1717
1718    /**
1719     * Method updateSortingState.
1720     */

1721    void updateSortingState() {
1722        int curColumn = comparator.getTopPriority();
1723        sortByCategoryAction.setChecked(curColumn == TaskSorter.TYPE);
1724        sortByCompletedAction.setChecked(curColumn == TaskSorter.COMPLETION);
1725        sortByPriorityAction.setChecked(curColumn == TaskSorter.PRIORITY);
1726        sortByDescriptionAction.setChecked(curColumn == TaskSorter.DESCRIPTION);
1727        sortByResourceAction.setChecked(curColumn == TaskSorter.RESOURCE);
1728        sortByContainerAction.setChecked(curColumn == TaskSorter.FOLDER);
1729        sortByLocationAction.setChecked(curColumn == TaskSorter.LOCATION);
1730        sortByCreationTimeAction
1731                .setChecked(curColumn == TaskSorter.CREATION_TIME);
1732
1733        int curDirection = comparator.getTopPriorityDirection();
1734        sortAscendingAction.setChecked(curDirection == TaskSorter.ASCENDING);
1735        sortDescendingAction.setChecked(curDirection == TaskSorter.DESCENDING);
1736    }
1737
1738}
1739
Popular Tags