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