]> git.saurik.com Git - wxWidgets.git/blob - src/msw/filedlg.cpp
adde wxSTC bakefile
[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
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__)
47 #include <commdlg.h>
48 #endif
49
50 #include <math.h>
51 #include <stdlib.h>
52 #include <string.h>
53
54 #include "wx/filename.h"
55 #include "wx/tokenzr.h"
56
57 #ifndef OFN_EXPLORER
58 #define OFN_EXPLORER 0x00080000
59 #endif
60
61 // ----------------------------------------------------------------------------
62 // constants
63 // ----------------------------------------------------------------------------
64
65 #ifdef __WIN32__
66 # define wxMAXPATH 65534
67 #else
68 # define wxMAXPATH 1024
69 #endif
70
71 # define wxMAXFILE 1024
72
73 # define wxMAXEXT 5
74
75 // ============================================================================
76 // implementation
77 // ============================================================================
78
79 // ----------------------------------------------------------------------------
80 // wxWin macros
81 // ----------------------------------------------------------------------------
82
83 IMPLEMENT_CLASS(wxFileDialog, wxDialog)
84
85 // ----------------------------------------------------------------------------
86 // wxFileDialog
87 // ----------------------------------------------------------------------------
88
89 wxFileDialog::wxFileDialog(wxWindow *parent,
90 const wxString& message,
91 const wxString& defaultDir,
92 const wxString& defaultFileName,
93 const wxString& wildCard,
94 long style,
95 const wxPoint& WXUNUSED(pos))
96 {
97 m_message = message;
98 m_dialogStyle = style;
99 if ( ( m_dialogStyle & wxMULTIPLE ) && ( m_dialogStyle & wxSAVE ) )
100 m_dialogStyle &= ~wxMULTIPLE;
101 m_parent = parent;
102 m_path = wxT("");
103 m_fileName = defaultFileName;
104 m_dir = defaultDir;
105 m_wildCard = wildCard;
106 m_filterIndex = 0;
107 }
108
109 void wxFileDialog::GetPaths(wxArrayString& paths) const
110 {
111 paths.Empty();
112
113 wxString dir(m_dir);
114 if ( m_dir.Last() != _T('\\') )
115 dir += _T('\\');
116
117 size_t count = m_fileNames.GetCount();
118 for ( size_t n = 0; n < count; n++ )
119 {
120 if (wxFileName(m_fileNames[n]).IsAbsolute())
121 paths.Add(m_fileNames[n]);
122 else
123 paths.Add(dir + m_fileNames[n]);
124 }
125 }
126
127 void wxFileDialog::SetPath(const wxString& path)
128 {
129 wxString ext;
130 wxSplitPath(path, &m_dir, &m_fileName, &ext);
131 if ( !ext.empty() )
132 m_fileName << _T('.') << ext;
133 }
134
135 int wxFileDialog::ShowModal()
136 {
137 HWND hWnd = 0;
138 if (m_parent) hWnd = (HWND) m_parent->GetHWND();
139 if (!hWnd && wxTheApp->GetTopWindow())
140 hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();
141
142 static wxChar fileNameBuffer [ wxMAXPATH ]; // the file-name
143 wxChar titleBuffer [ wxMAXFILE+1+wxMAXEXT ]; // the file-name, without path
144
145 *fileNameBuffer = wxT('\0');
146 *titleBuffer = wxT('\0');
147
148 long msw_flags = 0;
149 if ( (m_dialogStyle & wxHIDE_READONLY) || (m_dialogStyle & wxSAVE) )
150 msw_flags |= OFN_HIDEREADONLY;
151 if ( m_dialogStyle & wxFILE_MUST_EXIST )
152 msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
153
154 if (m_dialogStyle & wxMULTIPLE )
155 {
156 // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT
157 msw_flags |= OFN_EXPLORER | OFN_ALLOWMULTISELECT;
158 }
159
160 // if wxCHANGE_DIR flag is not given we shouldn't change the CWD which the
161 // standard dialog does by default
162 if ( !(m_dialogStyle & wxCHANGE_DIR) )
163 {
164 msw_flags |= OFN_NOCHANGEDIR;
165 }
166 /* chris elliott for some reason this does not work usefully if no extension
167 is given, as it test for junk instead of junk.ext
168 if ( m_dialogStyle & wxOVERWRITE_PROMPT )
169 {
170 msw_flags |= OFN_OVERWRITEPROMPT;
171 }
172 */
173 OPENFILENAME of;
174 wxZeroMemory(of);
175
176 // the OPENFILENAME struct has been extended in newer version of
177 // comcdlg32.dll, but as we don't use the extended fields anyhow, set
178 // the struct size to the old value - otherwise, the programs compiled
179 // with new headers will not work with the old libraries
180 #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0500)
181 of.lStructSize = sizeof(OPENFILENAME) -
182 (sizeof(void *) + 2*sizeof(DWORD));
183 #else // old headers
184 of.lStructSize = sizeof(OPENFILENAME);
185 #endif
186
187 of.hwndOwner = hWnd;
188 of.lpstrTitle = WXSTRINGCAST m_message;
189 of.lpstrFileTitle = titleBuffer;
190 of.nMaxFileTitle = wxMAXFILE + 1 + wxMAXEXT; // Windows 3.0 and 3.1
191
192 // Convert forward slashes to backslashes (file selector doesn't like
193 // forward slashes) and also squeeze multiple consecutive slashes into one
194 // as it doesn't like two backslashes in a row neither
195
196 wxString dir;
197 size_t i, len = m_dir.length();
198 dir.reserve(len);
199 for ( i = 0; i < len; i++ )
200 {
201 wxChar ch = m_dir[i];
202 switch ( ch )
203 {
204 case _T('/'):
205 // convert to backslash
206 ch = _T('\\');
207
208 // fall through
209
210 case _T('\\'):
211 while ( i < len - 1 )
212 {
213 wxChar chNext = m_dir[i + 1];
214 if ( chNext != _T('\\') && chNext != _T('/') )
215 break;
216
217 // ignore the next one, unless it is at the start of a UNC path
218 if (i > 0)
219 i++;
220 else
221 break;
222 }
223 // fall through
224
225 default:
226 // normal char
227 dir += ch;
228 }
229 }
230
231 of.lpstrInitialDir = dir.c_str();
232
233 of.Flags = msw_flags;
234
235
236 //=== Like Alejandro Sierra's wildcard modification >>===================
237 /*
238 In wxFileSelector you can put, instead of a single wild_card,
239 pairs of strings separated by '|'.
240 The first string is a description, and the
241 second is the wild card. You can put any number of pairs.
242
243 eg. "description1 (*.ex1)|*.ex1|description2 (*.ex2)|*.ex2"
244
245 If you put a single wild card, it works as before the modification.
246 */
247 //=======================================================================
248
249 wxString theFilter;
250 if ( wxStrlen(m_wildCard) == 0 )
251 theFilter = wxString(wxT("*.*"));
252 else
253 theFilter = m_wildCard ;
254 wxString filterBuffer;
255
256 if ( !wxStrchr( theFilter, wxT('|') ) ) { // only one filter ==> default text
257 filterBuffer.Printf(_("Files (%s)|%s"),
258 theFilter.c_str(), theFilter.c_str());
259 }
260 else { // more then one filter
261 filterBuffer = theFilter;
262
263 }
264
265 filterBuffer += wxT("|");
266 // Replace | with \0
267 for (i = 0; i < filterBuffer.Len(); i++ ) {
268 if ( filterBuffer.GetChar(i) == wxT('|') ) {
269 filterBuffer[i] = wxT('\0');
270 }
271 }
272
273 of.lpstrFilter = (LPTSTR)(const wxChar *)filterBuffer;
274 of.nFilterIndex = m_filterIndex + 1;
275
276 //=== Setting defaultFileName >>=========================================
277
278 wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 );
279 fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0');
280
281 of.lpstrFile = fileNameBuffer; // holds returned filename
282 of.nMaxFile = wxMAXPATH;
283
284 //== Execute FileDialog >>=================================================
285
286 bool success = (m_dialogStyle & wxSAVE ? GetSaveFileName(&of)
287 : GetOpenFileName(&of)) != 0;
288
289 DWORD errCode = CommDlgExtendedError();
290
291 #ifdef __WIN32__
292 if (!success && (errCode == CDERR_STRUCTSIZE))
293 {
294 // The struct size has changed so try a smaller or bigger size
295
296 int oldStructSize = of.lStructSize;
297 of.lStructSize = oldStructSize - (sizeof(void *) + 2*sizeof(DWORD));
298 success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
299 : (GetOpenFileName(&of) != 0);
300 errCode = CommDlgExtendedError();
301
302 if (!success && (errCode == CDERR_STRUCTSIZE))
303 {
304 of.lStructSize = oldStructSize + (sizeof(void *) + 2*sizeof(DWORD));
305 success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
306 : (GetOpenFileName(&of) != 0);
307 }
308 }
309 #endif // __WIN32__
310
311 if ( success )
312 {
313 m_fileNames.Empty();
314
315 if ( ( m_dialogStyle & wxMULTIPLE ) &&
316 #if defined(OFN_EXPLORER)
317 ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') ) )
318 #else
319 ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') ) )
320 #endif // OFN_EXPLORER
321 {
322 #if defined(OFN_EXPLORER)
323 m_dir = fileNameBuffer;
324 i = of.nFileOffset;
325 m_fileName = &fileNameBuffer[i];
326 m_fileNames.Add(m_fileName);
327 i += m_fileName.Len() + 1;
328
329 while (fileNameBuffer[i] != wxT('\0'))
330 {
331 m_fileNames.Add(&fileNameBuffer[i]);
332 i += wxStrlen(&fileNameBuffer[i]) + 1;
333 }
334 #else
335 wxStringTokenizer toke(fileNameBuffer, _T(" \t\r\n"));
336 m_dir = toke.GetNextToken();
337 m_fileName = toke.GetNextToken();
338 m_fileNames.Add(m_fileName);
339
340 while (toke.HasMoreTokens())
341 m_fileNames.Add(toke.GetNextToken());
342 #endif // OFN_EXPLORER
343
344 wxString dir(m_dir);
345 if ( m_dir.Last() != _T('\\') )
346 dir += _T('\\');
347
348 m_fileNames.Sort();
349 m_path = dir + m_fileName;
350 }
351 else
352 {
353 const wxChar* extension = NULL;
354
355 //=== Adding the correct extension >>=================================
356
357 m_filterIndex = (int)of.nFilterIndex - 1;
358
359 if ( !of.nFileExtension ||
360 (of.nFileExtension && fileNameBuffer[of.nFileExtension] == wxT('\0')) )
361 {
362 // User has typed a filename without an extension:
363
364 // A filename can end in a "." here ("abc."), this means it
365 // does not have an extension. Because later on a "." with
366 // the default extension is appended we remove the "." if
367 // filename ends with one (We don't want files called
368 // "abc..ext")
369 int idx = wxStrlen(fileNameBuffer) - 1;
370 if ( fileNameBuffer[idx] == wxT('.') )
371 {
372 fileNameBuffer[idx] = wxT('\0');
373 }
374
375 int maxFilter = (int)(of.nFilterIndex*2L-1L);
376 extension = filterBuffer;
377
378 for( int i = 0; i < maxFilter; i++ ) { // get extension
379 extension = extension + wxStrlen( extension ) +1;
380 }
381
382 extension = wxStrrchr( extension, wxT('.') );
383 if ( extension // != "blabla"
384 && !wxStrrchr( extension, wxT('*') ) // != "blabla.*"
385 && !wxStrrchr( extension, wxT('?') ) // != "blabla.?"
386 && extension[1] // != "blabla."
387 && extension[1] != wxT(' ') ) // != "blabla. "
388 {
389 // now concat extension to the fileName:
390 m_fileName = wxString(fileNameBuffer) + extension;
391
392 int len = wxStrlen( fileNameBuffer );
393 wxStrncpy( fileNameBuffer + len, extension, wxMAXPATH - len );
394 fileNameBuffer[ wxMAXPATH -1 ] = wxT('\0');
395 }
396 }
397
398 m_path = fileNameBuffer;
399 m_fileName = wxFileNameFromPath(fileNameBuffer);
400 m_fileNames.Add(m_fileName);
401 m_dir = wxPathOnly(fileNameBuffer);
402 }
403 //=== Simulating the wxOVERWRITE_PROMPT >>============================
404 //should we also test for file save style ??
405 if ( (m_dialogStyle & wxOVERWRITE_PROMPT) &&
406 ::wxFileExists( fileNameBuffer ) )
407 {
408 wxString messageText;
409 messageText.Printf(_("File '%s' already exists.\nDo you want to replace it?"), fileNameBuffer);
410 if ( wxMessageBox(messageText, wxT("Save File As"), wxYES_NO | wxICON_EXCLAMATION ) != wxYES )
411 {
412 success = FALSE;
413 }
414 }
415 }
416 else
417 {
418 // common dialog failed - why?
419 #ifdef __WXDEBUG__
420 DWORD dwErr = CommDlgExtendedError();
421 if ( dwErr != 0 )
422 {
423 // this msg is only for developers
424 wxLogError(wxT("Common dialog failed with error code %0lx."),
425 dwErr);
426 }
427 //else: it was just cancelled
428 #endif
429 }
430
431 return success ? wxID_OK : wxID_CANCEL;
432
433 }
434
435 #endif // wxUSE_FILEDLG
436