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