wxFileDialog changed to use (new) wxCHANGE_DIR flag, docs updated
[wxWidgets.git] / src / msw / filedlg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/filedlg.cpp
3 // Purpose: wxFileDialog
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 01/02/97
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "filedlg.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/utils.h"
33 #include "wx/msgdlg.h"
34 #include "wx/dialog.h"
35 #include "wx/filedlg.h"
36 #include "wx/intl.h"
37 #include "wx/log.h"
38 #include "wx/app.h"
39 #endif
40
41 #include "wx/msw/private.h"
42
43 #if !defined(__WIN32__) || defined(__SALFORDC__) || defined(__WXWINE__)
44 #include <commdlg.h>
45 #endif
46
47 #include <math.h>
48 #include <stdlib.h>
49 #include <string.h>
50
51 #include "wx/tokenzr.h"
52
53 // ----------------------------------------------------------------------------
54 // constants
55 // ----------------------------------------------------------------------------
56
57 #ifdef __WIN32__
58 # define wxMAXPATH 4096
59 #else
60 # define wxMAXPATH 1024
61 #endif
62
63 # define wxMAXFILE 1024
64
65 # define wxMAXEXT 5
66
67 // ============================================================================
68 // implementation
69 // ============================================================================
70
71 // ----------------------------------------------------------------------------
72 // wxWin macros
73 // ----------------------------------------------------------------------------
74
75 IMPLEMENT_CLASS(wxFileDialog, wxDialog)
76
77 // ----------------------------------------------------------------------------
78 // global functions
79 // ----------------------------------------------------------------------------
80
81 wxString wxFileSelector(const wxChar *title,
82 const wxChar *defaultDir,
83 const wxChar *defaultFileName,
84 const wxChar *defaultExtension,
85 const wxChar *filter,
86 int flags,
87 wxWindow *parent,
88 int x, int y)
89 {
90 // In the original implementation, defaultExtension is passed to the
91 // lpstrDefExt member of OPENFILENAME. This extension, if non-NULL, is
92 // appended to the filename if the user fails to type an extension. The new
93 // implementation (taken from wxFileSelectorEx) appends the extension
94 // automatically, by looking at the filter specification. In fact this
95 // should be better than the native Microsoft implementation because
96 // Windows only allows *one* default extension, whereas here we do the
97 // right thing depending on the filter the user has chosen.
98
99 // If there's a default extension specified but no filter, we create a
100 // suitable filter.
101
102 wxString filter2;
103 if ( defaultExtension && !filter )
104 filter2 = wxString(wxT("*.")) + defaultExtension;
105 else if ( filter )
106 filter2 = filter;
107
108 wxString defaultDirString;
109 if (defaultDir)
110 defaultDirString = defaultDir;
111
112 wxString defaultFilenameString;
113 if (defaultFileName)
114 defaultFilenameString = defaultFileName;
115
116 wxFileDialog fileDialog(parent, title, defaultDirString,
117 defaultFilenameString, filter2,
118 flags, wxPoint(x, y));
119 if( wxStrlen(defaultExtension) != 0 )
120 {
121 int filterFind = 0,
122 filterIndex = 0;
123
124 for( unsigned int i = 0; i < filter2.Len(); i++ )
125 {
126 if( filter2.GetChar(i) == wxT('|') )
127 {
128 // save the start index of the new filter
129 unsigned int is = i++;
130
131 // find the end of the filter
132 for( ; i < filter2.Len(); i++ )
133 {
134 if(filter2[i] == wxT('|'))
135 break;
136 }
137
138 if( i-is-1 > 0 && is+1 < filter2.Len() )
139 {
140 if( filter2.Mid(is+1,i-is-1).Contains(defaultExtension) )
141 {
142 filterFind = filterIndex;
143 break;
144 }
145 }
146
147 filterIndex++;
148 }
149 }
150
151 fileDialog.SetFilterIndex(filterFind);
152 }
153
154 wxString filename;
155 if ( fileDialog.ShowModal() == wxID_OK )
156 {
157 filename = fileDialog.GetPath();
158 }
159
160 return filename;
161 }
162
163
164 wxString wxFileSelectorEx(const wxChar *title,
165 const wxChar *defaultDir,
166 const wxChar *defaultFileName,
167 int* defaultFilterIndex,
168 const wxChar *filter,
169 int flags,
170 wxWindow* parent,
171 int x,
172 int y)
173
174 {
175 wxFileDialog fileDialog(parent,
176 title ? title : wxT(""),
177 defaultDir ? defaultDir : wxT(""),
178 defaultFileName ? defaultFileName : wxT(""),
179 filter ? filter : wxT(""),
180 flags, wxPoint(x, y));
181
182 wxString filename;
183 if ( fileDialog.ShowModal() == wxID_OK )
184 {
185 if ( defaultFilterIndex )
186 *defaultFilterIndex = fileDialog.GetFilterIndex();
187
188 filename = fileDialog.GetPath();
189 }
190
191 return filename;
192 }
193
194 wxFileDialog::wxFileDialog(wxWindow *parent, const wxString& message,
195 const wxString& defaultDir, const wxString& defaultFileName, const wxString& wildCard,
196 long style, const wxPoint& pos)
197 {
198 m_message = message;
199 m_dialogStyle = style;
200 if ( ( m_dialogStyle & wxMULTIPLE ) && ( m_dialogStyle & wxSAVE ) )
201 m_dialogStyle &= ~wxMULTIPLE;
202 m_parent = parent;
203 m_path = wxT("");
204 m_fileName = defaultFileName;
205 m_dir = defaultDir;
206 m_wildCard = wildCard;
207 m_filterIndex = 0;
208 }
209
210 void wxFileDialog::GetPaths(wxArrayString& paths) const
211 {
212 paths.Empty();
213
214 wxString dir(m_dir);
215 if ( m_dir.Last() != _T('\\') )
216 dir += _T('\\');
217
218 size_t count = m_fileNames.GetCount();
219 for ( size_t n = 0; n < count; n++ )
220 {
221 paths.Add(dir + m_fileNames[n]);
222 }
223 }
224
225 int wxFileDialog::ShowModal()
226 {
227 HWND hWnd = 0;
228 if (m_parent) hWnd = (HWND) m_parent->GetHWND();
229 if (!hWnd && wxTheApp->GetTopWindow())
230 hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();
231
232 static wxChar fileNameBuffer [ wxMAXPATH ]; // the file-name
233 wxChar titleBuffer [ wxMAXFILE+1+wxMAXEXT ]; // the file-name, without path
234
235 *fileNameBuffer = wxT('\0');
236 *titleBuffer = wxT('\0');
237
238 long msw_flags = 0;
239 if ( (m_dialogStyle & wxHIDE_READONLY) || (m_dialogStyle & wxSAVE) )
240 msw_flags |= OFN_HIDEREADONLY;
241 if ( m_dialogStyle & wxFILE_MUST_EXIST )
242 msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
243 if (m_dialogStyle & wxMULTIPLE )
244 msw_flags |=
245 #if defined(OFN_EXPLORER)
246 OFN_EXPLORER |
247 #endif // OFN_EXPLORER
248 OFN_ALLOWMULTISELECT;
249 if ( !(m_dialogStyle & wxCHANGE_DIR) )
250 msw_flags |= OFN_NOCHANGEDIR;
251
252 OPENFILENAME of;
253 wxZeroMemory(of);
254
255 // the OPENFILENAME struct has been extended in newer version of
256 // comcdlg32.dll, but as we don't use the extended fields anyhow, set
257 // the struct size to the old value - otherwise, the programs compiled
258 // with new headers will not work with the old libraries
259 #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0500)
260 of.lStructSize = sizeof(OPENFILENAME) -
261 (sizeof(void *) + 2*sizeof(DWORD));
262 #else // old headers
263 of.lStructSize = sizeof(OPENFILENAME);
264 #endif
265
266 of.hwndOwner = hWnd;
267 of.lpstrTitle = WXSTRINGCAST m_message;
268 of.lpstrFileTitle = titleBuffer;
269 of.nMaxFileTitle = wxMAXFILE + 1 + wxMAXEXT; // Windows 3.0 and 3.1
270
271 // Convert forward slashes to backslashes (file selector doesn't like
272 // forward slashes)
273 size_t i = 0;
274 size_t len = m_dir.Length();
275 for (i = 0; i < len; i++)
276 if (m_dir[i] == wxT('/'))
277 m_dir[i] = wxT('\\');
278
279 of.lpstrInitialDir = m_dir.c_str();
280
281 of.Flags = msw_flags;
282
283
284 //=== Like Alejandro Sierra's wildcard modification >>===================
285 /*
286 In wxFileSelector you can put, instead of a single wild_card,
287 pairs of strings separated by '|'.
288 The first string is a description, and the
289 second is the wild card. You can put any number of pairs.
290
291 eg. "description1 (*.ex1)|*.ex1|description2 (*.ex2)|*.ex2"
292
293 If you put a single wild card, it works as before the modification.
294 */
295 //=======================================================================
296
297 wxString theFilter;
298 if ( wxStrlen(m_wildCard) == 0 )
299 theFilter = wxString(wxT("*.*"));
300 else
301 theFilter = m_wildCard ;
302 wxString filterBuffer;
303
304 if ( !wxStrchr( theFilter, wxT('|') ) ) { // only one filter ==> default text
305 filterBuffer.Printf(_("Files (%s)|%s"),
306 theFilter.c_str(), theFilter.c_str());
307 }
308 else { // more then one filter
309 filterBuffer = theFilter;
310
311 }
312
313 filterBuffer += wxT("|");
314 // Replace | with \0
315 for (i = 0; i < filterBuffer.Len(); i++ ) {
316 if ( filterBuffer.GetChar(i) == wxT('|') ) {
317 filterBuffer[i] = wxT('\0');
318 }
319 }
320
321 of.lpstrFilter = (LPTSTR)(const wxChar *)filterBuffer;
322 of.nFilterIndex = m_filterIndex + 1;
323
324 //=== Setting defaultFileName >>=========================================
325
326 wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 );
327 fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0');
328
329 of.lpstrFile = fileNameBuffer; // holds returned filename
330 of.nMaxFile = wxMAXPATH;
331
332 //== Execute FileDialog >>=================================================
333
334 bool success = (m_dialogStyle & wxSAVE ? GetSaveFileName(&of)
335 : GetOpenFileName(&of)) != 0;
336
337 DWORD errCode = CommDlgExtendedError();
338
339 #ifdef __WIN32__
340 if (!success && (errCode == CDERR_STRUCTSIZE))
341 {
342 // The struct size has changed so try a smaller or bigger size
343
344 int oldStructSize = of.lStructSize;
345 of.lStructSize = oldStructSize - (sizeof(void *) + 2*sizeof(DWORD));
346 success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
347 : (GetOpenFileName(&of) != 0);
348 errCode = CommDlgExtendedError();
349
350 if (!success && (errCode == CDERR_STRUCTSIZE))
351 {
352 of.lStructSize = oldStructSize + (sizeof(void *) + 2*sizeof(DWORD));
353 success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
354 : (GetOpenFileName(&of) != 0);
355 }
356 }
357 #endif
358
359 if ( success )
360 {
361 m_fileNames.Empty();
362
363 if ( ( m_dialogStyle & wxMULTIPLE ) &&
364 #if defined(OFN_EXPLORER)
365 ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') ) )
366 #else
367 ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') ) )
368 #endif // OFN_EXPLORER
369 {
370 #if defined(OFN_EXPLORER)
371 m_dir = fileNameBuffer;
372 i = of.nFileOffset;
373 m_fileName = &fileNameBuffer[i];
374 m_fileNames.Add(m_fileName);
375 i += m_fileName.Len() + 1;
376
377 while (fileNameBuffer[i] != wxT('\0'))
378 {
379 m_fileNames.Add(&fileNameBuffer[i]);
380 i += wxStrlen(&fileNameBuffer[i]) + 1;
381 }
382 #else
383 wxStringTokenizer toke(fileNameBuffer, " \t\r\n");
384 m_dir = toke.GetNextToken();
385 m_fileName = toke.GetNextToken();
386 m_fileNames.Add(m_fileName);
387
388 while (toke.HasMoreTokens())
389 m_fileNames.Add(toke.GetNextToken());
390 #endif // OFN_EXPLORER
391
392 wxString dir(m_dir);
393 if ( m_dir.Last() != _T('\\') )
394 dir += _T('\\');
395
396 m_fileNames.Sort();
397 m_path = dir + m_fileName;
398 }
399 else
400 {
401 const wxChar* extension = NULL;
402
403 //=== Adding the correct extension >>=================================
404
405 m_filterIndex = (int)of.nFilterIndex - 1;
406
407 if ( !of.nFileExtension || (of.nFileExtension && fileNameBuffer[ of.nFileExtension-1] != wxT('.')) )
408 { // user has typed an filename
409 // without an extension:
410
411 int maxFilter = (int)(of.nFilterIndex*2L-1L);
412 extension = filterBuffer;
413
414 for( int i = 0; i < maxFilter; i++ ) { // get extension
415 extension = extension + wxStrlen( extension ) +1;
416 }
417
418 extension = wxStrrchr( extension, wxT('.') );
419 if ( extension // != "blabla"
420 && !wxStrrchr( extension, wxT('*') ) // != "blabla.*"
421 && !wxStrrchr( extension, wxT('?') ) // != "blabla.?"
422 && extension[1] // != "blabla."
423 && extension[1] != wxT(' ') ) // != "blabla. "
424 {
425 // now concat extension to the fileName:
426 m_fileName = wxString(fileNameBuffer) + extension;
427
428 int len = wxStrlen( fileNameBuffer );
429 wxStrncpy( fileNameBuffer + len, extension, wxMAXPATH - len );
430 fileNameBuffer[ wxMAXPATH -1 ] = wxT('\0');
431 }
432 }
433
434 m_path = fileNameBuffer;
435 m_fileName = wxFileNameFromPath(fileNameBuffer);
436 m_fileNames.Add(m_fileName);
437 m_dir = wxPathOnly(fileNameBuffer);
438 }
439
440
441 //=== Simulating the wxOVERWRITE_PROMPT >>============================
442
443 if ( (m_dialogStyle & wxOVERWRITE_PROMPT) &&
444 ::wxFileExists( fileNameBuffer ) )
445 {
446 wxString messageText;
447 messageText.Printf(_("Replace file '%s'?"), fileNameBuffer);
448
449 if ( wxMessageBox(messageText, m_message, wxYES_NO ) != wxYES )
450 {
451 success = FALSE;
452 }
453 }
454
455 }
456 else
457 {
458 // common dialog failed - why?
459 #ifdef __WXDEBUG__
460 DWORD dwErr = CommDlgExtendedError();
461 if ( dwErr != 0 )
462 {
463 // this msg is only for developers
464 wxLogError(wxT("Common dialog failed with error code %0lx."),
465 dwErr);
466 }
467 //else: it was just cancelled
468 #endif
469 }
470
471 return success ? wxID_OK : wxID_CANCEL;
472
473 }
474
475 // Generic file load/save dialog (for internal use only)
476 static
477 wxString wxDefaultFileSelector(bool load,
478 const wxChar *what,
479 const wxChar *extension,
480 const wxChar *default_name,
481 wxWindow *parent)
482 {
483 wxString prompt;
484 wxString str;
485 if (load) str = _("Load %s file");
486 else str = _("Save %s file");
487 prompt.Printf(str, what);
488
489 const wxChar *ext = extension;
490 if (*ext == wxT('.'))
491 ext++;
492
493 wxString wild;
494 wild.Printf(wxT("*.%s"), ext);
495
496 return wxFileSelector (prompt, NULL, default_name, ext, wild, 0, parent);
497 }
498
499 // Generic file load dialog
500 WXDLLEXPORT wxString wxLoadFileSelector(const wxChar *what,
501 const wxChar *extension,
502 const wxChar *default_name,
503 wxWindow *parent)
504 {
505 return wxDefaultFileSelector(TRUE, what, extension, default_name, parent);
506 }
507
508 // Generic file save dialog
509 WXDLLEXPORT wxString wxSaveFileSelector(const wxChar *what,
510 const wxChar *extension,
511 const wxChar *default_name,
512 wxWindow *parent)
513 {
514 return wxDefaultFileSelector(FALSE, what, extension, default_name, parent);
515 }
516
517