KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > swt > widgets > FileDialog


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.swt.widgets;
12
13
14 import org.eclipse.swt.internal.*;
15 import org.eclipse.swt.internal.win32.*;
16 import org.eclipse.swt.*;
17
18 /**
19  * Instances of this class allow the user to navigate
20  * the file system and select or enter a file name.
21  * <dl>
22  * <dt><b>Styles:</b></dt>
23  * <dd>SAVE, OPEN, MULTI</dd>
24  * <dt><b>Events:</b></dt>
25  * <dd>(none)</dd>
26  * </dl>
27  * <p>
28  * Note: Only one of the styles SAVE and OPEN may be specified.
29  * </p><p>
30  * IMPORTANT: This class is intended to be subclassed <em>only</em>
31  * within the SWT implementation.
32  * </p>
33  */

34 public class FileDialog extends Dialog {
35     String JavaDoc [] filterNames = new String JavaDoc [0];
36     String JavaDoc [] filterExtensions = new String JavaDoc [0];
37     String JavaDoc [] fileNames = new String JavaDoc [0];
38     String JavaDoc filterPath = "", fileName = "";
39     static final String JavaDoc FILTER = "*.*";
40     static int BUFFER_SIZE = 1024 * 32;
41     static boolean USE_HOOK;
42
43 /**
44  * Constructs a new instance of this class given only its parent.
45  *
46  * @param parent a shell which will be the parent of the new instance
47  *
48  * @exception IllegalArgumentException <ul>
49  * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
50  * </ul>
51  * @exception SWTException <ul>
52  * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
53  * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
54  * </ul>
55  */

56 public FileDialog (Shell parent) {
57     this (parent, SWT.PRIMARY_MODAL);
58 }
59
60 /**
61  * Constructs a new instance of this class given its parent
62  * and a style value describing its behavior and appearance.
63  * <p>
64  * The style value is either one of the style constants defined in
65  * class <code>SWT</code> which is applicable to instances of this
66  * class, or must be built by <em>bitwise OR</em>'ing together
67  * (that is, using the <code>int</code> "|" operator) two or more
68  * of those <code>SWT</code> style constants. The class description
69  * lists the style constants that are applicable to the class.
70  * Style bits are also inherited from superclasses.
71  * </p>
72  *
73  * @param parent a shell which will be the parent of the new instance
74  * @param style the style of dialog to construct
75  *
76  * @exception IllegalArgumentException <ul>
77  * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
78  * </ul>
79  * @exception SWTException <ul>
80  * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
81  * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
82  * </ul>
83  */

84 public FileDialog (Shell parent, int style) {
85     super (parent, style);
86     checkSubclass ();
87 }
88
89 /**
90  * Returns the path of the first file that was
91  * selected in the dialog relative to the filter path, or an
92  * empty string if no such file has been selected.
93  *
94  * @return the relative path of the file
95  */

96 public String JavaDoc getFileName () {
97     return fileName;
98 }
99
100 /**
101  * Returns a (possibly empty) array with the paths of all files
102  * that were selected in the dialog relative to the filter path.
103  *
104  * @return the relative paths of the files
105  */

106 public String JavaDoc [] getFileNames () {
107     return fileNames;
108 }
109
110 /**
111  * Returns the file extensions which the dialog will
112  * use to filter the files it shows.
113  *
114  * @return the file extensions filter
115  */

116 public String JavaDoc [] getFilterExtensions () {
117     return filterExtensions;
118 }
119
120 /**
121  * Returns the names that describe the filter extensions
122  * which the dialog will use to filter the files it shows.
123  *
124  * @return the list of filter names
125  */

126 public String JavaDoc [] getFilterNames () {
127     return filterNames;
128 }
129
130 /**
131  * Returns the directory path that the dialog will use, or an empty
132  * string if this is not set. File names in this path will appear
133  * in the dialog, filtered according to the filter extensions.
134  *
135  * @return the directory path string
136  *
137  * @see #setFilterExtensions
138  */

139 public String JavaDoc getFilterPath () {
140     return filterPath;
141 }
142
143 int OFNHookProc (int hdlg, int uiMsg, int wParam, int lParam) {
144     switch (uiMsg) {
145         case OS.WM_NOTIFY:
146             OFNOTIFY ofn = new OFNOTIFY ();
147             OS.MoveMemory (ofn, lParam, OFNOTIFY.sizeof);
148             if (ofn.code == OS.CDN_SELCHANGE) {
149                 int lResult = OS.SendMessage (ofn.hwndFrom, OS.CDM_GETSPEC, 0, 0);
150                 if (lResult > 0) {
151                     lResult += OS.MAX_PATH;
152                     OPENFILENAME lpofn = new OPENFILENAME ();
153                     OS.MoveMemory (lpofn, ofn.lpOFN, OPENFILENAME.sizeof);
154                     if (lpofn.nMaxFile < lResult) {
155                         int hHeap = OS.GetProcessHeap ();
156                         int lpstrFile = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, lResult * TCHAR.sizeof);
157                         if (lpstrFile != 0) {
158                             if (lpofn.lpstrFile != 0) OS.HeapFree (hHeap, 0, lpofn.lpstrFile);
159                             lpofn.lpstrFile = lpstrFile;
160                             lpofn.nMaxFile = lResult;
161                             OS.MoveMemory (ofn.lpOFN, lpofn, OPENFILENAME.sizeof);
162                         }
163                     }
164               }
165           }
166           break;
167     }
168     return 0;
169 }
170
171 /**
172  * Makes the dialog visible and brings it to the front
173  * of the display.
174  *
175  * @return a string describing the absolute path of the first selected file,
176  * or null if the dialog was cancelled or an error occurred
177  *
178  * @exception SWTException <ul>
179  * <li>ERROR_WIDGET_DISPOSED - if the dialog has been disposed</li>
180  * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the dialog</li>
181  * </ul>
182  */

183 public String JavaDoc open () {
184     int hHeap = OS.GetProcessHeap ();
185     
186     /* Get the owner HWND for the dialog */
187     int hwndOwner = 0;
188     if (parent != null) hwndOwner = parent.handle;
189
190     /* Convert the title and copy it into lpstrTitle */
191     if (title == null) title = "";
192     /* Use the character encoding for the default locale */
193     TCHAR buffer3 = new TCHAR (0, title, true);
194     int byteCount3 = buffer3.length () * TCHAR.sizeof;
195     int lpstrTitle = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount3);
196     OS.MoveMemory (lpstrTitle, buffer3, byteCount3);
197
198     /* Compute filters and copy into lpstrFilter */
199     String JavaDoc strFilter = "";
200     if (filterNames == null) filterNames = new String JavaDoc [0];
201     if (filterExtensions == null) filterExtensions = new String JavaDoc [0];
202     for (int i=0; i<filterExtensions.length; i++) {
203         String JavaDoc filterName = filterExtensions [i];
204         if (i < filterNames.length) filterName = filterNames [i];
205         strFilter = strFilter + filterName + '\0' + filterExtensions [i] + '\0';
206     }
207     if (filterExtensions.length == 0) {
208         strFilter = strFilter + FILTER + '\0' + FILTER + '\0';
209     }
210     /* Use the character encoding for the default locale */
211     TCHAR buffer4 = new TCHAR (0, strFilter, true);
212     int byteCount4 = buffer4.length () * TCHAR.sizeof;
213     int lpstrFilter = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount4);
214     OS.MoveMemory (lpstrFilter, buffer4, byteCount4);
215     
216     /* Convert the fileName and filterName to C strings */
217     if (fileName == null) fileName = "";
218     /* Use the character encoding for the default locale */
219     TCHAR name = new TCHAR (0, fileName, true);
220
221     /*
222     * Copy the name into lpstrFile and ensure that the
223     * last byte is NULL and the buffer does not overrun.
224     */

225     int nMaxFile = OS.MAX_PATH;
226     if ((style & SWT.MULTI) != 0) nMaxFile = Math.max (nMaxFile, BUFFER_SIZE);
227     int byteCount = nMaxFile * TCHAR.sizeof;
228     int lpstrFile = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount);
229     int byteCountFile = Math.min (name.length () * TCHAR.sizeof, byteCount - TCHAR.sizeof);
230     OS.MoveMemory (lpstrFile, name, byteCountFile);
231
232     /*
233     * Copy the path into lpstrInitialDir and ensure that
234     * the last byte is NULL and the buffer does not overrun.
235     */

236     if (filterPath == null) filterPath = "";
237     /* Use the character encoding for the default locale */
238     TCHAR path = new TCHAR (0, filterPath.replace ('/', '\\'), true);
239     int byteCount5 = OS.MAX_PATH * TCHAR.sizeof;
240     int lpstrInitialDir = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount5);
241     int byteCountDir = Math.min (path.length () * TCHAR.sizeof, byteCount5 - TCHAR.sizeof);
242     OS.MoveMemory (lpstrInitialDir, path, byteCountDir);
243
244     /* Create the file dialog struct */
245     OPENFILENAME struct = new OPENFILENAME ();
246     struct.lStructSize = OPENFILENAME.sizeof;
247     struct.Flags = OS.OFN_HIDEREADONLY | OS.OFN_NOCHANGEDIR;
248     Callback callback = null;
249     if ((style & SWT.MULTI) != 0) {
250         struct.Flags |= OS.OFN_ALLOWMULTISELECT | OS.OFN_EXPLORER;
251         if (!OS.IsWinCE && USE_HOOK) {
252             callback = new Callback (this, "OFNHookProc", 4); //$NON-NLS-1$
253
int lpfnHook = callback.getAddress ();
254             if (lpfnHook == 0) SWT.error (SWT.ERROR_NO_MORE_CALLBACKS);
255             struct.lpfnHook = lpfnHook;
256             struct.Flags |= OS.OFN_ENABLEHOOK;
257         }
258     }
259     struct.hwndOwner = hwndOwner;
260     struct.lpstrTitle = lpstrTitle;
261     struct.lpstrFile = lpstrFile;
262     struct.nMaxFile = nMaxFile;
263     struct.lpstrInitialDir = lpstrInitialDir;
264     struct.lpstrFilter = lpstrFilter;
265     struct.nFilterIndex = 0;
266
267     /*
268     * Set the default extension to an empty string. If the
269     * user fails to type an extension and this extension is
270     * empty, Windows uses the current value of the filter
271     * extension at the time that the dialog is closed.
272     */

273     int lpstrDefExt = 0;
274     boolean save = (style & SWT.SAVE) != 0;
275     if (save) {
276         lpstrDefExt = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, TCHAR.sizeof);
277         struct.lpstrDefExt = lpstrDefExt;
278     }
279     
280     /* Make the parent shell be temporary modal */
281     Shell oldModal = null;
282     Display display = parent.getDisplay ();
283     if ((style & (SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL)) != 0) {
284         oldModal = display.getModalDialogShell ();
285         display.setModalDialogShell (parent);
286     }
287     
288     /*
289     * Feature in Windows. For some reason, the WH_MSGFILTER filter
290     * does not run for GetSaveFileName() or GetOpenFileName(). The
291     * fix is to allow async messages to run in the WH_FOREGROUNDIDLE
292     * hook instead.
293     *
294     * Bug in Windows 98. For some reason, when certain operating
295     * system calls such as Shell_NotifyIcon(), GetOpenFileName()
296     * and GetSaveFileName() are made during the WH_FOREGROUNDIDLE
297     * hook, Windows hangs. The fix is to disallow async messages
298     * during WH_FOREGROUNDIDLE.
299     */

300     boolean oldRunMessagesInIdle = display.runMessagesInIdle;
301     display.runMessagesInIdle = !OS.IsWin95;
302     /*
303     * Open the dialog. If the open fails due to an invalid
304     * file name, use an empty file name and open it again.
305     */

306     boolean success = (save) ? OS.GetSaveFileName (struct) : OS.GetOpenFileName (struct);
307     switch (OS.CommDlgExtendedError ()) {
308         case OS.FNERR_INVALIDFILENAME:
309             OS.MoveMemory (lpstrFile, new TCHAR (0, "", true), TCHAR.sizeof);
310             success = (save) ? OS.GetSaveFileName (struct) : OS.GetOpenFileName (struct);
311             break;
312         case OS.FNERR_BUFFERTOOSMALL:
313             USE_HOOK = true;
314             break;
315     }
316     display.runMessagesInIdle = oldRunMessagesInIdle;
317     
318     /* Clear the temporary dialog modal parent */
319     if ((style & (SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL)) != 0) {
320         display.setModalDialogShell (oldModal);
321     }
322
323     /* Dispose the callback and reassign the buffer */
324     if (callback != null) callback.dispose ();
325     lpstrFile = struct.lpstrFile;
326
327     /* Set the new path, file name and filter */
328     fileNames = new String JavaDoc [0];
329     String JavaDoc fullPath = null;
330     if (success) {
331         
332         /* Use the character encoding for the default locale */
333         TCHAR buffer = new TCHAR (0, struct.nMaxFile);
334         int byteCount1 = buffer.length () * TCHAR.sizeof;
335         OS.MoveMemory (buffer, lpstrFile, byteCount1);
336         
337         /*
338         * Bug in WinCE. For some reason, nFileOffset and nFileExtension
339         * are always zero on WinCE HPC. nFileOffset is always zero on
340         * WinCE PPC when using GetSaveFileName(). nFileOffset is correctly
341         * set on WinCE PPC when using OpenFileName(). The fix is to parse
342         * lpstrFile to calculate nFileOffset.
343         *
344         * Note: WinCE does not support multi-select file dialogs.
345         */

346         int nFileOffset = struct.nFileOffset;
347         if (OS.IsWinCE && nFileOffset == 0) {
348             int index = 0;
349             while (index < buffer.length ()) {
350                 int ch = buffer.tcharAt (index);
351                 if (ch == 0) break;
352                 if (ch == '\\') nFileOffset = index + 1;
353                 index++;
354             }
355         }
356         if (nFileOffset > 0) {
357         
358             /* Use the character encoding for the default locale */
359             TCHAR prefix = new TCHAR (0, nFileOffset - 1);
360             int byteCount2 = prefix.length () * TCHAR.sizeof;
361             OS.MoveMemory (prefix, lpstrFile, byteCount2);
362             filterPath = prefix.toString (0, prefix.length ());
363             
364             /*
365             * Get each file from the buffer. Files are delimited
366             * by a NULL character with 2 NULL characters at the end.
367             */

368             int count = 0;
369             fileNames = new String JavaDoc [(style & SWT.MULTI) != 0 ? 4 : 1];
370             int start = nFileOffset;
371             do {
372                 int end = start;
373                 while (end < buffer.length () && buffer.tcharAt (end) != 0) end++;
374                 String JavaDoc string = buffer.toString (start, end - start);
375                 start = end;
376                 if (count == fileNames.length) {
377                     String JavaDoc [] newFileNames = new String JavaDoc [fileNames.length + 4];
378                     System.arraycopy (fileNames, 0, newFileNames, 0, fileNames.length);
379                     fileNames = newFileNames;
380                 }
381                 fileNames [count++] = string;
382                 if ((style & SWT.MULTI) == 0) break;
383                 start++;
384             } while (start < buffer.length () && buffer.tcharAt (start) != 0);
385             
386             if (fileNames.length > 0) fileName = fileNames [0];
387             String JavaDoc separator = "";
388             int length = filterPath.length ();
389             if (length > 0 && filterPath.charAt (length - 1) != '\\') {
390                 separator = "\\";
391             }
392             fullPath = filterPath + separator + fileName;
393             if (count < fileNames.length) {
394                 String JavaDoc [] newFileNames = new String JavaDoc [count];
395                 System.arraycopy (fileNames, 0, newFileNames, 0, count);
396                 fileNames = newFileNames;
397             }
398         }
399     }
400     
401     /* Free the memory that was allocated. */
402     OS.HeapFree (hHeap, 0, lpstrFile);
403     OS.HeapFree (hHeap, 0, lpstrFilter);
404     OS.HeapFree (hHeap, 0, lpstrInitialDir);
405     OS.HeapFree (hHeap, 0, lpstrTitle);
406     if (lpstrDefExt != 0) OS.HeapFree (hHeap, 0, lpstrDefExt);
407
408     /*
409     * This code is intentionally commented. On some
410     * platforms, the owner window is repainted right
411     * away when a dialog window exits. This behavior
412     * is currently unspecified.
413     */

414 // if (hwndOwner != 0) OS.UpdateWindow (hwndOwner);
415

416     /* Answer the full path or null */
417     return fullPath;
418 }
419
420 /**
421  * Set the initial filename which the dialog will
422  * select by default when opened to the argument,
423  * which may be null. The name will be prefixed with
424  * the filter path when one is supplied.
425  *
426  * @param string the file name
427  */

428 public void setFileName (String JavaDoc string) {
429     fileName = string;
430 }
431
432 /**
433  * Set the file extensions which the dialog will
434  * use to filter the files it shows to the argument,
435  * which may be null.
436  * <p>
437  * The strings are platform specific. For example, on
438  * Windows, an extension filter string is typically of
439  * the form "*.extension", where "*.*" matches all files.
440  * </p>
441  *
442  * @param extensions the file extension filter
443  *
444  * @see #setFilterNames to specify the user-friendly
445  * names corresponding to the extensions
446  */

447 public void setFilterExtensions (String JavaDoc [] extensions) {
448     filterExtensions = extensions;
449 }
450
451 /**
452  * Sets the the names that describe the filter extensions
453  * which the dialog will use to filter the files it shows
454  * to the argument, which may be null.
455  * <p>
456  * Each name is a user-friendly short description shown for
457  * its corresponding filter. The <code>names</code> array must
458  * be the same length as the <code>extensions</code> array.
459  * </p>
460  *
461  * @param names the list of filter names, or null for no filter names
462  *
463  * @see #setFilterExtensions
464  */

465 public void setFilterNames (String JavaDoc [] names) {
466     filterNames = names;
467 }
468
469 /**
470  * Sets the directory path that the dialog will use
471  * to the argument, which may be null. File names in this
472  * path will appear in the dialog, filtered according
473  * to the filter extensions. If the string is null,
474  * then the operating system's default filter path
475  * will be used.
476  * <p>
477  * Note that the path string is platform dependent.
478  * For convenience, either '/' or '\' can be used
479  * as a path separator.
480  * </p>
481  *
482  * @param string the directory path
483  *
484  * @see #setFilterExtensions
485  */

486 public void setFilterPath (String JavaDoc string) {
487     filterPath = string;
488 }
489
490 }
491
Popular Tags