KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > tasklist > usertasks > UserTaskView


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.tasklist.usertasks;
21
22 import java.awt.BorderLayout JavaDoc;
23 import java.awt.Image JavaDoc;
24 import java.awt.Point JavaDoc;
25 import java.awt.event.InputEvent JavaDoc;
26 import java.awt.event.KeyEvent JavaDoc;
27 import java.beans.PropertyChangeEvent JavaDoc;
28 import java.beans.PropertyChangeListener JavaDoc;
29 import java.io.File JavaDoc;
30 import java.io.FileOutputStream JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.InputStream JavaDoc;
33 import java.io.ObjectInput JavaDoc;
34 import java.io.ObjectOutput JavaDoc;
35 import java.io.OutputStream JavaDoc;
36 import java.io.Serializable JavaDoc;
37 import java.net.URL JavaDoc;
38 import java.util.HashMap JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.logging.Level JavaDoc;
41 import javax.swing.Action JavaDoc;
42 import javax.swing.ActionMap JavaDoc;
43 import javax.swing.JComponent JavaDoc;
44 import javax.swing.JPanel JavaDoc;
45 import javax.swing.JScrollPane JavaDoc;
46 import javax.swing.JToolBar JavaDoc;
47 import javax.swing.KeyStroke JavaDoc;
48 import javax.swing.SwingUtilities JavaDoc;
49 import javax.swing.border.EmptyBorder JavaDoc;
50 import javax.swing.tree.TreePath JavaDoc;
51 import org.netbeans.modules.tasklist.core.export.ExportImportFormat;
52 import org.netbeans.modules.tasklist.core.export.ExportImportProvider;
53 import org.netbeans.modules.tasklist.core.filter.Filter;
54 import org.netbeans.modules.tasklist.core.filter.FilterAction;
55 import org.netbeans.modules.tasklist.core.filter.FilterRepository;
56 import org.netbeans.modules.tasklist.core.filter.FilteredTopComponent;
57 import org.netbeans.modules.tasklist.core.filter.RemoveFilterAction;
58 import org.netbeans.modules.tasklist.core.util.RightSideBorder;
59 import org.netbeans.modules.tasklist.usertasks.actions.GoToUserTaskAction;
60 import org.netbeans.modules.tasklist.usertasks.actions.MoveDownAction;
61 import org.netbeans.modules.tasklist.usertasks.actions.MoveLeftAction;
62 import org.netbeans.modules.tasklist.usertasks.actions.MoveRightAction;
63 import org.netbeans.modules.tasklist.usertasks.actions.MoveUpAction;
64 import org.netbeans.modules.tasklist.usertasks.actions.NewTaskAction;
65 import org.netbeans.modules.tasklist.usertasks.actions.PauseAction;
66 import org.netbeans.modules.tasklist.usertasks.actions.StartTaskAction;
67 import org.netbeans.modules.tasklist.usertasks.actions.UTCopyAction;
68 import org.netbeans.modules.tasklist.usertasks.actions.UTCutAction;
69 import org.netbeans.modules.tasklist.usertasks.actions.UTDeleteAction;
70 import org.netbeans.modules.tasklist.usertasks.actions.UTPasteAction;
71 import org.netbeans.modules.tasklist.usertasks.actions.UTSaveAction;
72 import org.netbeans.modules.tasklist.usertasks.filter.UserTaskFilter;
73 import org.netbeans.modules.tasklist.usertasks.model.StartedUserTask;
74 import org.netbeans.modules.tasklist.usertasks.options.Settings;
75 import org.netbeans.modules.tasklist.usertasks.translators.HistoryTextExportFormat;
76 import org.netbeans.modules.tasklist.usertasks.translators.HtmlExportFormat;
77 import org.netbeans.modules.tasklist.usertasks.translators.ICalExportFormat;
78 import org.netbeans.modules.tasklist.usertasks.translators.ICalImportFormat;
79 import org.netbeans.modules.tasklist.usertasks.translators.TextExportFormat;
80 import org.netbeans.modules.tasklist.usertasks.translators.XmlExportFormat;
81 import org.netbeans.modules.tasklist.core.table.ChooseColumnsPanel;
82 import org.netbeans.modules.tasklist.usertasks.actions.ClearCompletedAction;
83 import org.netbeans.modules.tasklist.usertasks.actions.PurgeTasksAction;
84 import org.netbeans.modules.tasklist.usertasks.actions.ShowTaskAction;
85 import org.netbeans.modules.tasklist.usertasks.actions.UTPasteAtTopLevelAction;
86 import org.netbeans.modules.tasklist.usertasks.actions.UTPropertiesAction;
87 import org.netbeans.modules.tasklist.usertasks.treetable.TreeTableModel;
88 import org.netbeans.modules.tasklist.usertasks.util.AWTThreadAnnotation;
89 import org.netbeans.modules.tasklist.usertasks.util.UTUtils;
90 import org.openide.actions.FindAction;
91 import org.openide.cookies.InstanceCookie;
92 import org.openide.filesystems.FileChangeListener;
93 import org.openide.filesystems.FileEvent;
94 import org.openide.filesystems.FileObject;
95 import org.openide.filesystems.FileSystem;
96 import org.openide.filesystems.FileUtil;
97 import org.openide.filesystems.Repository;
98 import org.openide.filesystems.URLMapper;
99 import org.openide.loaders.DataObject;
100 import org.openide.loaders.DataObjectNotFoundException;
101 import org.openide.util.HelpCtx;
102 import org.openide.util.NbBundle;
103 import org.openide.util.Utilities;
104 import org.openide.util.actions.SystemAction;
105 import org.openide.util.lookup.Lookups;
106 import org.openide.windows.Mode;
107 import org.openide.windows.TopComponent;
108 import org.openide.windows.WindowManager;
109 import org.netbeans.modules.tasklist.usertasks.model.UserTask;
110 import org.netbeans.modules.tasklist.usertasks.model.UserTaskList;
111 import org.netbeans.modules.tasklist.usertasks.treetable.TreeTable;
112 import org.openide.DialogDisplayer;
113 import org.openide.NotifyDescriptor;
114 import org.openide.cookies.SaveCookie;
115
116 /**
117  * View showing the user tasks.
118  *
119  * @author Tor Norbye
120  * @author tl
121  */

122 public class UserTaskView extends TopComponent implements ExportImportProvider,
123         FileChangeListener, FilteredTopComponent {
124     // List category
125
private final static String JavaDoc USER_CATEGORY = "usertasks"; // NOI18N
126

127     private static final String JavaDoc DEFAULT_FILTER_NAME =
128             NbBundle.getMessage(UserTaskView.class,
129             "default-filter-name"); // NOI18N
130

131     private static final long serialVersionUID = 1;
132
133     private static final Image JavaDoc ICON = Utilities.loadImage(
134         "org/netbeans/modules/tasklist/usertasks/actions/taskView.gif"); // NOI18N
135

136     static {
137         // DEBUG:
138
// UTUtils.dumpClassLoaders(UserTaskView.class.getClassLoader());
139
// UTUtils.dumpClassLoaders(Thread.currentThread().getContextClassLoader());
140

141         // repaint the view if the number of working hours per day has
142
// changed (spent time, rem. effort and effort columns should be
143
// repainted)
144
Settings.getDefault().addPropertyChangeListener(
145             new PropertyChangeListener JavaDoc() {
146                 public void propertyChange(PropertyChangeEvent JavaDoc e) {
147                     String JavaDoc n = e.getPropertyName();
148                     if (n == Settings.PROP_WORKING_DAY_END ||
149                             n == Settings.PROP_WORKING_DAY_END ||
150                             n == Settings.PROP_PAUSE_START ||
151                             n == Settings.PROP_PAUSE_END ||
152                             n == Settings.PROP_WORKING_DAYS) {
153                         UserTaskView[] all;
154                         synchronized(UserTaskView.class) {
155                             all = UserTaskViewRegistry.
156                                     getInstance().getAll();
157                         }
158                         for (int i = 0; i < all.length; i++) {
159                             all[i].repaint();
160                         }
161                     }
162                 }
163             }
164         );
165     }
166     
167     /**
168      * Returns the default task list file. Copies template file to the
169      * default location if the file does not exist.
170      *
171      * @return default task list file
172      */

173     public static FileObject getDefaultFile() throws IOException JavaDoc {
174         String JavaDoc name = Settings.getDefault().getExpandedFilename();
175         File JavaDoc f = FileUtil.normalizeFile(new File JavaDoc(name));
176        
177         FileObject fo = FileUtil.toFileObject(f);
178         if (fo == null) {
179             File JavaDoc dir = f.getParentFile();
180             if (!dir.exists() && !dir.mkdirs()) {
181                 throw new IOException JavaDoc(
182                     NbBundle.getMessage(UserTaskList.class,
183                         "CannotCreateDir", dir.getAbsolutePath())); // NOI18N
184
}
185             OutputStream JavaDoc os = new FileOutputStream JavaDoc(f);
186             try {
187                 InputStream JavaDoc is = UserTaskList.class.getResourceAsStream(
188                         "/org/netbeans/modules/tasklist/usertasks/tasklist.ics"); // NOI18N
189
try {
190                     UTUtils.copyStream(is, os);
191                 } finally {
192                     is.close();
193                 }
194             } finally {
195                 os.close();
196             }
197             fo = FileUtil.toFileObject(f);
198         }
199         return fo;
200     }
201     
202     private UserTasksTreeTable tt;
203     private JScrollPane JavaDoc scrollPane;
204     private boolean initialized = false;
205     private UserTaskList tasklist = null;
206     private FilterRepository filters = null;
207     private Filter activeFilter = null;
208     private boolean default_;
209     
210     /** View specific action for moving the selected task up. */
211     public MoveUpAction moveUpAction;
212     
213     /** View specific action for moving the selected task down. */
214     public MoveDownAction moveDownAction;
215     
216     /** View specific action for moving the selected task left. */
217     public MoveLeftAction moveLeftAction;
218     
219     /** View specific action for moving the selected task left. */
220     public MoveRightAction moveRightAction;
221     
222     /** View specific action for purging completed tasks. */
223     public PurgeTasksAction purgeTasksAction;
224     
225     /** View specific action for clearing completion status. */
226     public ClearCompletedAction clearCompletedAction;
227     
228     /** View specific action for creating a sub-task. */
229     public NewTaskAction newTaskAction;
230     
231     /** View specific action for editing a task. */
232     public ShowTaskAction showTaskAction;
233     
234     /** "Show properties" action. */
235     public UTPropertiesAction propertiesAction;
236     
237     /** "Save" */
238     public UTSaveAction saveAction;
239     
240     /** "Paste at the Top Level" */
241     public UTPasteAtTopLevelAction pasteAtTopLevelAction;
242             
243     private FileObject file;
244     
245     /**
246      * Construct a new UserTaskView.
247      * NOTE: this is used by the window
248      * system when deserializing windows.
249      */

250     public UserTaskView() {
251     }
252
253     /**
254      * Constructor.
255      *
256      * @param fo .ics file
257      * @param default_ true for the global "User Tasks" view
258      */

259     @AWTThreadAnnotation
260     public UserTaskView(FileObject fo, boolean default_) {
261         init(fo, default_);
262     }
263
264     /**
265      * Returns the file shown in this view.
266      *
267      * @return file
268      */

269     public FileObject getFile() {
270         return file;
271     }
272     
273     public boolean canClose() {
274         if (!super.canClose())
275             return false;
276         DataObject do_;
277         try {
278             do_ = DataObject.find(file);
279         } catch (DataObjectNotFoundException e) {
280             UTUtils.LOGGER.log(Level.SEVERE, e.getMessage(), e);
281             return false;
282         }
283         SaveCookie sc = do_.getCookie(SaveCookie.class);
284         if (sc == null)
285             return true;
286         
287         String JavaDoc save = NbBundle.getMessage(UserTaskView.class, "Save");
288         String JavaDoc discard = NbBundle.getMessage(UserTaskView.class, "Discard");
289         String JavaDoc cancel = NbBundle.getMessage(UserTaskView.class, "Cancel");
290         
291         NotifyDescriptor d = new NotifyDescriptor(
292                 NbBundle.getMessage(UserTaskView.class,
293                 "FileWasModified", // NOI18N
294
FileUtil.getFileDisplayName(file)),
295                 NbBundle.getMessage(UserTaskView.class,
296                 "Question"), // NOI18N
297
NotifyDescriptor.YES_NO_CANCEL_OPTION,
298                 NotifyDescriptor.QUESTION_MESSAGE,
299                 new Object JavaDoc[] {save, discard, cancel}, save);
300         Object JavaDoc ret = DialogDisplayer.getDefault().notify(d);
301         if (ret.equals(save)) {
302             try {
303                 sc.save();
304                 return true;
305             } catch (IOException JavaDoc e) {
306                 UTUtils.LOGGER.log(Level.SEVERE, e.getMessage(), e);
307                 return false;
308             }
309         } else if (ret.equals(discard)) {
310             do_.setModified(false);
311             return true;
312         } else {
313             return false;
314         }
315     }
316     
317     /**
318      * Returns the component representing the tasks.
319      *
320      * @return TreeTable
321      */

322     public UserTasksTreeTable getTreeTable() {
323         return tt;
324     }
325     
326     /**
327      * Returns actions for the toolbar.
328      *
329      * @return actions for the toolbar or null
330      */

331     public Action JavaDoc[] getToolBarActions() {
332         return new Action JavaDoc[] {
333             saveAction,
334             newTaskAction,
335             new GoToUserTaskAction(this),
336             null,
337             SystemAction.get(FilterAction.class),
338             SystemAction.get(RemoveFilterAction.class),
339             null,
340             new StartTaskAction(this),
341             PauseAction.getInstance(),
342             null,
343             moveUpAction,
344             moveDownAction,
345             // SystemAction.get(AsListAction.class)
346
};
347     }
348     
349     public void componentActivated() {
350         super.componentActivated();
351
352         RemoveFilterAction removeFilter =
353             (RemoveFilterAction) SystemAction.get(RemoveFilterAction.class);
354         removeFilter.enable();
355         UserTaskViewRegistry.getInstance().setLastActivated(this);
356     }
357     
358     /**
359      * Read in a serialized version of the tasklist
360      * and reads in sorting preferences etc. such that
361      * we use the same preferences now.
362      * @param objectInput object stream to read from
363      * @throws IOException
364      * @throws ClassNotFoundException
365      */

366     public void readExternalCore(ObjectInput JavaDoc objectInput) throws IOException JavaDoc,
367             java.lang.ClassNotFoundException JavaDoc {
368         // Don't call super!
369
// See writeExternal for justification
370
// super.readExternal(objectInput);
371

372         int ver = objectInput.read();
373
374         objectInput.readObject(); // ignore the UID of selected task
375

376         if (ver == 4)
377             return;
378
379         int sortingColumn = objectInput.read();
380         int sortAscendingInt = objectInput.read();
381         int numVisible = objectInput.read();
382
383         // Account for conversion to unsigned byte in writeExternal
384
if (sortingColumn == 255) {
385             sortingColumn = -1;
386         }
387
388         if (numVisible > 0) {
389             String JavaDoc[] columns = new String JavaDoc[0];
390             int numColumns = columns.length;
391             boolean[] columnVisible = new boolean[numColumns];
392             for (int i = 0; i < numColumns; i++) {
393                 columnVisible[i] = false;
394             }
395             for (int i = 0; i < numVisible; i++) {
396                 int uid = objectInput.read();
397             }
398         }
399
400         if (ver >= 2) {
401             objectInput.readObject(); // ignoring category
402
objectInput.readObject(); // ignoring title
403
int persistentInt = objectInput.read();
404         }
405     }
406     
407     /**
408      * Read in a serialized version of the tasklist
409      * and reads in sorting preferences etc. such that
410      * we use the same preferences now.
411      * @param objectInput object stream to read from
412      * @throws IOException
413      * @throws ClassNotFoundException
414      */

415     public void readExternal(ObjectInput JavaDoc objectInput) throws IOException JavaDoc,
416             java.lang.ClassNotFoundException JavaDoc {
417         readExternalCore(objectInput);
418         int ver = objectInput.read();
419
420         if (ver >= 2) {
421             // Read tasklist file name
422
String JavaDoc urlString = (String JavaDoc)objectInput.readObject();
423
424             if (urlString != null) {
425                 URL JavaDoc url = new URL JavaDoc(urlString);
426                 file = URLMapper.findFileObject(url);
427                 if (file != null && file.isValid()) {
428                     init(file, false);
429                 } else {
430                     Runnable JavaDoc r = new Runnable JavaDoc() {
431                         public void run() {
432                             close();
433                         }
434                     };
435                     SwingUtilities.invokeLater(r);
436                 }
437             } else {
438                 init(getDefaultFile(), true);
439                 UserTaskViewRegistry.getInstance().setDefaultView(this);
440             }
441         }
442         if (ver >= 3) {
443             // just reading expanded state without using it
444
// for compatibility only
445
objectInput.readObject();
446         }
447         if (ver >= 4) {
448             // just reading selected node without using it
449
// for compatibility only
450
objectInput.readObject();
451         }
452         if (ver >= 5) {
453             String JavaDoc uid = (String JavaDoc) objectInput.readObject();
454             
455             // started task
456
if (StartedUserTask.getInstance().getStarted() == null && uid != null) {
457                 UserTask ut = tasklist.findItem(
458                     tasklist.getSubtasks().iterator(), uid);
459                 if (ut != null)
460                     ut.start();
461             }
462         }
463         if (ver >= 6) {
464             // scroll bars positions
465
Map JavaDoc m = (Map JavaDoc) objectInput.readObject();
466             Point JavaDoc p = (Point JavaDoc) m.get("scrollPosition"); // NOI18N
467
if (p != null) {
468                 scrollPane.getVerticalScrollBar().setValue(p.y);
469                 scrollPane.getHorizontalScrollBar().setValue(p.x);
470             }
471             
472             // columns
473
TreeTable.ColumnsConfig cc = (TreeTable.ColumnsConfig) m.get("columns"); // NOI18N
474
if (cc != null) {
475                 tt.setColumnsConfig(cc);
476             }
477             
478             // active filter 25. March 2005
479
String JavaDoc filter = (String JavaDoc) m.get("filter"); // NOI18N
480
if (filter != null) {
481                 Filter f = getFilters().getFilterByName(filter);
482                 setFilter(f);
483             }
484             
485             // expanded state 25. March 2005
486
Object JavaDoc expn = m.get("expandedNodes"); // NOI18N
487
if (expn != null) {
488                 tt.setExpandedNodes(tt.readResolveExpandedNodes(expn));
489             }
490             
491             // selected nodes
492
Object JavaDoc seln = m.get("selectedNodes"); // NOI18N
493
if (seln != null) {
494                 tt.select(tt.readResolveExpandedNodes(seln));
495             }
496         }
497     }
498
499     /**
500      * Write out relevant settings in the window (visible
501      * columns, sorting order, etc.) such that they can
502      * be reconstructed the next time the IDE is started.
503      *
504      * @param objectOutput Object stream to write to
505      * @throws IOException
506      */

507     public void writeExternal(ObjectOutput JavaDoc objectOutput) throws IOException JavaDoc {
508         // Don't call super.writeExternal.
509
// Our parent is TopComponent.
510
// TopComponent persists the name and tooltip text; we
511
// don't care about that either.
512
// super.writeExternal(objectOutput);
513

514         // Version 1 format:
515
// String: selected uid
516
// byte: sortingColumn (255: no sort, otherwise, sorting id)
517
// byte: sort ascending (0:false or 1:true)
518
// byte: number of visible columns (N)
519
// N bytes: visible column uids
520

521         // Version 4 format:
522
// String: selected UID
523
// String: category
524
// String: title
525
// byte: persistent
526

527         // Write out the UID of the currently selected task, or null if none
528
objectOutput.write(4); // SERIAL VERSION
529

530         // Write out the UID of the currently selected task, or null if none
531
objectOutput.writeObject(null); // Unused. Was never implemented
532

533         // Here I should record a few things; in particular, sorting order, view
534
// preferences, etc.
535
// Since I'm not doing that yet, let's at a minimum put in a version
536
// byte so we can do the right thing later without corrupting the userdir
537
objectOutput.write(6); // SERIAL VERSION
538

539         UserTaskList tl = getUserTaskList();
540         if (!default_) {
541             // Write out the name of the tasklist
542
URL JavaDoc url = URLMapper.findURL(file, URLMapper.EXTERNAL);
543             String JavaDoc urlString = url.toExternalForm();
544             objectOutput.writeObject(urlString);
545         } else {
546             objectOutput.writeObject(null);
547         }
548         
549         // writing null instead of expanded nodes
550
// just for compatibility
551
objectOutput.writeObject(null);
552         
553         // writing null instead of the selected task
554
// just for compatibility
555
objectOutput.writeObject(null);
556         
557         // started task
558
if (StartedUserTask.getInstance().getStarted() != null &&
559             StartedUserTask.getInstance().getStarted().getList() == tasklist) {
560             objectOutput.writeObject(StartedUserTask.getInstance().
561                 getStarted().getUID());
562             StartedUserTask.getInstance().start(null);
563         } else {
564             objectOutput.writeObject(null);
565         }
566
567         Map JavaDoc<String JavaDoc, Serializable JavaDoc> m = new HashMap JavaDoc<String JavaDoc, Serializable JavaDoc>();
568         
569         // scroll bars positions
570
Point JavaDoc p = new Point JavaDoc(
571             scrollPane.getHorizontalScrollBar().getValue(),
572             scrollPane.getVerticalScrollBar().getValue());
573         m.put("scrollPosition", p); // NOI18N
574

575         // columns
576
Serializable JavaDoc cc = tt.getColumnsConfig();
577         m.put("columns", cc); // NOI18N
578

579         // active filter
580
if (getFilter() != null)
581             m.put("filter", getFilter().getName()); // NOI18N
582

583         // expanded nodes
584
m.put("expandedNodes", tt.writeReplaceExpandedNodes(tt.getExpandedNodes())); // NOI18N
585

586         // selected nodes
587
m.put("selectedNodes", tt.writeReplaceExpandedNodes(tt.getSelectedPaths())); // NOI18N
588

589         objectOutput.writeObject(m);
590     }
591
592     /**
593      * Updates the name of this TC and the tooltip
594      * corresponding to the FileObject.
595      */

596     private void updateNameAndToolTip() {
597         setToolTipText(FileUtil.getFileDisplayName(file));
598         if (!default_) {
599             setName(file.getNameExt());
600         } else {
601             setName(NbBundle.getMessage(UserTaskView.class, "TaskViewName")); // NOI18N
602
}
603     }
604     
605     public String JavaDoc toString() {
606         return "UserTaskView(" + getName() + ", " + getUserTaskList() + ")"; // NOI18N
607
}
608     
609     /**
610      * Create filter template.
611      *
612      * @return created filter
613      */

614     public org.netbeans.modules.tasklist.core.filter.Filter createFilter() {
615         return new UserTaskFilter("Simple"); // NOI18N
616
}
617
618     protected java.lang.String JavaDoc preferredID() {
619         return "org.netbeans.modules.tasklist.usertasks.Window"; // NOI18N
620
}
621
622     protected void setFiltered() {
623         if (getFilter() != null) {
624             ((RemoveFilterAction) SystemAction.get(
625                 RemoveFilterAction.class)).enable();
626         }
627
628         TreeTableModel ttm = tt.getTreeTableModel();
629         if (ttm instanceof UserTasksTreeTableModel) {
630             ((UserTasksTreeTableModel) ttm).destroy();
631         }
632         tt.setTreeTableModel(new UserTasksTreeTableModel((UserTaskList) getUserTaskList(),
633             tt.getSortingModel(), getFilter()));
634     }
635
636     /**
637      * Expand nodes and select the particular item, IF the list
638      * view is showing
639      *
640      * @param item The item to be shown
641      */

642     public void select(UserTask task) {
643         if (isShowing() == false) return;
644         
645         assert tt != null : "tt == null"; // NOI18N
646
TreePath JavaDoc tp = tt.findPath(task);
647         
648         // tp could be null if a filter is in use
649
if (tp != null) {
650             tt.expandPath(tp.getParentPath());
651             tt.select(tp);
652         }
653     }
654     
655     /**
656      * Makes the specified task visible (scrolls to it)
657      *
658      * @param task a task
659      */

660     public void scrollTo(UserTask task) {
661         if (isShowing() == false)
662             return;
663         
664         TreePath JavaDoc tp = tt.findPath(task);
665         tt.scrollTo(tp);
666     }
667     
668     public int getPersistenceType() {
669         return TopComponent.PERSISTENCE_ONLY_OPENED;
670     }
671     
672     public org.openide.util.HelpCtx getHelpCtx() {
673         return new HelpCtx(
674             "org.netbeans.modules.tasklist.usertasks.HOMEID"); // NOI18N
675
}
676     
677     public ExportImportFormat[] getExportFormats() {
678         return new ExportImportFormat[] {
679             new TextExportFormat(),
680             new XmlExportFormat(),
681             new HtmlExportFormat(),
682             new ICalExportFormat(),
683             new HistoryTextExportFormat()
684         };
685     }
686     
687     public ExportImportFormat[] getImportFormats() {
688         return new ExportImportFormat[] {
689             new ICalImportFormat()
690         };
691     }
692     
693     /**
694      * Common part for all constructors.
695      *
696      * file and default_ variable should be initialized before calling this.
697      */

698     @AWTThreadAnnotation
699     private void init(FileObject file, boolean default_) {
700         assert SwingUtilities.isEventDispatchThread();
701         
702         TaskListDataObject do_ = null;
703         try {
704             do_ = (TaskListDataObject) DataObject.find(file);
705         } catch (DataObjectNotFoundException e) {
706             UTUtils.LOGGER.log(Level.SEVERE, e.getMessage(), e);
707             return;
708         }
709         
710         this.file = file;
711         this.default_ = default_;
712             
713         try {
714             tasklist = do_.getUserTaskList();
715         } catch (IOException JavaDoc e) {
716             NotifyDescriptor nd = new NotifyDescriptor.Message(
717                     NbBundle.getMessage(TaskListDataObject.class,
718                     "ErrorReadingFile", e.getMessage())); // NOI18N
719
DialogDisplayer.getDefault().notify(nd);
720         }
721         
722         updateNameAndToolTip();
723         
724         new DueTasksNotifier(tasklist);
725         
726         file.addFileChangeListener(this);
727         
728         setIcon(ICON);
729         
730         setLayout(new BorderLayout JavaDoc());
731
732         JPanel JavaDoc centerPanel = new JPanel JavaDoc();
733         centerPanel.setLayout(new BorderLayout JavaDoc());
734         
735         tt = new UserTasksTreeTable(this, getUserTaskList(), getFilter());
736
737         associateLookup(Lookups.fixed(do_, do_.getNodeDelegate(),
738                 getActionMap()));
739         
740         configureActions();
741         
742         scrollPane = new JScrollPane JavaDoc(tt,
743             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
744             JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
745         scrollPane.setBorder(new EmptyBorder JavaDoc(0, 0, 0, 0));
746         
747         ChooseColumnsPanel.installChooseColumnsButton(scrollPane);
748         
749         centerPanel.add(scrollPane, BorderLayout.CENTER);
750         add(centerPanel, BorderLayout.CENTER);
751
752         Action JavaDoc[] actions = getToolBarActions();
753         JToolBar JavaDoc toolbar = UTUtils.createToolbarPresenter(actions);
754         toolbar.setFloatable(false);
755         toolbar.putClientProperty("JToolBar.isRollover", Boolean.TRUE); // NOI18N
756
toolbar.setOrientation(JToolBar.VERTICAL);
757         toolbar.setBorder(new RightSideBorder());
758         add(toolbar, BorderLayout.WEST);
759
760         if (tt.getRowCount() > 0)
761             tt.getSelectionModel().setSelectionInterval(0, 0);
762     }
763
764     /**
765      * Loads filters
766      */

767     protected void loadFilters() {
768         FileSystem fs = Repository.getDefault().getDefaultFileSystem();
769         FileObject fo = fs.findResource("TaskList/" + // NOI18N
770
USER_CATEGORY + "/filters.settings"); // NOI18N
771
assert fo != null : "Missing config TaskList/" + // NOI18N
772
USER_CATEGORY + "/filters.settings"; // NOI18N
773

774         try {
775             DataObject dobj = DataObject.find(fo);
776             InstanceCookie ic = (InstanceCookie) dobj.getCookie(InstanceCookie.class);
777             filters = (FilterRepository) ic.instanceCreate();
778             
779             // filters.addPropertyChangeListener(new PropertyChangeListener() {
780
// public void propertyChange(PropertyChangeEvent evt) {
781
// if (evt.getPropertyName().equals(FilterRepository.PROP_ACTIVE_FILTER)) {
782
// setFilter(filters.getActive());
783
// // setFiltered();
784
// }
785
// }
786
// });
787
filters.setActive(null);
788             
789             // create a default filter if there is none
790
if (filters.size() == 0) {
791                 Filter f = createFilter();
792                 f.setName(DEFAULT_FILTER_NAME);
793                 filters.add(f);
794             }
795             
796         } catch (ClassNotFoundException JavaDoc e) {
797             UTUtils.LOGGER.log(Level.WARNING, "", e); // NOI18N
798
} catch (DataObjectNotFoundException e) {
799             UTUtils.LOGGER.log(Level.WARNING, "", e); // NOI18N
800
} catch (IOException JavaDoc e) {
801             UTUtils.LOGGER.log(Level.WARNING, "", e); // NOI18N
802
}
803     }
804     
805     /**
806      * Called when the object is opened. Add the GUI.
807      */

808     protected void componentOpened() {
809         UserTaskViewRegistry.getInstance().viewOpened(this);
810         if (initialized) {
811             return;
812         }
813         initialized = true;
814
815         UserTaskViewRegistry.getInstance().setLastActivated(this);
816     }
817
818
819     /**
820      * Called when the window is closed. Cleans up.
821      */

822     protected void componentClosed() {
823         UserTask started = StartedUserTask.getInstance().getStarted();
824         if (started != null && started.getList() == getUserTaskList())
825             started.stop();
826         
827         getUserTaskList().destroy();
828         
829         UserTaskViewRegistry.getInstance().viewClosed(this);
830         
831         try {
832             TaskListDataObject do_ = (TaskListDataObject) DataObject.find(file);
833             do_.release();
834         } catch (DataObjectNotFoundException e) {
835             UTUtils.LOGGER.log(Level.SEVERE, e.getMessage(), e);
836         }
837     }
838
839     /**
840      * Shows the TC in the output mode and activates it.
841      */

842     public void showInMode() {
843         if (!isOpened()) {
844             Mode mode = WindowManager.getDefault().findMode("output"); // NOI18N
845
if (mode != null) {
846                 mode.dockInto(UserTaskView.this);
847             }
848         }
849         open();
850         requestVisible();
851         requestActive();
852     }
853
854     /**
855      * Return the tasklist shown in this view
856      *
857      * @return task list
858      */

859     public UserTaskList getUserTaskList() {
860         return this.tasklist;
861     }
862
863     /**
864      * Get the toggle filter for this view. It's
865      * applied if {@link #isFiltered} returns true.
866      *
867      * @return The toggle filter or <code>null</code> if not defined.
868      */

869     public final Filter getFilter() {
870         return activeFilter;
871     }
872
873     /**
874      * Returns the collection of filters assiciated with this view.
875      * @return FilterRepository, never null
876      */

877     public FilterRepository getFilters() {
878         if (filters == null) loadFilters();
879         assert filters != null : "Missing FilterRepository"; // NOI18N
880

881         return filters;
882     }
883     
884     /** Tests if any real filter is applied. */
885     public final boolean isFiltered() {
886         return getFilter() != null;
887     }
888
889     /**
890      * Set the filter to be used (determined by isFiltered) in this view.
891      * @param filter The filter to be set, or null, to remove filtering.
892      */

893     public void setFilter(Filter filter) {
894         if (filter == null || getFilters().contains(filter)) {
895             getFilters().setActive(filter);
896         }
897
898         this.activeFilter = filter;
899         setFiltered();
900     }
901
902     public void requestActive() {
903         super.requestActive();
904         if (tt != null) {
905             tt.requestFocusInWindow();
906         }
907     }
908
909     public void fileRenamed(org.openide.filesystems.FileRenameEvent fe) {
910         SwingUtilities.invokeLater(new Runnable JavaDoc() {
911             public void run() {
912                 UserTaskView.this.updateNameAndToolTip();
913             }
914         });
915     }
916
917     public void fileAttributeChanged(org.openide.filesystems.FileAttributeEvent fe) {
918     }
919
920     public void fileFolderCreated(FileEvent fe) {
921     }
922
923     public void fileDeleted(FileEvent fe) {
924         SwingUtilities.invokeLater(new Runnable JavaDoc() {
925             public void run() {
926                 UserTaskView.this.close();
927             }
928         });
929     }
930
931     public void fileDataCreated(FileEvent fe) {
932     }
933
934     public void fileChanged(FileEvent fe) {
935     }
936     
937     /* check isSliding
938         if (view.getClientProperty("isSliding") == Boolean.TRUE)
939      **/

940     
941     /*
942      * debug Ctrl+C,V,X
943      *
944     private void debugCopyPaste() {
945          if (UTUtils.LOGGER.isLoggable(Level.FINE)) {
946             ActionMap am = this.getActionMap();
947             Object[] actionKeys = am.allKeys();
948             for (int i = 0; i < actionKeys.length; i++) {
949                 Action action = am.get(actionKeys[i]);
950                 UTUtils.LOGGER.fine(actionKeys[i] + " => " + action.getClass());
951             }
952             
953             UTUtils.LOGGER.fine("printing InputMaps:");
954             Component cmp = tt;
955             while (cmp != null) {
956                 UTUtils.LOGGER.fine("checking " + cmp.getClass());
957                 if (cmp instanceof JComponent) {
958                     InputMap keys = ((JComponent) cmp).
959                         getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
960                     if (keys != null) {
961                         UTUtils.LOGGER.fine("InputMap.class: " + keys.getClass());
962                         KeyStroke[] ks = keys.keys();
963                         if (ks != null) {
964                             for (int i = 0; i < ks.length; i++) {
965                                 UTUtils.LOGGER.fine(ks[i] + " " + keys.get(ks[i]));
966                             }
967                         } else {
968                             UTUtils.LOGGER.fine("InputMap.keys() == null");
969                         }
970                     } else {
971                         UTUtils.LOGGER.fine("InputMap == null");
972                     }
973                 }
974                 cmp = cmp.getParent();
975             }
976         }
977     }
978     */

979
980     /**
981      * Configures actions.
982      */

983     private void configureActions() {
984         moveUpAction = new MoveUpAction(this);
985         moveDownAction = new MoveDownAction(this);
986         moveLeftAction = new MoveLeftAction(this);
987         moveRightAction = new MoveRightAction(this);
988         purgeTasksAction = new PurgeTasksAction(this);
989         clearCompletedAction = new ClearCompletedAction(this);
990         newTaskAction = new NewTaskAction(this);
991         showTaskAction = new ShowTaskAction(this);
992         propertiesAction = new UTPropertiesAction(this);
993         pasteAtTopLevelAction = new UTPasteAtTopLevelAction(this);
994         
995         try {
996             saveAction = new UTSaveAction(DataObject.find(file));
997         } catch (DataObjectNotFoundException e) {
998             UTUtils.LOGGER.log(Level.SEVERE, e.getMessage(), e);
999             return;
1000        }
1001        
1002        getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
1003                put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,
1004                InputEvent.CTRL_MASK), "moveUp"); // NOI18N
1005
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
1006                put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,
1007                InputEvent.CTRL_MASK), "moveDown"); // NOI18N
1008
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
1009                put((KeyStroke JavaDoc) newTaskAction.getValue(Action.ACCELERATOR_KEY),
1010                "newTask"); // NOI18N
1011
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
1012                put((KeyStroke JavaDoc) saveAction.getValue(Action.ACCELERATOR_KEY),
1013                "save"); // NOI18N
1014

1015        ActionMap JavaDoc map = getActionMap();
1016        map.put(javax.swing.text.DefaultEditorKit.copyAction,
1017            new UTCopyAction(this));
1018        map.put(javax.swing.text.DefaultEditorKit.cutAction,
1019            new UTCutAction(this));
1020        map.put(javax.swing.text.DefaultEditorKit.pasteAction,
1021            new UTPasteAction(this));
1022
1023        map.put("delete", new UTDeleteAction(tt)); // NOI18N
1024
map.put("moveUp", moveUpAction); // NOI18N
1025
map.put("moveDown", moveDownAction); // NOI18N
1026
map.put("newTask", newTaskAction); // NOI18N
1027
map.put("save", saveAction); // NOI18N
1028

1029        FindAction find = (FindAction) FindAction.get(FindAction.class);
1030        FilterAction filter = (FilterAction)
1031            FilterAction.get(FilterAction.class);
1032        map.put(find.getActionMapKey(), filter);
1033    }
1034}
1035
Popular Tags