]> git.saurik.com Git - wxWidgets.git/blob - src/msw/filedlg.cpp
umph, had made a dangerous mistake
[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 = 1,
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 filterIndex++;
131
132 // find the end of the filter
133 for( ; i < filter2.Len(); i++ )
134 {
135 if(filter2[i] == wxT('|'))
136 break;
137 }
138
139 if( i-is-1 > 0 && is+1 < filter2.Len() )
140 {
141 if( filter2.Mid(is+1,i-is-1).Contains(defaultExtension) )
142 // if( filter2.Mid(is+1,i-is-1) == defaultExtension )
143 {
144 filterFind = filterIndex;
145 break;
146 }
147 }
148 }
149 }
150
151 fileDialog.SetFilterIndex(filterFind);
152 }
153
154 if ( fileDialog.ShowModal() == wxID_OK )
155 {
156 wxStrcpy(wxBuffer, (const wxChar *)fileDialog.GetPath());
157 return wxBuffer;
158 }
159 else
160 return wxGetEmptyString();
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, title ? title : wxT(""), defaultDir ? defaultDir : wxT(""),
176 defaultFileName ? defaultFileName : wxT(""), filter ? filter : wxT(""), flags, wxPoint(x, y));
177
178 if ( fileDialog.ShowModal() == wxID_OK )
179 {
180 *defaultFilterIndex = fileDialog.GetFilterIndex();
181 wxStrcpy(wxBuffer, (const wxChar *)fileDialog.GetPath());
182 return wxBuffer;
183 }
184 else
185 return wxGetEmptyString();
186 }
187
188 wxFileDialog::wxFileDialog(wxWindow *parent, const wxString& message,
189 const wxString& defaultDir, const wxString& defaultFileName, const wxString& wildCard,
190 long style, const wxPoint& pos)
191 {
192 m_message = message;
193 m_dialogStyle = style;
194 if ( ( m_dialogStyle & wxMULTIPLE ) && ( m_dialogStyle & wxSAVE ) )
195 m_dialogStyle &= ~wxMULTIPLE;
196 m_parent = parent;
197 m_path = wxT("");
198 m_fileName = defaultFileName;
199 m_dir = defaultDir;
200 m_wildCard = wildCard;
201 m_filterIndex = 0;
202 }
203
204 void wxFileDialog::GetPaths(wxArrayString& paths) const
205 {
206 paths.Empty();
207
208 wxString dir(m_dir);
209 if ( m_dir.Last() != _T('\\') )
210 dir += _T('\\');
211
212 size_t count = m_fileNames.GetCount();
213 for ( size_t n = 0; n < count; n++ )
214 {
215 paths.Add(dir + m_fileNames[n]);
216 }
217 }
218
219 int wxFileDialog::ShowModal()
220 {
221 HWND hWnd = 0;
222 if (m_parent) hWnd = (HWND) m_parent->GetHWND();
223 if (!hWnd && wxTheApp->GetTopWindow())
224 hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();
225
226 static wxChar fileNameBuffer [ wxMAXPATH ]; // the file-name
227 wxChar titleBuffer [ wxMAXFILE+1+wxMAXEXT ]; // the file-name, without path
228
229 *fileNameBuffer = wxT('\0');
230 *titleBuffer = wxT('\0');
231
232 long msw_flags = 0;
233 if ( (m_dialogStyle & wxHIDE_READONLY) || (m_dialogStyle & wxSAVE) )
234 msw_flags |= OFN_HIDEREADONLY;
235 if ( m_dialogStyle & wxFILE_MUST_EXIST )
236 msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
237 if (m_dialogStyle & wxMULTIPLE )
238 msw_flags |=
239 #if defined(OFN_EXPLORER)
240 OFN_EXPLORER |
241 #endif // OFN_EXPLORER
242 OFN_ALLOWMULTISELECT;
243
244 OPENFILENAME of;
245 wxZeroMemory(of);
246
247 // the OPENFILENAME struct has been extended in newer version of
248 // comcdlg32.dll, but as we don't use the extended fields anyhow, set
249 // the struct size to the old value - otherwise, the programs compiled
250 // with new headers will not work with the old libraries
251 #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0500)
252 of.lStructSize = sizeof(OPENFILENAME) -
253 (sizeof(void *) + 2*sizeof(DWORD));
254 #else // old headers
255 of.lStructSize = sizeof(OPENFILENAME);
256 #endif
257
258 of.hwndOwner = hWnd;
259 of.lpstrTitle = WXSTRINGCAST m_message;
260 of.lpstrFileTitle = titleBuffer;
261 of.nMaxFileTitle = wxMAXFILE + 1 + wxMAXEXT; // Windows 3.0 and 3.1
262
263 // Convert forward slashes to backslashes (file selector doesn't like
264 // forward slashes)
265 size_t i = 0;
266 size_t len = m_dir.Length();
267 for (i = 0; i < len; i++)
268 if (m_dir[i] == wxT('/'))
269 m_dir[i] = wxT('\\');
270
271 of.lpstrInitialDir = m_dir.c_str();
272
273 of.Flags = msw_flags;
274
275
276 //=== Like Alejandro Sierra's wildcard modification >>===================
277 /*
278 In wxFileSelector you can put, instead of a single wild_card,
279 pairs of strings separated by '|'.
280 The first string is a description, and the
281 second is the wild card. You can put any number of pairs.
282
283 eg. "description1 (*.ex1)|*.ex1|description2 (*.ex2)|*.ex2"
284
285 If you put a single wild card, it works as before the modification.
286 */
287 //=======================================================================
288
289 wxString theFilter;
290 if ( wxStrlen(m_wildCard) == 0 )
291 theFilter = wxString(wxT("*.*"));
292 else
293 theFilter = m_wildCard ;
294 wxString filterBuffer;
295
296 if ( !wxStrchr( theFilter, wxT('|') ) ) { // only one filter ==> default text
297 filterBuffer.Printf(_("Files (%s)|%s"),
298 theFilter.c_str(), theFilter.c_str());
299 }
300 else { // more then one filter
301 filterBuffer = theFilter;
302
303 }
304
305 filterBuffer += wxT("|");
306 // Replace | with \0
307 for (i = 0; i < filterBuffer.Len(); i++ ) {
308 if ( filterBuffer.GetChar(i) == wxT('|') ) {
309 filterBuffer[i] = wxT('\0');
310 }
311 }
312
313 of.lpstrFilter = (LPTSTR)(const wxChar *)filterBuffer;
314 of.nFilterIndex = m_filterIndex + 1;
315
316 //=== Setting defaultFileName >>=========================================
317
318 wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 );
319 fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0');
320
321 of.lpstrFile = fileNameBuffer; // holds returned filename
322 of.nMaxFile = wxMAXPATH;
323
324 //== Execute FileDialog >>=================================================
325
326 bool success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
327 : (GetOpenFileName(&of) != 0);
328
329 DWORD errCode = CommDlgExtendedError();
330
331 #ifdef __WIN32__
332 if (!success && (errCode == CDERR_STRUCTSIZE))
333 {
334 // The struct size has changed so try a smaller or bigger size
335
336 int oldStructSize = of.lStructSize;
337 of.lStructSize = oldStructSize - (sizeof(void *) + 2*sizeof(DWORD));
338 success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
339 : (GetOpenFileName(&of) != 0);
340 errCode = CommDlgExtendedError();
341
342 if (!success && (errCode == CDERR_STRUCTSIZE))
343 {
344 of.lStructSize = oldStructSize + (sizeof(void *) + 2*sizeof(DWORD));
345 success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
346 : (GetOpenFileName(&of) != 0);
347 }
348 }
349 #endif
350
351 if ( success )
352 {
353 m_fileNames.Empty();
354
355 if ( ( m_dialogStyle & wxMULTIPLE ) &&
356 #if defined(OFN_EXPLORER)
357 ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') ) )
358 #else
359 ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') ) )
360 #endif // OFN_EXPLORER
361 {
362 #if defined(OFN_EXPLORER)
363 m_dir = fileNameBuffer;
364 i = of.nFileOffset;
365 m_fileName = &fileNameBuffer[i];
366 m_fileNames.Add(m_fileName);
367 i += m_fileName.Len() + 1;
368
369 while (fileNameBuffer[i] != wxT('\0'))
370 {
371 m_fileNames.Add(&fileNameBuffer[i]);
372 i += wxStrlen(&fileNameBuffer[i]) + 1;
373 }
374 #else
375 wxStringTokenizer toke(fileNameBuffer, " \t\r\n");
376 m_dir = toke.GetNextToken();
377 m_fileName = toke.GetNextToken();
378 m_fileNames.Add(m_fileName);
379
380 while (toke.HasMoreTokens())
381 m_fileNames.Add(toke.GetNextToken());
382 #endif // OFN_EXPLORER
383
384 wxString dir(m_dir);
385 if ( m_dir.Last() != _T('\\') )
386 dir += _T('\\');
387
388 m_fileNames.Sort();
389 m_path = dir + m_fileName;
390 }
391 else
392 {
393 const wxChar* extension = NULL;
394
395 //=== Adding the correct extension >>=================================
396
397 m_filterIndex = (int)of.nFilterIndex - 1;
398
399 if ( !of.nFileExtension || (of.nFileExtension && fileNameBuffer[ of.nFileExtension-1] != wxT('.')) )
400 { // user has typed an filename
401 // without an extension:
402
403 int maxFilter = (int)(of.nFilterIndex*2L-1L);
404 extension = filterBuffer;
405
406 for( int i = 0; i < maxFilter; i++ ) { // get extension
407 extension = extension + wxStrlen( extension ) +1;
408 }
409
410 extension = wxStrrchr( extension, wxT('.') );
411 if ( extension // != "blabla"
412 && !wxStrrchr( extension, wxT('*') ) // != "blabla.*"
413 && !wxStrrchr( extension, wxT('?') ) // != "blabla.?"
414 && extension[1] // != "blabla."
415 && extension[1] != wxT(' ') ) // != "blabla. "
416 {
417 // now concat extension to the fileName:
418 m_fileName = wxString(fileNameBuffer) + extension;
419
420 int len = wxStrlen( fileNameBuffer );
421 wxStrncpy( fileNameBuffer + len, extension, wxMAXPATH - len );
422 fileNameBuffer[ wxMAXPATH -1 ] = wxT('\0');
423 }
424 }
425
426 m_path = fileNameBuffer;
427 m_fileName = wxFileNameFromPath(fileNameBuffer);
428 m_fileNames.Add(m_fileName);
429 m_dir = wxPathOnly(fileNameBuffer);
430 }
431
432
433 //=== Simulating the wxOVERWRITE_PROMPT >>============================
434
435 if ( (m_dialogStyle & wxOVERWRITE_PROMPT) &&
436 ::wxFileExists( fileNameBuffer ) )
437 {
438 wxString messageText;
439 messageText.Printf(_("Replace file '%s'?"), fileNameBuffer);
440
441 if ( wxMessageBox(messageText, m_message, wxYES_NO ) != wxYES )
442 {
443 success = FALSE;
444 }
445 }
446
447 }
448 else
449 {
450 // common dialog failed - why?
451 #ifdef __WXDEBUG__
452 DWORD dwErr = CommDlgExtendedError();
453 if ( dwErr != 0 )
454 {
455 // this msg is only for developers
456 wxLogError(wxT("Common dialog failed with error code %0lx."),
457 dwErr);
458 }
459 //else: it was just cancelled
460 #endif
461 }
462
463 return success ? wxID_OK : wxID_CANCEL;
464
465 }
466
467 // Generic file load/save dialog (for internal use only)
468 static
469 wxString wxDefaultFileSelector(bool load,
470 const wxChar *what,
471 const wxChar *extension,
472 const wxChar *default_name,
473 wxWindow *parent)
474 {
475 wxString prompt;
476 wxString str;
477 if (load) str = _("Load %s file");
478 else str = _("Save %s file");
479 prompt.Printf(str, what);
480
481 const wxChar *ext = extension;
482 if (*ext == wxT('.'))
483 ext++;
484
485 wxString wild;
486 wild.Printf(wxT("*.%s"), ext);
487
488 return wxFileSelector (prompt, NULL, default_name, ext, wild, 0, parent);
489 }
490
491 // Generic file load dialog
492 WXDLLEXPORT wxString wxLoadFileSelector(const wxChar *what,
493 const wxChar *extension,
494 const wxChar *default_name,
495 wxWindow *parent)
496 {
497 return wxDefaultFileSelector(TRUE, what, extension, default_name, parent);
498 }
499
500 // Generic file save dialog
501 WXDLLEXPORT wxString wxSaveFileSelector(const wxChar *what,
502 const wxChar *extension,
503 const wxChar *default_name,
504 wxWindow *parent)
505 {
506 return wxDefaultFileSelector(FALSE, what, extension, default_name, parent);
507 }
508
509