KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > beaninfo > editors > FileArrayEditor


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.beaninfo.editors;
21
22 import java.awt.Component JavaDoc;
23 import java.beans.PropertyChangeEvent JavaDoc;
24 import java.beans.PropertyChangeListener JavaDoc;
25 import java.beans.PropertyEditorSupport JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FilenameFilter JavaDoc;
28 import java.util.logging.Logger JavaDoc;
29 import javax.swing.JFileChooser JavaDoc;
30
31 import org.openide.nodes.Node;
32 import org.openide.explorer.propertysheet.ExPropertyEditor;
33 import org.openide.explorer.propertysheet.PropertyEnv;
34 import org.openide.util.HelpCtx;
35 import org.openide.util.NbBundle;
36
37 /**
38  * PropertyEditor for <code>[java.io.File</code>.
39  *
40  * @author David Strupl
41  */

42 public class FileArrayEditor extends PropertyEditorSupport JavaDoc implements ExPropertyEditor, PropertyChangeListener JavaDoc {
43     
44     /** Openning mode.*/
45     private int mode = JFileChooser.FILES_AND_DIRECTORIES;
46     
47     /** Flag indicating whether to choose directories. Default value is <code>true</code>. */
48     private boolean directories = true;
49     /** Flag indicating whether to choose files. Default value is <code>true</code>. */
50     private boolean files = true;
51     /** Flag indicating whether to hide files marked as hidden. Default value is <code>false</code>. */
52     private boolean fileHiding = false;
53     /** Filter for files to show. */
54     private javax.swing.filechooser.FileFilter JavaDoc fileFilter;
55     /** Current firectory. */
56     private File JavaDoc currentDirectory;
57     /** Base directory to which to show relative path, if is set. */
58     private File JavaDoc baseDirectory;
59
60     /** Cached chooser.
61      * If you don't cache it, MountIterator in core flickers and behaves weirdly,
62      * because apparently PropertyPanel will call getCustomEditor repeatedly and
63      * refresh the display each time.
64      * XXX MountIterator is dead so is this still necessary? -jglick
65      */

66     private JFileChooser JavaDoc chooser;
67     
68     /** whether the value can be edited -- default to true */
69     private boolean editable = true;
70
71     /**
72      * This method is called by the IDE to pass
73      * the environment to the property editor.
74      * @param env Environment passed by the ide.
75      */

76     public void attachEnv(PropertyEnv env) {
77         // clearing to defaults
78
directories = true;
79         files = true;
80         fileFilter = null;
81         fileHiding = false;
82
83         Object JavaDoc dirs = env.getFeatureDescriptor().getValue(FileEditor.PROPERTY_SHOW_DIRECTORIES);
84         if (dirs instanceof Boolean JavaDoc) {
85             directories = ((Boolean JavaDoc)dirs).booleanValue();
86         } // XXX else if != null, warn
87
Object JavaDoc fil = env.getFeatureDescriptor().getValue(FileEditor.PROPERTY_SHOW_FILES);
88         if (fil instanceof Boolean JavaDoc) {
89             files = ((Boolean JavaDoc)fil).booleanValue();
90         } // XXX else if != null, warn
91
Object JavaDoc filter = env.getFeatureDescriptor().getValue(FileEditor.PROPERTY_FILTER);
92         if (filter instanceof FilenameFilter JavaDoc) {
93             fileFilter = new FileEditor.DelegatingFilenameFilter((FilenameFilter JavaDoc)filter);
94         } else if (filter instanceof javax.swing.filechooser.FileFilter JavaDoc) {
95             fileFilter = (javax.swing.filechooser.FileFilter JavaDoc)filter;
96         } else if (filter instanceof java.io.FileFilter JavaDoc) {
97             fileFilter = new FileEditor.DelegatingFileFilter((java.io.FileFilter JavaDoc)filter);
98         } // XXX else if != null, warn
99

100         Object JavaDoc curDir = env.getFeatureDescriptor().getValue(FileEditor.PROPERTY_CURRENT_DIR);
101         if (curDir instanceof File JavaDoc) {
102             currentDirectory = (File JavaDoc)curDir;
103             if(! currentDirectory.isDirectory()) {
104                 Logger.getAnonymousLogger().warning("java.io.File will not accept currentDir=" + baseDirectory); // NOI18N
105
currentDirectory = null;
106             }
107         } // XXX else if != null, warn
108

109         Object JavaDoc baseDir = env.getFeatureDescriptor().getValue(FileEditor.PROPERTY_BASE_DIR);
110         if(baseDir instanceof File JavaDoc) {
111             baseDirectory = (File JavaDoc)baseDir;
112             // As baseDir accept only directories in their absolute form.
113
if(!baseDirectory.isDirectory() || !baseDirectory.isAbsolute()) {
114                 Logger.getAnonymousLogger().warning("java.io.File will not accept baseDir=" + baseDirectory); // NOI18N
115
baseDirectory = null;
116             }
117         } // XXX else if != null, warn
118
if (files) {
119             mode = directories ? JFileChooser.FILES_AND_DIRECTORIES :
120                 JFileChooser.FILES_ONLY;
121         } else {
122             mode = directories ? JFileChooser.DIRECTORIES_ONLY :
123                 JFileChooser.FILES_AND_DIRECTORIES; // both false, what now? XXX warn
124
}
125         
126         Object JavaDoc fileHide = env.getFeatureDescriptor().getValue(FileEditor.PROPERTY_FILE_HIDING);
127         if (fileHide instanceof Boolean JavaDoc) {
128             fileHiding = ((Boolean JavaDoc)fileHide).booleanValue();
129         }
130         
131         if (env.getFeatureDescriptor() instanceof Node.Property){
132             Node.Property prop = (Node.Property)env.getFeatureDescriptor();
133             editable = prop.canWrite();
134         }
135     }
136
137     /** Returns human readable form of the edited value.
138      * @return string reprezentation
139      */

140     public String JavaDoc getAsText() {
141         File JavaDoc[] file = (File JavaDoc[])getValue();
142         if (file == null) {
143             return ""; // NOI18N
144
}
145         StringBuilder JavaDoc path = new StringBuilder JavaDoc("[");
146         for (int i = 0; i < file.length; i++) {
147             path.append(file[i].getPath());
148         }
149         // Dot is more friendly to people though Java itself would prefer blank:
150
if (file.length == 0) path.append('.'); // NOI18N
151
return path.append(']').toString(); // NOI18N
152
}
153     
154     /** Parses the given string and should create a new instance of the
155      * edited object.
156      * @param str string reprezentation of the file (used as a parameter for File).
157      * @throws IllegalArgumentException If the given string cannot be parsed
158      */

159     public void setAsText(String JavaDoc str) throws IllegalArgumentException JavaDoc {
160         if (str == null) {
161             throw new IllegalArgumentException JavaDoc("null"); // NOI18N
162
}
163         if ("".equals(str)) { // NOI18N
164
setValue(null);
165             return;
166         }
167         // See getAsText.
168

169         // [PENDING] Add tokenizer here !!!
170
}
171
172     /** Custon editor.
173      * @return Returns custom editor component.
174      */

175     public Component JavaDoc getCustomEditor() {
176         if (!editable) {
177             return new StringCustomEditor(getAsText(), false);
178         }
179         if (chooser == null) {
180             chooser = FileEditor.createHackedFileChooser();
181             chooser.setMultiSelectionEnabled(true);
182         
183             Object JavaDoc vv = getValue ();
184             File JavaDoc originalFile = null;
185             
186             if (vv instanceof File JavaDoc[]) {
187                 File JavaDoc[] ofile = (File JavaDoc[]) vv;
188                 if (ofile.length > 0) {
189                     originalFile = ofile[0];
190                     if (originalFile != null && ! originalFile.isAbsolute() && baseDirectory != null) {
191                         originalFile = new File JavaDoc(baseDirectory, originalFile.getPath());
192                     }
193                 }
194             }
195             if (currentDirectory != null) {
196                 chooser.setCurrentDirectory (currentDirectory);
197             } else if (originalFile != null && originalFile.getParentFile() != null) {
198                 chooser.setCurrentDirectory (originalFile.getParentFile());
199                 chooser.setSelectedFile (originalFile);
200             } else if (FileEditor.lastCurrentDir != null) {
201                 chooser.setCurrentDirectory(FileEditor.lastCurrentDir);
202             }
203             chooser.setFileSelectionMode(mode);
204             if (fileFilter != null) {
205                 chooser.setFileFilter(fileFilter);
206             }
207             switch (mode) {
208                 case JFileChooser.FILES_AND_DIRECTORIES:
209                     chooser.setDialogTitle (getString ("CTL_DialogTitleFilesAndDirs"));
210                     break;
211                 case JFileChooser.FILES_ONLY:
212                     chooser.setDialogTitle (getString ("CTL_DialogTitleFiles"));
213                     break;
214                 case JFileChooser.DIRECTORIES_ONLY:
215                     chooser.setDialogTitle (getString ("CTL_DialogTitleDirs"));
216                     break;
217             }
218             chooser.setFileHidingEnabled(fileHiding);
219
220             chooser.setControlButtonsAreShown(false);
221
222             chooser.addPropertyChangeListener(this);
223             
224             HelpCtx.setHelpIDString (chooser, getHelpCtx ().getHelpID ());
225         }
226         return chooser;
227     }
228     
229     /** Implements PropertyEditor method.
230      * @return Returns true.
231      */

232     public boolean supportsCustomEditor() {
233         return true;
234     }
235     
236     /** Should create a string insertable to the newly generated source code.
237      * @return initialization string
238      */

239     public String JavaDoc getJavaInitializationString() {
240         File JavaDoc[] value = (File JavaDoc[]) getValue ();
241         if (value == null) {
242             return "null"; // NOI18N
243
} else {
244             // [PENDING] not a full escape of filenames, but enough to at least
245
// handle normal Windows backslashes
246
StringBuilder JavaDoc retVal = new StringBuilder JavaDoc("new java.io.File[] { "); // NOI18N
247
for (int i = 0; i < value.length; i++) {
248                 if (baseDirectory != null && !value[i].isAbsolute()) {
249                     retVal.append("new java.io.File(") // NOI18N
250
.append(FileEditor.stringify(baseDirectory.getPath()))
251                         .append( ", " ) // NOI18N
252
.append(FileEditor.stringify(value[i].getPath()))
253                         .append( "), " ); // NOI18N
254
} else {
255                     retVal.append("new java.io.File(") // NOI18N
256
.append(FileEditor.stringify(value[i].getAbsolutePath()))
257                         .append("), "); // NOI18N
258
}
259             }
260             return retVal.append(" }").toString();
261         }
262     }
263     
264     /** Gets help context. */
265     private HelpCtx getHelpCtx () {
266         return new HelpCtx (FileEditor.class);
267     }
268     
269     /** Gets localized string. Helper method. */
270     private static String JavaDoc getString(String JavaDoc key) {
271         return NbBundle.getBundle(FileArrayEditor.class).getString(key);
272     }
273     
274     /** Property change listaner attached to the JFileChooser chooser. */
275     public void propertyChange(PropertyChangeEvent JavaDoc e) {
276         if (e.getSource() instanceof JFileChooser JavaDoc) {
277             JFileChooser JavaDoc jfc = (JFileChooser JavaDoc) e.getSource();
278             if (mode == jfc.DIRECTORIES_ONLY && jfc.DIRECTORY_CHANGED_PROPERTY.equals(e.getPropertyName())) {
279                 if (jfc.getSelectedFile() == null) {
280                     File JavaDoc dir = jfc.getCurrentDirectory();
281                     if (dir != null) {
282                         setValue (new File JavaDoc[] {new File JavaDoc(dir.getAbsolutePath())});
283                         return;
284                     }
285                 }
286             }
287         }
288         
289         if (( ! JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(e.getPropertyName())) &&
290             ( ! JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(e.getPropertyName()))) {
291                 return;
292         }
293         if (! (e.getSource() instanceof JFileChooser JavaDoc)) {
294             return;
295         }
296         JFileChooser JavaDoc chooser = (JFileChooser JavaDoc)e.getSource();
297         File JavaDoc[] f = (File JavaDoc[])chooser.getSelectedFiles();
298         if (f == null) {
299             return;
300         }
301         
302         if ((f.length == 0) && (chooser.getSelectedFile() != null)) {
303             f = new File JavaDoc[] { chooser.getSelectedFile() };
304         }
305         
306         for (int i = 0; i < f.length; i++) {
307             if (!files && f[i].isFile ()) return;
308             if (!directories && f[i].isDirectory ()) return;
309         }
310
311         if (baseDirectory != null) {
312             for (int i = 0; i < f.length; i++) {
313                 String JavaDoc rel = FileEditor.getChildRelativePath(baseDirectory, f[i]);
314                 if (rel != null) {
315                     f[i] = new File JavaDoc(rel);
316                 }
317             }
318         }
319         
320         File JavaDoc[] nf = new File JavaDoc[f.length];
321         for (int i = 0; i < f.length; i++) {
322             // the next line is
323
// workaround for JDK bug 4533419
324
// it should be returned back to f[i] after the
325
// mentioned bug is fixed in JDK.
326
nf[i] = new File JavaDoc(f[i].getAbsolutePath());
327         }
328         setValue(nf);
329         
330         FileEditor.lastCurrentDir = chooser.getCurrentDirectory();
331     }
332 }
333
Popular Tags