Fixed wxFileDialog breakage on WinCE due to incorrect structure size, and
[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 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_FILEDLG && !(defined(__SMARTPHONE__) && defined(__WXWINCE__))
28
29 #ifndef WX_PRECOMP
30 #include "wx/utils.h"
31 #include "wx/msgdlg.h"
32 #include "wx/filedlg.h"
33 #include "wx/filefn.h"
34 #include "wx/intl.h"
35 #include "wx/log.h"
36 #include "wx/app.h"
37 #endif
38
39 #include "wx/msw/wrapcdlg.h"
40
41 #include <stdlib.h>
42 #include <string.h>
43
44 #include "wx/filename.h"
45 #include "wx/tokenzr.h"
46 #include "wx/math.h"
47
48 #include "wx/msw/missing.h"
49
50 // ----------------------------------------------------------------------------
51 // constants
52 // ----------------------------------------------------------------------------
53
54 #ifdef __WIN32__
55 # define wxMAXPATH 65534
56 #else
57 # define wxMAXPATH 1024
58 #endif
59
60 # define wxMAXFILE 1024
61
62 # define wxMAXEXT 5
63
64 // ----------------------------------------------------------------------------
65 // globals
66 // ----------------------------------------------------------------------------
67
68 // standard dialog size
69 static wxRect gs_rectDialog(0, 0, 428, 266);
70
71 // ============================================================================
72 // implementation
73 // ============================================================================
74
75 IMPLEMENT_CLASS(wxFileDialog, wxFileDialogBase)
76
77 // ----------------------------------------------------------------------------
78 // hook function for moving the dialog
79 // ----------------------------------------------------------------------------
80
81 UINT_PTR APIENTRY
82 wxFileDialogHookFunction(HWND hDlg,
83 UINT iMsg,
84 WPARAM WXUNUSED(wParam),
85 LPARAM lParam)
86 {
87 HWND hwndDialog;
88 hwndDialog = ::GetParent( hDlg );
89 switch (iMsg)
90 {
91 case WM_DESTROY:
92 {
93 RECT dlgRect;
94 GetWindowRect( hwndDialog, & dlgRect );
95 gs_rectDialog.x = dlgRect.left;
96 gs_rectDialog.y = dlgRect.top;
97 gs_rectDialog.width = dlgRect.right - dlgRect.left;
98 gs_rectDialog.height = dlgRect.bottom - dlgRect.top;
99 }
100 break;
101
102 case WM_NOTIFY:
103 {
104 OFNOTIFY * pNotifyCode;
105 pNotifyCode = (LPOFNOTIFY) lParam;
106 if (CDN_INITDONE == (pNotifyCode->hdr).code)
107 {
108 SetWindowPos( hwndDialog, HWND_TOP,
109 gs_rectDialog.x,
110 gs_rectDialog.y,
111 gs_rectDialog.width,
112 gs_rectDialog.height,
113 SWP_NOZORDER|SWP_NOSIZE);
114 }
115 }
116 break;
117 }
118
119 // do the default processing
120 return 0;
121 }
122
123 // ----------------------------------------------------------------------------
124 // wxFileDialog
125 // ----------------------------------------------------------------------------
126
127 wxFileDialog::wxFileDialog(wxWindow *parent,
128 const wxString& message,
129 const wxString& defaultDir,
130 const wxString& defaultFileName,
131 const wxString& wildCard,
132 long style,
133 const wxPoint& pos)
134 : wxFileDialogBase(parent, message, defaultDir, defaultFileName,
135 wildCard, style, pos)
136
137 {
138 if ( ( m_dialogStyle & wxMULTIPLE ) && ( m_dialogStyle & wxSAVE ) )
139 m_dialogStyle &= ~wxMULTIPLE;
140
141 m_bMovedWindow = false;
142
143 // Must set to zero, otherwise the wx routines won't size the window
144 // the second time you call the file dialog, because it thinks it is
145 // already at the requested size.. (when centering)
146 gs_rectDialog.x =
147 gs_rectDialog.y = 0;
148
149 }
150 void wxFileDialog::GetPaths(wxArrayString& paths) const
151 {
152 paths.Empty();
153
154 wxString dir(m_dir);
155 if ( m_dir.Last() != _T('\\') )
156 dir += _T('\\');
157
158 size_t count = m_fileNames.GetCount();
159 for ( size_t n = 0; n < count; n++ )
160 {
161 if (wxFileName(m_fileNames[n]).IsAbsolute())
162 paths.Add(m_fileNames[n]);
163 else
164 paths.Add(dir + m_fileNames[n]);
165 }
166 }
167
168 void wxFileDialog::GetFilenames(wxArrayString& files) const
169 {
170 files = m_fileNames;
171 }
172
173 void wxFileDialog::SetPath(const wxString& path)
174 {
175 wxString ext;
176 wxSplitPath(path, &m_dir, &m_fileName, &ext);
177 if ( !ext.empty() )
178 m_fileName << _T('.') << ext;
179 }
180
181 void wxFileDialog::DoGetPosition( int *x, int *y ) const
182 {
183 *x = gs_rectDialog.x;
184 *y = gs_rectDialog.y;
185 }
186
187
188 void wxFileDialog::DoGetSize(int *width, int *height) const
189 {
190 *width = gs_rectDialog.width;
191 *height = gs_rectDialog.height;
192 }
193
194 void wxFileDialog::DoMoveWindow(int x, int y, int WXUNUSED(width), int WXUNUSED(height))
195 {
196 m_bMovedWindow = true;
197
198 gs_rectDialog.x = x;
199 gs_rectDialog.y = y;
200
201 /*
202 The width and height can not be set by the programmer
203 its just not possible. But the program can get the
204 size of the Dlg after it has been shown, in case they need
205 that data.
206 */
207 }
208
209 int wxFileDialog::ShowModal()
210 {
211 HWND hWnd = 0;
212 if (m_parent) hWnd = (HWND) m_parent->GetHWND();
213 if (!hWnd && wxTheApp->GetTopWindow())
214 hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();
215
216 static wxChar fileNameBuffer [ wxMAXPATH ]; // the file-name
217 wxChar titleBuffer [ wxMAXFILE+1+wxMAXEXT ]; // the file-name, without path
218
219 *fileNameBuffer = wxT('\0');
220 *titleBuffer = wxT('\0');
221
222 #if WXWIN_COMPATIBILITY_2_4
223 long msw_flags = 0;
224 if ( (m_dialogStyle & wxHIDE_READONLY) || (m_dialogStyle & wxSAVE) )
225 msw_flags |= OFN_HIDEREADONLY;
226 #else
227 long msw_flags = OFN_HIDEREADONLY;
228 #endif
229
230 if ( m_dialogStyle & wxFILE_MUST_EXIST )
231 msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
232 /*
233 If the window has been moved the programmer is probably
234 trying to center or position it. Thus we set the callback
235 or hook function so that we can actually adjust the position.
236 Without moving or centering the dlg, it will just stay
237 in the upper left of the frame, it does not center
238 automatically.. One additional note, when the hook is
239 enabled, the PLACES BAR in the dlg (shown on later versions
240 of windows (2000 and XP) will automatically be turned off
241 according to the MSDN docs. This is normal. If the
242 programmer needs the PLACES BAR (left side of dlg) they
243 just shouldn't move or center the dlg.
244 */
245 if (m_bMovedWindow) // we need these flags.
246 {
247 msw_flags |= OFN_EXPLORER|OFN_ENABLEHOOK;
248 #ifndef __WXWINCE__
249 msw_flags |= OFN_ENABLESIZING;
250 #endif
251 }
252
253 if (m_dialogStyle & wxMULTIPLE )
254 {
255 // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT
256 msw_flags |= OFN_EXPLORER | OFN_ALLOWMULTISELECT;
257 }
258
259 // if wxCHANGE_DIR flag is not given we shouldn't change the CWD which the
260 // standard dialog does by default (notice that under NT it does it anyhow,
261 // OFN_NOCHANGEDIR or not, see below)
262 if ( !(m_dialogStyle & wxCHANGE_DIR) )
263 {
264 msw_flags |= OFN_NOCHANGEDIR;
265 }
266
267 if ( m_dialogStyle & wxOVERWRITE_PROMPT )
268 {
269 msw_flags |= OFN_OVERWRITEPROMPT;
270 }
271
272 OPENFILENAME of;
273 wxZeroMemory(of);
274
275 // the OPENFILENAME struct has been extended in newer version of
276 // comcdlg32.dll, but as we don't use the extended fields anyhow, set
277 // the struct size to the old value - otherwise, the programs compiled
278 // with new headers will not work with the old libraries
279 #if !defined(__WXWINCE__) && defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0500)
280 of.lStructSize = sizeof(OPENFILENAME) -
281 (sizeof(void *) + 2*sizeof(DWORD));
282 #else // old headers
283 of.lStructSize = sizeof(OPENFILENAME);
284 #endif
285
286 of.hwndOwner = hWnd;
287 of.lpstrTitle = WXSTRINGCAST m_message;
288 of.lpstrFileTitle = titleBuffer;
289 of.nMaxFileTitle = wxMAXFILE + 1 + wxMAXEXT; // Windows 3.0 and 3.1
290
291 // Convert forward slashes to backslashes (file selector doesn't like
292 // forward slashes) and also squeeze multiple consecutive slashes into one
293 // as it doesn't like two backslashes in a row neither
294
295 wxString dir;
296 size_t i, len = m_dir.length();
297 dir.reserve(len);
298 for ( i = 0; i < len; i++ )
299 {
300 wxChar ch = m_dir[i];
301 switch ( ch )
302 {
303 case _T('/'):
304 // convert to backslash
305 ch = _T('\\');
306
307 // fall through
308
309 case _T('\\'):
310 while ( i < len - 1 )
311 {
312 wxChar chNext = m_dir[i + 1];
313 if ( chNext != _T('\\') && chNext != _T('/') )
314 break;
315
316 // ignore the next one, unless it is at the start of a UNC path
317 if (i > 0)
318 i++;
319 else
320 break;
321 }
322 // fall through
323
324 default:
325 // normal char
326 dir += ch;
327 }
328 }
329
330 of.lpstrInitialDir = dir.c_str();
331
332 of.Flags = msw_flags;
333 of.lpfnHook = wxFileDialogHookFunction;
334
335 wxArrayString wildDescriptions, wildFilters;
336
337 size_t items = wxParseCommonDialogsFilter(m_wildCard, wildDescriptions, wildFilters);
338
339 wxASSERT_MSG( items > 0 , _T("empty wildcard list") );
340
341 wxString filterBuffer;
342
343 for (i = 0; i < items ; i++)
344 {
345 filterBuffer += wildDescriptions[i];
346 filterBuffer += wxT("|");
347 filterBuffer += wildFilters[i];
348 filterBuffer += wxT("|");
349 }
350
351 // Replace | with \0
352 for (i = 0; i < filterBuffer.Len(); i++ ) {
353 if ( filterBuffer.GetChar(i) == wxT('|') ) {
354 filterBuffer[i] = wxT('\0');
355 }
356 }
357
358 of.lpstrFilter = (LPTSTR)filterBuffer.c_str();
359 of.nFilterIndex = m_filterIndex + 1;
360
361 //=== Setting defaultFileName >>=========================================
362
363 wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 );
364 fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0');
365
366 of.lpstrFile = fileNameBuffer; // holds returned filename
367 of.nMaxFile = wxMAXPATH;
368
369 // we must set the default extension because otherwise Windows would check
370 // for the existing of a wrong file with wxOVERWRITE_PROMPT (i.e. if the
371 // user types "foo" and the default extension is ".bar" we should force it
372 // to check for "foo.bar" existence and not "foo")
373 wxString defextBuffer; // we need it to be alive until GetSaveFileName()!
374 if (m_dialogStyle & wxSAVE)
375 {
376 const wxChar* extension = filterBuffer;
377 int maxFilter = (int)(of.nFilterIndex*2L) - 1;
378
379 for( int i = 0; i < maxFilter; i++ ) // get extension
380 extension = extension + wxStrlen( extension ) + 1;
381
382 // use dummy name a to avoid assert in AppendExtension
383 defextBuffer = AppendExtension(wxT("a"), extension);
384 if (defextBuffer.StartsWith(wxT("a.")))
385 {
386 defextBuffer.Mid(2);
387 of.lpstrDefExt = defextBuffer.c_str();
388 }
389 }
390
391 // store off before the standard windows dialog can possibly change it
392 const wxString cwdOrig = wxGetCwd();
393
394 //== Execute FileDialog >>=================================================
395
396 bool success = (m_dialogStyle & wxSAVE ? GetSaveFileName(&of)
397 : GetOpenFileName(&of)) != 0;
398
399 #ifdef __WXWINCE__
400 DWORD errCode = GetLastError();
401 #else
402 DWORD errCode = CommDlgExtendedError();
403
404 DWORD errCode = CommDlgExtendedError();
405
406 // GetOpenFileName will always change the current working directory on
407 // (according to MSDN) "Windows NT 4.0/2000/XP" because the flag
408 // OFN_NOCHANGEDIR has no effect. If the user did not specify wxCHANGE_DIR
409 // let's restore the current working directory to what it was before the
410 // dialog was shown (assuming this behavior extends to Windows Server 2003
411 // seems safe).
412 if ( success &&
413 (msw_flags & OFN_NOCHANGEDIR) &&
414 wxGetOsVersion() == wxWINDOWS_NT )
415 {
416 wxSetWorkingDirectory(cwdOrig);
417 }
418
419 #ifdef __WIN32__
420 if (!success && (errCode == CDERR_STRUCTSIZE))
421 {
422 // The struct size has changed so try a smaller or bigger size
423
424 int oldStructSize = of.lStructSize;
425 of.lStructSize = oldStructSize - (sizeof(void *) + 2*sizeof(DWORD));
426 success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
427 : (GetOpenFileName(&of) != 0);
428 errCode = CommDlgExtendedError();
429
430 if (!success && (errCode == CDERR_STRUCTSIZE))
431 {
432 of.lStructSize = oldStructSize + (sizeof(void *) + 2*sizeof(DWORD));
433 success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
434 : (GetOpenFileName(&of) != 0);
435 }
436 }
437 #endif // __WIN32__
438 #endif // __WXWINCE__
439
440 if ( success )
441 {
442 m_fileNames.Empty();
443
444 if ( ( m_dialogStyle & wxMULTIPLE ) &&
445 #if defined(OFN_EXPLORER)
446 ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') )
447 #else
448 ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') )
449 #endif // OFN_EXPLORER
450 )
451 {
452 #if defined(OFN_EXPLORER)
453 m_dir = fileNameBuffer;
454 i = of.nFileOffset;
455 m_fileName = &fileNameBuffer[i];
456 m_fileNames.Add(m_fileName);
457 i += m_fileName.Len() + 1;
458
459 while (fileNameBuffer[i] != wxT('\0'))
460 {
461 m_fileNames.Add(&fileNameBuffer[i]);
462 i += wxStrlen(&fileNameBuffer[i]) + 1;
463 }
464 #else
465 wxStringTokenizer toke(fileNameBuffer, _T(" \t\r\n"));
466 m_dir = toke.GetNextToken();
467 m_fileName = toke.GetNextToken();
468 m_fileNames.Add(m_fileName);
469
470 while (toke.HasMoreTokens())
471 m_fileNames.Add(toke.GetNextToken());
472 #endif // OFN_EXPLORER
473
474 wxString dir(m_dir);
475 if ( m_dir.Last() != _T('\\') )
476 dir += _T('\\');
477
478 m_path = dir + m_fileName;
479 m_filterIndex = (int)of.nFilterIndex - 1;
480 }
481 else
482 {
483 //=== Adding the correct extension >>=================================
484
485 m_filterIndex = (int)of.nFilterIndex - 1;
486
487 if ( !of.nFileExtension ||
488 (of.nFileExtension && fileNameBuffer[of.nFileExtension] == wxT('\0')) )
489 {
490 // User has typed a filename without an extension:
491 const wxChar* extension = filterBuffer;
492 int maxFilter = (int)(of.nFilterIndex*2L) - 1;
493
494 for( int i = 0; i < maxFilter; i++ ) // get extension
495 extension = extension + wxStrlen( extension ) + 1;
496
497 m_fileName = AppendExtension(fileNameBuffer, extension);
498 wxStrncpy(fileNameBuffer, m_fileName.c_str(), wxMin(m_fileName.Len(), wxMAXPATH-1));
499 fileNameBuffer[wxMin(m_fileName.Len(), wxMAXPATH-1)] = wxT('\0');
500 }
501
502 m_path = fileNameBuffer;
503 m_fileName = wxFileNameFromPath(fileNameBuffer);
504 m_fileNames.Add(m_fileName);
505 m_dir = wxPathOnly(fileNameBuffer);
506 }
507 }
508 else
509 {
510 // common dialog failed - why?
511 #ifdef __WXDEBUG__
512 #ifdef __WXWINCE__
513 if (errCode == 0)
514 {
515 // OK, user cancelled the dialog
516 }
517 else if (errCode == ERROR_INVALID_PARAMETER)
518 {
519 wxLogError(wxT("Invalid parameter passed to file dialog function."));
520 }
521 else if (errCode == ERROR_OUTOFMEMORY)
522 {
523 wxLogError(wxT("Out of memory when calling file dialog function."));
524 }
525 else if (errCode == ERROR_CALL_NOT_IMPLEMENTED)
526 {
527 wxLogError(wxT("Call not implemented when calling file dialog function."));
528 }
529 else
530 {
531 wxLogError(wxT("Unknown error %d when calling file dialog function."), errCode);
532 }
533 #else
534 DWORD dwErr = CommDlgExtendedError();
535 if ( dwErr != 0 )
536 {
537 // this msg is only for developers
538 wxLogError(wxT("Common dialog failed with error code %0lx."),
539 dwErr);
540 }
541 //else: it was just cancelled
542 #endif
543 #endif
544 }
545
546 return success ? wxID_OK : wxID_CANCEL;
547
548 }
549
550 #endif // wxUSE_FILEDLG && !(__SMARTPHONE__ && __WXWINCE__)
551