KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > favorites > Actions


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.favorites;
21
22 import java.awt.Image JavaDoc;
23 import java.awt.event.ActionEvent JavaDoc;
24 import java.beans.PropertyVetoException JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.List JavaDoc;
29 import javax.swing.AbstractAction JavaDoc;
30 import javax.swing.Action JavaDoc;
31 import javax.swing.ImageIcon JavaDoc;
32 import javax.swing.JFileChooser JavaDoc;
33 import javax.swing.JMenuItem JavaDoc;
34 import javax.swing.SwingUtilities JavaDoc;
35 import org.openide.DialogDisplayer;
36 import org.openide.NotifyDescriptor;
37 import org.openide.filesystems.FileObject;
38 import org.openide.filesystems.FileStateInvalidException;
39 import org.openide.filesystems.FileUtil;
40 import org.openide.loaders.DataFolder;
41 import org.openide.loaders.DataObject;
42 import org.openide.loaders.DataObjectNotFoundException;
43 import org.openide.loaders.DataShadow;
44 import org.openide.nodes.Node;
45 import org.openide.util.Exceptions;
46 import org.openide.util.HelpCtx;
47 import org.openide.util.NbBundle;
48 import org.openide.util.Utilities;
49 import org.openide.util.actions.NodeAction;
50 import org.openide.windows.TopComponent;
51 import org.openide.windows.WindowManager;
52
53 /** List of all actions available for Favorites module.
54 * @author Jaroslav Tulach
55 */

56 public final class Actions extends Object JavaDoc {
57     
58     /** Used to keep current dir from JFileChooser for Add to Favorites action
59      * on root node. */

60     private static File JavaDoc currentDir = null;
61     
62     private Actions () {
63         // noinstances
64
}
65     
66     public static Action JavaDoc view () { return View.getDefault(); }
67     public static Action JavaDoc add () { return Add.getDefault(); }
68     public static Action JavaDoc addOnFavoritesNode () { return AddOnFavoritesNode.getDefault(); }
69     public static Action JavaDoc remove () { return Remove.getDefault(); }
70     public static Action JavaDoc select () { return Select.getDefault(); }
71     
72     /**
73      * Action which opend <code>CurrentProjectNode.ProjectsTab</code> default component.
74      *
75      * @author Peter Zavadsky
76      */

77     private static class View extends AbstractAction JavaDoc implements HelpCtx.Provider {
78         
79         private static final View VIEW = new View ();
80         
81         public View() {
82             putValue(NAME, NbBundle.getMessage(Actions.class,
83                     "ACT_View"));
84             Image JavaDoc image = Utilities.loadImage("org/netbeans/modules/favorites/resources/actionView.gif"); // NOI18N
85
putValue(SMALL_ICON, image != null ? new ImageIcon JavaDoc(image) : null);
86         }
87         
88         public static Action JavaDoc getDefault () {
89             return VIEW;
90         }
91         
92         public void actionPerformed(ActionEvent JavaDoc evt) {
93             final TopComponent projectsTab = Tab.findDefault();
94             projectsTab.open();
95             projectsTab.requestActive();
96         }
97
98         public HelpCtx getHelpCtx() {
99             return new HelpCtx(View.class);
100         }
101     } // end of View
102

103     
104     /** An action which selects activated nodes in the Explorer's tab.
105     * @author Dusan Balek
106     */

107     private static class Select extends NodeAction {
108         private static final Select SELECT = new Select ();
109         
110         public static Action JavaDoc getDefault () {
111             return SELECT;
112         }
113         
114         private Select () {
115             super();
116             putValue("noIconInMenu", Boolean.TRUE); //NOI18N
117
}
118         
119         protected void performAction(Node[] activatedNodes) {
120             Tab proj = Tab.findDefault();
121             proj.open();
122             proj.requestActive();
123             proj.doSelectNode((DataObject)activatedNodes[0].getCookie(DataObject.class));
124         }
125
126         protected boolean enable(Node[] activatedNodes) {
127             if (activatedNodes.length != 1) {
128                 return false;
129             }
130             return true;
131             /*
132             DataObject dobj = (DataObject)activatedNodes[0].getCookie(DataObject.class);
133             if (dobj == null) {
134                 return false;
135             }
136             return Tab.findDefault().containsNode(dobj);
137              */

138           }
139
140         public String JavaDoc getName() {
141             return NbBundle.getMessage(Select.class, "ACT_Select_Main_Menu"); // NOI18N
142
}
143
144         /** Overriden to have different title in popup menu, works but ugly a bit */
145         public JMenuItem JavaDoc getPopupPresenter() {
146             JMenuItem JavaDoc mi = super.getPopupPresenter();
147             mi.setText(NbBundle.getMessage(Select.class, "ACT_Select")); // NOI18N
148
return mi;
149         }
150
151         protected String JavaDoc iconResource() {
152             return "org/netbeans/modules/favorites/resources/actionSelect.gif"; // NOI18N
153
}
154
155         public HelpCtx getHelpCtx() {
156             return null;
157         }
158
159         protected boolean asynchronous() {
160             return false;
161         }
162
163     } // end of Select
164

165     /** Removes root link from favorites
166     * @author Jaroslav Tulach
167     */

168     private static class Remove extends NodeAction {
169         static final long serialVersionUID =-6471281373153172312L;
170         /** generated Serialized Version UID */
171         // static final long serialVersionUID = -5280204757097896304L;
172

173         private static final Remove REMOVE = new Remove ();
174         
175         public static Action JavaDoc getDefault () {
176             return REMOVE;
177         }
178         
179         /** Enabled only if the current project is ProjectDataObject.
180         */

181         public boolean enable (Node[] arr) {
182             if ((arr == null) || (arr.length == 0)) return false;
183
184             for (int i = 0; i < arr.length; i++) {
185                 DataObject shad = (DataObject) arr[i].getCookie (DataObject.class);
186                 //Disable when node is not shadow in Favorites folder.
187
if (shad == null || shad.getFolder() != Favorites.getFolder()) {
188                     return false;
189                 }
190             }
191             return true;
192         }
193
194         /** Human presentable name of the action. This should be
195         * presented as an item in a menu.
196         * @return the name of the action
197         */

198         public String JavaDoc getName() {
199             return NbBundle.getMessage (
200                     Actions.class, "ACT_Remove"); // NOI18N
201
}
202
203         /** Help context where to find more about the action.
204         * @return the help context for this action
205         */

206         public HelpCtx getHelpCtx() {
207             return new HelpCtx(Remove.class);
208         }
209
210         /**
211         * Removes the links.
212         *
213         * @param arr gives array of actually activated nodes.
214         */

215         protected void performAction (Node[] arr) {
216             for (int i = 0; i < arr.length; i++) {
217                 DataObject shad = (DataObject) arr[i].getCookie(DataObject.class);
218
219                 if (shad != null && shad.getFolder() == Favorites.getFolder()) {
220                     try {
221                         shad.delete();
222                     }
223                     catch (IOException JavaDoc ex) {
224                         Exceptions.printStackTrace(ex);
225                     }
226                 }
227             }
228         }
229
230         protected boolean asynchronous() {
231             return false;
232         }
233
234     } // end of Remove
235

236     /** Adds something to favorites. Made public so it can be referenced
237     * directly from manifest.
238     *
239     * @author Jaroslav Tulach
240     */

241     public static class Add extends NodeAction {
242         static final long serialVersionUID =-6471281373153172312L;
243         /** generated Serialized Version UID */
244         // static final long serialVersionUID = -5280204757097896304L;
245
private static final Add ADD = new Add ();
246         
247         public static Action JavaDoc getDefault () {
248             return ADD;
249         }
250         
251         private Add () {
252             putValue("noIconInMenu", Boolean.TRUE); // NOI18N
253
}
254         
255         /** Enabled only if the current project is ProjectDataObject.
256         */

257         public boolean enable (Node[] arr) {
258             if ((arr == null) || (arr.length == 0)) return false;
259             if (arr.length == 1 && arr[0] instanceof Favorites) return true;
260                 
261             
262
263             for (int i = 0; i < arr.length; i++) {
264                 DataObject dataObject = (DataObject) arr[i].getCookie (DataObject.class);
265                 //Action is disabled for root folder eg:"/" on Linux or "C:" on Win
266
if (dataObject == null) {
267                     return false;
268                 }
269                 FileObject fo = dataObject.getPrimaryFile();
270                 if (fo != null) {
271                     //Allow to link only once
272
if (isInFavorites(fo)) {
273                         return false;
274                     }
275                     //Check if it is root.
276
File JavaDoc file = FileUtil.toFile(fo);
277                     if (file != null) {
278                         if (file.getParent() == null) {
279                             //It is root: disable.
280
return false;
281                         }
282                     }
283                 }
284
285                 // Fix #14740 disable action on SystemFileSystem.
286
try {
287                     if(dataObject.getPrimaryFile().getFileSystem().isDefault()) {
288                         return false;
289                     }
290                 } catch(FileStateInvalidException fsie) {
291                     return false;
292                 }
293             }
294             return true;
295         }
296         
297         /** Check if given fileobject is already linked in favorites
298          * @return true if given fileobject is already linked
299          */

300         private boolean isInFavorites (FileObject fo) {
301             DataFolder f = Favorites.getFolder();
302             
303             DataObject [] arr = f.getChildren();
304             for (int i = 0; i < arr.length; i++) {
305                 if (arr[i] instanceof DataShadow) {
306                     if (fo.equals(((DataShadow) arr[i]).getOriginal().getPrimaryFile())) {
307                         return true;
308                     }
309                 }
310             }
311             return false;
312         }
313         
314         /** Human presentable name of the action. This should be
315         * presented as an item in a menu.
316         * @return the name of the action
317         */

318         public String JavaDoc getName() {
319             return NbBundle.getMessage (
320                     Actions.class, "ACT_Add"); // NOI18N
321
}
322
323         /** Help context where to find more about the action.
324         * @return the help context for this action
325         */

326         public HelpCtx getHelpCtx() {
327             return new HelpCtx(Add.class);
328         }
329
330         /**
331         * Standard perform action extended by actually activated nodes.
332         *
333         * @param activatedNodes gives array of actually activated nodes.
334         */

335         protected void performAction (final Node[] activatedNodes) {
336             final DataFolder f = Favorites.getFolder();
337             final DataObject [] arr = f.getChildren();
338             final List JavaDoc<DataObject> listAdd = new ArrayList JavaDoc<DataObject>();
339             
340             DataObject createdDO = null;
341             Node[] toShadows = activatedNodes;
342
343             try {
344                 if (activatedNodes.length == 1 && activatedNodes[0] instanceof Favorites) {
345                     // show JFileChooser
346
FileObject fo = chooseFileObject();
347                     if (fo == null) return;
348                     toShadows = new Node[] {DataObject.find(fo).getNodeDelegate()};
349                 }
350                 
351                 
352                 createdDO = createShadows(f, toShadows, listAdd);
353                 
354                 //This is done to set desired order of nodes in view
355
reorderAfterAddition(f, arr, listAdd);
356                 selectAfterAddition(createdDO);
357             } catch (DataObjectNotFoundException e) {
358                 Exceptions.printStackTrace(e);
359             }
360         }
361         
362         /**
363          *
364          * @return FileObject or null if FileChooser dialog is cancelled
365          */

366         private static FileObject chooseFileObject() {
367             FileObject retVal = null;
368             File JavaDoc chooserSelection = null;
369             JFileChooser JavaDoc chooser = new JFileChooser JavaDoc ();
370             chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
371             chooser.setDialogTitle(NbBundle.getBundle(Actions.class).getString ("CTL_DialogTitle"));
372             chooser.setApproveButtonText(NbBundle.getBundle(Actions.class).getString ("CTL_ApproveButtonText"));
373             if (currentDir != null) {
374                 chooser.setCurrentDirectory(currentDir);
375             }
376             int option = chooser.showOpenDialog( WindowManager.getDefault().getMainWindow() ); // Show the chooser
377
if ( option == JFileChooser.APPROVE_OPTION ) {
378                 chooserSelection = chooser.getSelectedFile();
379                 File JavaDoc selectedFile = FileUtil.normalizeFile(chooserSelection);
380                 //Workaround for JDK bug #5075580 (filed also in IZ as #46882)
381
if (!selectedFile.exists()) {
382                     if ((selectedFile.getParentFile() != null) && selectedFile.getParentFile().exists()) {
383                         if (selectedFile.getName().equals(selectedFile.getParentFile().getName())) {
384                             selectedFile = selectedFile.getParentFile();
385                         }
386                     }
387                 }
388                 //#50482: Check if selected file exists eg. user can enter any file name to text box.
389
if (!selectedFile.exists()) {
390                     String JavaDoc message = NbBundle.getMessage(Actions.class,"ERR_FileDoesNotExist",selectedFile.getPath());
391                     String JavaDoc title = NbBundle.getMessage(Actions.class,"ERR_FileDoesNotExistDlgTitle");
392                     DialogDisplayer.getDefault().notify
393                     (new NotifyDescriptor(message,title,NotifyDescriptor.DEFAULT_OPTION,
394                     NotifyDescriptor.INFORMATION_MESSAGE, new Object JavaDoc[] { NotifyDescriptor.CLOSED_OPTION },
395                     NotifyDescriptor.OK_OPTION));
396                 } else {
397                     retVal = FileUtil.toFileObject(selectedFile);
398                     assert retVal != null;
399                 }
400             }
401             currentDir = chooser.getCurrentDirectory();
402             return retVal;
403         }
404         
405         private void selectAfterAddition(final DataObject createdDO) {
406             final Tab projectsTab = Tab.findDefault();
407             projectsTab.open();
408             projectsTab.requestActive();
409             //Try to locate newly added node and select it
410
if (createdDO != null) {
411                 Node n = Favorites.getNode();
412                 Node [] nodes = projectsTab.getExplorerManager().getRootContext().getChildren().getNodes(true);
413                 final Node [] toSelect = new Node[1];
414                 boolean setSelected = false;
415                 for (int i = 0; i < nodes.length; i++) {
416                     if (createdDO.getName().equals(nodes[i].getName())) {
417                         toSelect[0] = nodes[i];
418                         setSelected = true;
419                         break;
420                     }
421                 }
422                 if (setSelected) {
423                     SwingUtilities.invokeLater(new Runnable JavaDoc () {
424                         public void run() {
425                             try {
426                                 projectsTab.getExplorerManager().setExploredContextAndSelection(toSelect[0],toSelect);
427                             } catch (PropertyVetoException JavaDoc ex) {
428                                 //Nothing to do
429
}
430                         }
431                     });
432                 }
433             }
434         }
435
436         private static DataObject createShadows(final DataFolder favourities, final Node[] activatedNodes, final List JavaDoc<DataObject> listAdd) {
437             DataObject createdDO = null;
438             for (int i = 0; i < activatedNodes.length; i++) {
439                 DataObject obj = (DataObject) activatedNodes[i].getCookie(DataObject.class);
440
441                 if (obj != null) {
442                     try {
443                         if (createdDO == null) {
444                             // Select only first node in array added to favorites
445
createdDO = obj.createShadow(favourities);
446                             listAdd.add(createdDO);
447                         } else {
448                             listAdd.add(obj.createShadow(favourities));
449                         }
450                     }
451                     catch (IOException JavaDoc ex) {
452                         Exceptions.printStackTrace(ex);
453                     }
454                 }
455             }
456             return createdDO;
457         }
458
459         private static void reorderAfterAddition(final DataFolder favourities, final DataObject[] children, final List JavaDoc<DataObject> listAdd) {
460             List JavaDoc<DataObject> listDest = new ArrayList JavaDoc<DataObject>();
461             if (listAdd.size() > 0) {
462                 //Insert new nodes just before last (root) node
463
DataObject root = null;
464                 //Find root
465
for (int i = 0; i < children.length; i++) {
466                     FileObject fo = children[i].getPrimaryFile();
467                     if ("Favorites/Root.instance".equals(fo.getPath())) { //NOI18N
468
root = children[i];
469                     }
470                 }
471                 if (root != null) {
472                     for (int i = 0; i < children.length; i++) {
473                         if (!root.equals(children[i])) {
474                             listDest.add(children[i]);
475                         }
476                     }
477                     listDest.addAll(listAdd);
478                     listDest.add(root);
479                 } else {
480                     //Root not found. It should not happen because root is defined in layer
481
for (int i = 0; i < children.length; i++) {
482                         listDest.add(children[i]);
483                     }
484                     listDest.addAll(listAdd);
485                 }
486                 //Set desired order
487
DataObject [] newOrder = listDest.toArray(new DataObject[listDest.size()]);
488                 try {
489                     favourities.setOrder(newOrder);
490                 } catch (IOException JavaDoc ex) {
491                     Exceptions.printStackTrace(ex);
492                 }
493             }
494         }
495
496         protected boolean asynchronous() {
497             return false;
498         }
499
500     } // end of Add
501

502     /** Subclass of Add. Only its display name is different otherwise the same as Add.
503     *
504     * @author Marek Slama
505     */

506     public static class AddOnFavoritesNode extends Add {
507         static final long serialVersionUID =-6471284573153172312L;
508         
509         private static final AddOnFavoritesNode ADD_ON_FAVORITES_NODE = new AddOnFavoritesNode ();
510         
511         public static Action JavaDoc getDefault () {
512             return ADD_ON_FAVORITES_NODE;
513         }
514         
515         /** Human presentable name of the action. This should be
516         * presented as an item in a menu.
517         * @return the name of the action
518         */

519         public String JavaDoc getName() {
520             return NbBundle.getMessage (
521                     Actions.class, "ACT_AddOnFavoritesNode"); // NOI18N
522
}
523     }
524     
525 }
526
Popular Tags