1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/filedlg.cpp
3 // Purpose: wxFileDialog
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "filedlg.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
35 #include "wx/msgdlg.h"
36 #include "wx/dialog.h"
37 #include "wx/filedlg.h"
38 #include "wx/filefn.h"
44 #include "wx/msw/private.h"
46 #if !defined(__WIN32__) || defined(__SALFORDC__)
54 #include "wx/filename.h"
55 #include "wx/tokenzr.h"
58 #define OFN_EXPLORER 0x00080000
61 // ----------------------------------------------------------------------------
63 // ----------------------------------------------------------------------------
66 # define wxMAXPATH 65534
68 # define wxMAXPATH 1024
71 # define wxMAXFILE 1024
75 // ============================================================================
77 // ============================================================================
79 // ----------------------------------------------------------------------------
81 // ----------------------------------------------------------------------------
83 IMPLEMENT_CLASS(wxFileDialog
, wxDialog
)
85 // ----------------------------------------------------------------------------
87 // ----------------------------------------------------------------------------
89 wxString
wxFileSelector(const wxChar
*title
,
90 const wxChar
*defaultDir
,
91 const wxChar
*defaultFileName
,
92 const wxChar
*defaultExtension
,
98 // In the original implementation, defaultExtension is passed to the
99 // lpstrDefExt member of OPENFILENAME. This extension, if non-NULL, is
100 // appended to the filename if the user fails to type an extension. The new
101 // implementation (taken from wxFileSelectorEx) appends the extension
102 // automatically, by looking at the filter specification. In fact this
103 // should be better than the native Microsoft implementation because
104 // Windows only allows *one* default extension, whereas here we do the
105 // right thing depending on the filter the user has chosen.
107 // If there's a default extension specified but no filter, we create a
111 if ( defaultExtension
&& !filter
)
112 filter2
= wxString(wxT("*.")) + defaultExtension
;
116 wxString defaultDirString
;
118 defaultDirString
= defaultDir
;
120 wxString defaultFilenameString
;
122 defaultFilenameString
= defaultFileName
;
124 wxFileDialog
fileDialog(parent
, title
, defaultDirString
,
125 defaultFilenameString
, filter2
,
126 flags
, wxPoint(x
, y
));
127 if( wxStrlen(defaultExtension
) != 0 )
132 for( unsigned int i
= 0; i
< filter2
.Len(); i
++ )
134 if( filter2
.GetChar(i
) == wxT('|') )
136 // save the start index of the new filter
137 unsigned int is
= i
++;
139 // find the end of the filter
140 for( ; i
< filter2
.Len(); i
++ )
142 if(filter2
[i
] == wxT('|'))
146 if( i
-is
-1 > 0 && is
+1 < filter2
.Len() )
148 if( filter2
.Mid(is
+1,i
-is
-1).Contains(defaultExtension
) )
150 filterFind
= filterIndex
;
159 fileDialog
.SetFilterIndex(filterFind
);
163 if ( fileDialog
.ShowModal() == wxID_OK
)
165 filename
= fileDialog
.GetPath();
172 wxString
wxFileSelectorEx(const wxChar
*title
,
173 const wxChar
*defaultDir
,
174 const wxChar
*defaultFileName
,
175 int* defaultFilterIndex
,
176 const wxChar
*filter
,
183 wxFileDialog
fileDialog(parent
,
184 title
? title
: wxT(""),
185 defaultDir
? defaultDir
: wxT(""),
186 defaultFileName
? defaultFileName
: wxT(""),
187 filter
? filter
: wxT(""),
188 flags
, wxPoint(x
, y
));
191 if ( fileDialog
.ShowModal() == wxID_OK
)
193 if ( defaultFilterIndex
)
194 *defaultFilterIndex
= fileDialog
.GetFilterIndex();
196 filename
= fileDialog
.GetPath();
202 wxFileDialog::wxFileDialog(wxWindow
*parent
,
203 const wxString
& message
,
204 const wxString
& defaultDir
,
205 const wxString
& defaultFileName
,
206 const wxString
& wildCard
,
208 const wxPoint
& WXUNUSED(pos
))
211 m_dialogStyle
= style
;
212 if ( ( m_dialogStyle
& wxMULTIPLE
) && ( m_dialogStyle
& wxSAVE
) )
213 m_dialogStyle
&= ~wxMULTIPLE
;
216 m_fileName
= defaultFileName
;
218 m_wildCard
= wildCard
;
222 void wxFileDialog::GetPaths(wxArrayString
& paths
) const
227 if ( m_dir
.Last() != _T('\\') )
230 size_t count
= m_fileNames
.GetCount();
231 for ( size_t n
= 0; n
< count
; n
++ )
233 if (wxFileName(m_fileNames
[n
]).IsAbsolute())
234 paths
.Add(m_fileNames
[n
]);
236 paths
.Add(dir
+ m_fileNames
[n
]);
240 void wxFileDialog::SetPath(const wxString
& path
)
243 wxSplitPath(path
, &m_dir
, &m_fileName
, &ext
);
245 m_fileName
<< _T('.') << ext
;
248 int wxFileDialog::ShowModal()
251 if (m_parent
) hWnd
= (HWND
) m_parent
->GetHWND();
252 if (!hWnd
&& wxTheApp
->GetTopWindow())
253 hWnd
= (HWND
) wxTheApp
->GetTopWindow()->GetHWND();
255 static wxChar fileNameBuffer
[ wxMAXPATH
]; // the file-name
256 wxChar titleBuffer
[ wxMAXFILE
+1+wxMAXEXT
]; // the file-name, without path
258 *fileNameBuffer
= wxT('\0');
259 *titleBuffer
= wxT('\0');
262 if ( (m_dialogStyle
& wxHIDE_READONLY
) || (m_dialogStyle
& wxSAVE
) )
263 msw_flags
|= OFN_HIDEREADONLY
;
264 if ( m_dialogStyle
& wxFILE_MUST_EXIST
)
265 msw_flags
|= OFN_PATHMUSTEXIST
| OFN_FILEMUSTEXIST
;
267 if (m_dialogStyle
& wxMULTIPLE
)
269 // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT
270 msw_flags
|= OFN_EXPLORER
| OFN_ALLOWMULTISELECT
;
273 // if wxCHANGE_DIR flag is not given we shouldn't change the CWD which the
274 // standard dialog does by default
275 if ( !(m_dialogStyle
& wxCHANGE_DIR
) )
277 msw_flags
|= OFN_NOCHANGEDIR
;
279 /* chris elliott for some reason this does not work usefully if no extension
280 is given, as it test for junk instead of junk.ext
281 if ( m_dialogStyle & wxOVERWRITE_PROMPT )
283 msw_flags |= OFN_OVERWRITEPROMPT;
289 // the OPENFILENAME struct has been extended in newer version of
290 // comcdlg32.dll, but as we don't use the extended fields anyhow, set
291 // the struct size to the old value - otherwise, the programs compiled
292 // with new headers will not work with the old libraries
293 #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0500)
294 of
.lStructSize
= sizeof(OPENFILENAME
) -
295 (sizeof(void *) + 2*sizeof(DWORD
));
297 of
.lStructSize
= sizeof(OPENFILENAME
);
301 of
.lpstrTitle
= WXSTRINGCAST m_message
;
302 of
.lpstrFileTitle
= titleBuffer
;
303 of
.nMaxFileTitle
= wxMAXFILE
+ 1 + wxMAXEXT
; // Windows 3.0 and 3.1
305 // Convert forward slashes to backslashes (file selector doesn't like
306 // forward slashes) and also squeeze multiple consecutive slashes into one
307 // as it doesn't like two backslashes in a row neither
310 size_t i
, len
= m_dir
.length();
312 for ( i
= 0; i
< len
; i
++ )
314 wxChar ch
= m_dir
[i
];
318 // convert to backslash
324 while ( i
< len
- 1 )
326 wxChar chNext
= m_dir
[i
+ 1];
327 if ( chNext
!= _T('\\') && chNext
!= _T('/') )
330 // ignore the next one, unless it is at the start of a UNC path
344 of
.lpstrInitialDir
= dir
.c_str();
346 of
.Flags
= msw_flags
;
349 //=== Like Alejandro Sierra's wildcard modification >>===================
351 In wxFileSelector you can put, instead of a single wild_card,
352 pairs of strings separated by '|'.
353 The first string is a description, and the
354 second is the wild card. You can put any number of pairs.
356 eg. "description1 (*.ex1)|*.ex1|description2 (*.ex2)|*.ex2"
358 If you put a single wild card, it works as before the modification.
360 //=======================================================================
363 if ( wxStrlen(m_wildCard
) == 0 )
364 theFilter
= wxString(wxT("*.*"));
366 theFilter
= m_wildCard
;
367 wxString filterBuffer
;
369 if ( !wxStrchr( theFilter
, wxT('|') ) ) { // only one filter ==> default text
370 filterBuffer
.Printf(_("Files (%s)|%s"),
371 theFilter
.c_str(), theFilter
.c_str());
373 else { // more then one filter
374 filterBuffer
= theFilter
;
378 filterBuffer
+= wxT("|");
380 for (i
= 0; i
< filterBuffer
.Len(); i
++ ) {
381 if ( filterBuffer
.GetChar(i
) == wxT('|') ) {
382 filterBuffer
[i
] = wxT('\0');
386 of
.lpstrFilter
= (LPTSTR
)(const wxChar
*)filterBuffer
;
387 of
.nFilterIndex
= m_filterIndex
+ 1;
389 //=== Setting defaultFileName >>=========================================
391 wxStrncpy( fileNameBuffer
, (const wxChar
*)m_fileName
, wxMAXPATH
-1 );
392 fileNameBuffer
[ wxMAXPATH
-1 ] = wxT('\0');
394 of
.lpstrFile
= fileNameBuffer
; // holds returned filename
395 of
.nMaxFile
= wxMAXPATH
;
397 //== Execute FileDialog >>=================================================
399 bool success
= (m_dialogStyle
& wxSAVE
? GetSaveFileName(&of
)
400 : GetOpenFileName(&of
)) != 0;
402 DWORD errCode
= CommDlgExtendedError();
405 if (!success
&& (errCode
== CDERR_STRUCTSIZE
))
407 // The struct size has changed so try a smaller or bigger size
409 int oldStructSize
= of
.lStructSize
;
410 of
.lStructSize
= oldStructSize
- (sizeof(void *) + 2*sizeof(DWORD
));
411 success
= (m_dialogStyle
& wxSAVE
) ? (GetSaveFileName(&of
) != 0)
412 : (GetOpenFileName(&of
) != 0);
413 errCode
= CommDlgExtendedError();
415 if (!success
&& (errCode
== CDERR_STRUCTSIZE
))
417 of
.lStructSize
= oldStructSize
+ (sizeof(void *) + 2*sizeof(DWORD
));
418 success
= (m_dialogStyle
& wxSAVE
) ? (GetSaveFileName(&of
) != 0)
419 : (GetOpenFileName(&of
) != 0);
428 if ( ( m_dialogStyle
& wxMULTIPLE
) &&
429 #if defined(OFN_EXPLORER)
430 ( fileNameBuffer
[of
.nFileOffset
-1] == wxT('\0') ) )
432 ( fileNameBuffer
[of
.nFileOffset
-1] == wxT(' ') ) )
433 #endif // OFN_EXPLORER
435 #if defined(OFN_EXPLORER)
436 m_dir
= fileNameBuffer
;
438 m_fileName
= &fileNameBuffer
[i
];
439 m_fileNames
.Add(m_fileName
);
440 i
+= m_fileName
.Len() + 1;
442 while (fileNameBuffer
[i
] != wxT('\0'))
444 m_fileNames
.Add(&fileNameBuffer
[i
]);
445 i
+= wxStrlen(&fileNameBuffer
[i
]) + 1;
448 wxStringTokenizer
toke(fileNameBuffer
, _T(" \t\r\n"));
449 m_dir
= toke
.GetNextToken();
450 m_fileName
= toke
.GetNextToken();
451 m_fileNames
.Add(m_fileName
);
453 while (toke
.HasMoreTokens())
454 m_fileNames
.Add(toke
.GetNextToken());
455 #endif // OFN_EXPLORER
458 if ( m_dir
.Last() != _T('\\') )
462 m_path
= dir
+ m_fileName
;
466 const wxChar
* extension
= NULL
;
468 //=== Adding the correct extension >>=================================
470 m_filterIndex
= (int)of
.nFilterIndex
- 1;
472 if ( !of
.nFileExtension
||
473 (of
.nFileExtension
&& fileNameBuffer
[of
.nFileExtension
] == wxT('\0')) )
475 // User has typed a filename without an extension:
477 // A filename can end in a "." here ("abc."), this means it
478 // does not have an extension. Because later on a "." with
479 // the default extension is appended we remove the "." if
480 // filename ends with one (We don't want files called
482 int idx
= wxStrlen(fileNameBuffer
) - 1;
483 if ( fileNameBuffer
[idx
] == wxT('.') )
485 fileNameBuffer
[idx
] = wxT('\0');
488 int maxFilter
= (int)(of
.nFilterIndex
*2L-1L);
489 extension
= filterBuffer
;
491 for( int i
= 0; i
< maxFilter
; i
++ ) { // get extension
492 extension
= extension
+ wxStrlen( extension
) +1;
495 extension
= wxStrrchr( extension
, wxT('.') );
496 if ( extension
// != "blabla"
497 && !wxStrrchr( extension
, wxT('*') ) // != "blabla.*"
498 && !wxStrrchr( extension
, wxT('?') ) // != "blabla.?"
499 && extension
[1] // != "blabla."
500 && extension
[1] != wxT(' ') ) // != "blabla. "
502 // now concat extension to the fileName:
503 m_fileName
= wxString(fileNameBuffer
) + extension
;
505 int len
= wxStrlen( fileNameBuffer
);
506 wxStrncpy( fileNameBuffer
+ len
, extension
, wxMAXPATH
- len
);
507 fileNameBuffer
[ wxMAXPATH
-1 ] = wxT('\0');
511 m_path
= fileNameBuffer
;
512 m_fileName
= wxFileNameFromPath(fileNameBuffer
);
513 m_fileNames
.Add(m_fileName
);
514 m_dir
= wxPathOnly(fileNameBuffer
);
516 //=== Simulating the wxOVERWRITE_PROMPT >>============================
517 //should we also test for file save style ??
518 if ( (m_dialogStyle
& wxOVERWRITE_PROMPT
) &&
519 ::wxFileExists( fileNameBuffer
) )
521 wxString messageText
;
522 messageText
.Printf(_("File '%s' already exists.\nDo you want to replace it?"), fileNameBuffer
);
523 if ( wxMessageBox(messageText
, wxT("Save File As"), wxYES_NO
| wxICON_EXCLAMATION
) != wxYES
)
531 // common dialog failed - why?
533 DWORD dwErr
= CommDlgExtendedError();
536 // this msg is only for developers
537 wxLogError(wxT("Common dialog failed with error code %0lx."),
540 //else: it was just cancelled
544 return success
? wxID_OK
: wxID_CANCEL
;
548 // Generic file load/save dialog (for internal use only)
550 wxString
wxDefaultFileSelector(bool load
,
552 const wxChar
*extension
,
553 const wxChar
*default_name
,
559 str
= _("Load %s file");
561 str
= _("Save %s file");
562 prompt
.Printf(str
, what
);
564 const wxChar
*ext
= extension
;
565 if (*ext
== wxT('.'))
569 wild
.Printf(wxT("*.%s"), ext
);
571 return wxFileSelector(prompt
, NULL
, default_name
, ext
, wild
,
572 load
? wxOPEN
: wxSAVE
, parent
);
575 // Generic file load dialog
576 WXDLLEXPORT wxString
wxLoadFileSelector(const wxChar
*what
,
577 const wxChar
*extension
,
578 const wxChar
*default_name
,
581 return wxDefaultFileSelector(TRUE
, what
, extension
, default_name
, parent
);
584 // Generic file save dialog
585 WXDLLEXPORT wxString
wxSaveFileSelector(const wxChar
*what
,
586 const wxChar
*extension
,
587 const wxChar
*default_name
,
590 return wxDefaultFileSelector(FALSE
, what
, extension
, default_name
, parent
);
593 #endif // wxUSE_FILEDLG