]> git.saurik.com Git - wxWidgets.git/blob - src/mac/filedlg.cpp
made wxFFile a bit more safe: don't crash when Tell() and Length() are called on...
[wxWidgets.git] / src / mac / filedlg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: filedlg.cpp
3 // Purpose: wxFileDialog
4 // Author: Stefan Csomor
5 // Modified by:
6 // Created: 1998-01-01
7 // RCS-ID: $Id$
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "filedlg.h"
14 #endif
15
16 #include "wx/defs.h"
17 #include "wx/app.h"
18 #include "wx/utils.h"
19 #include "wx/dialog.h"
20 #include "wx/filedlg.h"
21 #include "wx/intl.h"
22 #include "wx/tokenzr.h"
23 #include "wx/filename.h"
24
25 #ifndef __DARWIN__
26 #include "PLStringFuncs.h"
27 #endif
28
29 #if !USE_SHARED_LIBRARY
30 IMPLEMENT_CLASS(wxFileDialog, wxFileDialogBase)
31 #endif
32
33 // begin wxmac
34
35 #include "wx/mac/private.h"
36
37 #include <Navigation.h>
38
39 #ifdef __DARWIN__
40 # include "MoreFilesX.h"
41 #else
42 # include "MoreFiles.h"
43 # include "MoreFilesExtras.h"
44 #endif
45
46 extern bool gUseNavServices ;
47
48 // the data we need to pass to our standard file hook routine
49 // includes a pointer to the dialog, a pointer to the standard
50 // file reply record (so we can inspect the current selection)
51 // and a copy of the "previous" file spec of the reply record
52 // so we can see if the selection has changed
53
54 struct OpenUserDataRec {
55 int currentfilter ;
56 bool saveMode ;
57 wxArrayString name ;
58 wxArrayString extensions ;
59 wxArrayLong filtermactypes ;
60 wxString defaultLocation;
61 #if TARGET_CARBON
62 CFArrayRef menuitems ;
63 #else
64 NavMenuItemSpecArrayHandle menuitems ;
65 #endif
66 };
67
68 typedef struct OpenUserDataRec
69 OpenUserDataRec, *OpenUserDataRecPtr;
70
71 static pascal void NavEventProc(
72 NavEventCallbackMessage inSelector,
73 NavCBRecPtr ioParams,
74 NavCallBackUserData ioUserData);
75
76 #if TARGET_CARBON
77 static NavEventUPP sStandardNavEventFilter = NewNavEventUPP(NavEventProc);
78 #else
79 static NavEventUPP sStandardNavEventFilter = NewNavEventProc(NavEventProc);
80 #endif
81
82 static pascal void
83 NavEventProc(
84 NavEventCallbackMessage inSelector,
85 NavCBRecPtr ioParams,
86 NavCallBackUserData ioUserData )
87 {
88 OpenUserDataRec * data = ( OpenUserDataRec *) ioUserData ;
89 if (inSelector == kNavCBEvent) {
90 #if TARGET_CARBON
91 #else
92 wxTheApp->MacHandleOneEvent(ioParams->eventData.eventDataParms.event);
93 #endif
94 }
95 else if ( inSelector == kNavCBStart )
96 {
97 #if TARGET_CARBON
98 if (data && !(data->defaultLocation).IsEmpty())
99 {
100 // Set default location for the modern Navigation APIs
101 // Apple Technical Q&A 1151
102 FSSpec theFSSpec;
103 wxMacFilename2FSSpec(data->defaultLocation, &theFSSpec);
104 AEDesc theLocation = {typeNull, NULL};
105 if (noErr == ::AECreateDesc(typeFSS, &theFSSpec, sizeof(FSSpec), &theLocation))
106 ::NavCustomControl(ioParams->context, kNavCtlSetLocation, (void *) &theLocation);
107 }
108 #else
109 if ( data->menuitems )
110 NavCustomControl(ioParams->context, kNavCtlSelectCustomType, &(*data->menuitems)[data->currentfilter]);
111 #endif
112 }
113 else if ( inSelector == kNavCBPopupMenuSelect )
114 {
115 NavMenuItemSpec * menu = (NavMenuItemSpec *) ioParams->eventData.eventDataParms.param ;
116 #if TARGET_CARBON
117 #else
118 if ( menu->menuCreator == 'WXNG' )
119 #endif
120 {
121 data->currentfilter = menu->menuType ;
122 if ( data->saveMode )
123 {
124 int i = menu->menuType ;
125 wxString extension = data->extensions[i].AfterLast('.') ;
126 extension.MakeLower() ;
127 wxString sfilename ;
128
129 #if TARGET_CARBON
130 wxMacCFStringHolder cfString( NavDialogGetSaveFileName( ioParams->context ) , false );
131 sfilename = cfString.AsString() ;
132 #else
133 Str255 filename ;
134 // get the current filename
135 NavCustomControl(ioParams->context, kNavCtlGetEditFileName, &filename);
136 sfilename = wxMacMakeStringFromPascal( filename ) ;
137 #endif
138
139 int pos = sfilename.Find('.', true) ;
140 if ( pos != wxNOT_FOUND )
141 {
142 sfilename = sfilename.Left(pos+1)+extension ;
143 #if TARGET_CARBON
144 cfString = sfilename ;
145 NavDialogSetSaveFileName( ioParams->context , cfString ) ;
146 #else
147 wxMacStringToPascal( sfilename , filename ) ;
148 NavCustomControl(ioParams->context, kNavCtlSetEditFileName, &filename);
149 #endif
150 }
151 }
152 }
153 }
154 }
155
156
157 void MakeUserDataRec(OpenUserDataRec *myData , const wxString& filter )
158 {
159 myData->menuitems = NULL ;
160 myData->currentfilter = 0 ;
161 myData->saveMode = false ;
162
163 if ( filter && filter[0] )
164 {
165 wxString filter2(filter) ;
166 int filterIndex = 0;
167 bool isName = true ;
168 wxString current ;
169 for( unsigned int i = 0; i < filter2.Len() ; i++ )
170 {
171 if( filter2.GetChar(i) == wxT('|') )
172 {
173 if( isName ) {
174 myData->name.Add( current ) ;
175 }
176 else {
177 myData->extensions.Add( current.MakeUpper() ) ;
178 ++filterIndex ;
179 }
180 isName = !isName ;
181 current = wxEmptyString ;
182 }
183 else
184 {
185 current += filter2.GetChar(i) ;
186 }
187 }
188 // we allow for compatibility reason to have a single filter expression (like *.*) without
189 // an explanatory text, in that case the first part is name and extension at the same time
190
191 wxASSERT_MSG( filterIndex == 0 || !isName , wxT("incorrect format of format string") ) ;
192 if ( current.IsEmpty() )
193 myData->extensions.Add( myData->name[filterIndex] ) ;
194 else
195 myData->extensions.Add( current.MakeUpper() ) ;
196 if ( filterIndex == 0 || isName )
197 myData->name.Add( current.MakeUpper() ) ;
198
199 ++filterIndex ;
200
201 const size_t extCount = myData->extensions.GetCount();
202 for ( size_t i = 0 ; i < extCount; i++ )
203 {
204 wxUint32 fileType;
205 wxUint32 creator;
206 wxString extension = myData->extensions[i];
207
208 if (extension.GetChar(0) == '*')
209 extension = extension.Mid(1); // Remove leading *
210
211 if (extension.GetChar(0) == '.')
212 {
213 extension = extension.Mid(1); // Remove leading .
214 }
215
216 if (wxFileName::MacFindDefaultTypeAndCreator( extension, &fileType, &creator ))
217 {
218 myData->filtermactypes.Add( (OSType)fileType );
219 }
220 else
221 {
222 myData->filtermactypes.Add( '****' ) ; // We'll fail safe if it's not recognized
223 }
224 }
225 }
226 }
227
228 static Boolean CheckFile( const wxString &filename , OSType type , OpenUserDataRecPtr data)
229 {
230 wxString file(filename) ;
231 file.MakeUpper() ;
232
233 if ( data->extensions.GetCount() > 0 )
234 {
235 //for ( int i = 0 ; i < data->numfilters ; ++i )
236 int i = data->currentfilter ;
237 if ( data->extensions[i].Right(2) == wxT(".*") )
238 return true ;
239
240 {
241 if ( type == (OSType)data->filtermactypes[i] )
242 return true ;
243
244 wxStringTokenizer tokenizer( data->extensions[i] , wxT(";") ) ;
245 while( tokenizer.HasMoreTokens() )
246 {
247 wxString extension = tokenizer.GetNextToken() ;
248 if ( extension.GetChar(0) == '*' )
249 extension = extension.Mid(1) ;
250
251 if ( file.Len() >= extension.Len() && extension == file.Right(extension.Len() ) )
252 return true ;
253 }
254 }
255 return false ;
256 }
257 return true ;
258 }
259
260 #ifndef __DARWIN__
261 static pascal Boolean CrossPlatformFileFilter(CInfoPBPtr myCInfoPBPtr, void *dataPtr)
262 {
263 OpenUserDataRecPtr data = (OpenUserDataRecPtr) dataPtr ;
264 // return true if this item is invisible or a file
265
266 Boolean visibleFlag;
267 Boolean folderFlag;
268
269 visibleFlag = ! (myCInfoPBPtr->hFileInfo.ioFlFndrInfo.fdFlags & kIsInvisible);
270 folderFlag = (myCInfoPBPtr->hFileInfo.ioFlAttrib & 0x10);
271
272 // because the semantics of the filter proc are "true means don't show
273 // it" we need to invert the result that we return
274
275 if ( !visibleFlag )
276 return true ;
277
278 if ( !folderFlag )
279 {
280 wxString file = wxMacMakeStringFromPascal( myCInfoPBPtr->hFileInfo.ioNamePtr ) ;
281 return !CheckFile( file , myCInfoPBPtr->hFileInfo.ioFlFndrInfo.fdType , data ) ;
282 }
283
284 return false ;
285 }
286 #endif
287
288 // end wxmac
289
290 wxFileDialog::wxFileDialog(wxWindow *parent, const wxString& message,
291 const wxString& defaultDir, const wxString& defaultFileName, const wxString& wildCard,
292 long style, const wxPoint& pos)
293 :wxFileDialogBase(parent, message, defaultDir, defaultFileName, wildCard, style, pos)
294 {
295 wxASSERT_MSG( NavServicesAvailable() , wxT("Navigation Services are not running") ) ;
296 }
297
298 pascal Boolean CrossPlatformFilterCallback (
299 AEDesc *theItem,
300 void *info,
301 void *callBackUD,
302 NavFilterModes filterMode
303 )
304 {
305 bool display = true;
306 OpenUserDataRecPtr data = (OpenUserDataRecPtr) callBackUD ;
307
308 if (filterMode == kNavFilteringBrowserList)
309 {
310 NavFileOrFolderInfo* theInfo = (NavFileOrFolderInfo*) info ;
311 if ( !theInfo->isFolder )
312 {
313 if (theItem->descriptorType == typeFSS )
314 {
315 FSSpec spec;
316 memcpy( &spec , *theItem->dataHandle , sizeof(FSSpec) ) ;
317 wxString file = wxMacMakeStringFromPascal( spec.name ) ;
318 display = CheckFile( file , theInfo->fileAndFolder.fileInfo.finderInfo.fdType , data ) ;
319 }
320 #if TARGET_CARBON
321 else if ( theItem->descriptorType == typeFSRef )
322 {
323 FSRef fsref ;
324 memcpy( &fsref , *theItem->dataHandle , sizeof(FSRef) ) ;
325 wxString file ;
326 const short maxpath = 1024 ;
327 FSRefMakePath( &fsref , (UInt8*) file.GetWriteBuf(maxpath+1),maxpath) ;
328 file.UngetWriteBuf() ;
329 display = CheckFile( file , theInfo->fileAndFolder.fileInfo.finderInfo.fdType , data ) ;
330 }
331 #endif
332 }
333 }
334
335 return display;
336 }
337
338 int wxFileDialog::ShowModal()
339 {
340 #if TARGET_CARBON
341 OSErr err;
342 NavDialogCreationOptions dialogCreateOptions;
343 // set default options
344 ::NavGetDefaultDialogCreationOptions(&dialogCreateOptions);
345
346 // this was always unset in the old code
347 dialogCreateOptions.optionFlags &= ~kNavSelectDefaultLocation;
348
349 #if wxUSE_UNICODE
350 // tried using wxMacCFStringHolder in the code below, but it seems
351 // the CFStrings were being released before the save dialog was called,
352 // causing a crash - open dialog works fine with or without wxMacCFStringHolder
353 CFStringRef titleRef = ::CFStringCreateWithCharacters( kCFAllocatorDefault,
354 (const unsigned short*)m_message.wc_str(),
355 m_message.Len() );
356 #else
357 CFStringRef titleRef = ::CFStringCreateWithCString(NULL,
358 m_message.c_str(),
359 CFStringGetSystemEncoding());
360 #endif
361 dialogCreateOptions.windowTitle = titleRef;
362 #if wxUSE_UNICODE
363 CFStringRef defaultFileNameRef = ::CFStringCreateWithCharacters( kCFAllocatorDefault,
364 (const unsigned short*)m_fileName.wc_str(),
365 m_fileName.Len() );
366 #else
367 CFStringRef defaultFileNameRef = ::CFStringCreateWithCString(NULL,
368 m_fileName.c_str(),
369 CFStringGetSystemEncoding());
370 #endif
371 dialogCreateOptions.saveFileName = defaultFileNameRef;
372 NavDialogRef dialog;
373 NavObjectFilterUPP navFilterUPP = NULL;
374 CFArrayRef cfArray = NULL; // for popupExtension
375 OpenUserDataRec myData;
376 myData.defaultLocation = m_dir;
377
378 if (m_dialogStyle & wxSAVE)
379 {
380 dialogCreateOptions.optionFlags |= kNavNoTypePopup;
381 dialogCreateOptions.optionFlags |= kNavDontAutoTranslate;
382 dialogCreateOptions.optionFlags |= kNavDontAddTranslateItems;
383
384 // The extension is important
385 dialogCreateOptions.optionFlags |= kNavPreserveSaveFileExtension;
386
387 err = ::NavCreatePutFileDialog(&dialogCreateOptions,
388 'TEXT',
389 'TEXT',
390 sStandardNavEventFilter,
391 &myData, // for defaultLocation
392 &dialog);
393 }
394 else
395 {
396 MakeUserDataRec(&myData , m_wildCard);
397 size_t numfilters = myData.extensions.GetCount();
398 if (numfilters > 0)
399 {
400 CFMutableArrayRef popup = CFArrayCreateMutable( kCFAllocatorDefault ,
401 numfilters , &kCFTypeArrayCallBacks ) ;
402 dialogCreateOptions.popupExtension = popup ;
403 myData.menuitems = dialogCreateOptions.popupExtension ;
404 for ( size_t i = 0 ; i < numfilters ; ++i )
405 {
406 CFArrayAppendValue( popup , (CFStringRef) wxMacCFStringHolder( myData.name[i] ) ) ;
407 }
408 }
409
410 navFilterUPP = NewNavObjectFilterUPP(CrossPlatformFilterCallback);
411 err = ::NavCreateGetFileDialog(&dialogCreateOptions,
412 NULL, // NavTypeListHandle
413 sStandardNavEventFilter,
414 NULL, // NavPreviewUPP
415 navFilterUPP,
416 (void *) &myData, // inClientData
417 &dialog);
418 }
419
420 if (err == noErr)
421 err = ::NavDialogRun(dialog);
422
423 // clean up filter related data, etc.
424 if (navFilterUPP)
425 ::DisposeNavObjectFilterUPP(navFilterUPP);
426 if (cfArray)
427 {
428 CFIndex n = ::CFArrayGetCount(cfArray);
429 for (CFIndex i = 0; i < n; i++)
430 {
431 CFStringRef str = (CFStringRef) ::CFArrayGetValueAtIndex(cfArray, i);
432 if (str)
433 ::CFRelease(str);
434 }
435 ::CFRelease(cfArray);
436 }
437 if (titleRef)
438 ::CFRelease(titleRef);
439 if (defaultFileNameRef)
440 ::CFRelease(defaultFileNameRef);
441 if (err != noErr)
442 return wxID_CANCEL;
443
444 NavReplyRecord navReply;
445 err = ::NavDialogGetReply(dialog, &navReply);
446 if (err == noErr && navReply.validRecord)
447 {
448 AEKeyword theKeyword;
449 DescType actualType;
450 Size actualSize;
451 FSRef theFSRef;
452 wxString thePath ;
453 long count;
454 ::AECountItems(&navReply.selection , &count);
455 for (long i = 1; i <= count; ++i)
456 {
457 err = ::AEGetNthPtr(&(navReply.selection), 1, typeFSRef, &theKeyword, &actualType,
458 &theFSRef, sizeof(theFSRef), &actualSize);
459 if (err != noErr)
460 break;
461
462 CFURLRef fullURLRef;
463 if (m_dialogStyle & wxSAVE)
464 {
465 CFURLRef parentURLRef = ::CFURLCreateFromFSRef(NULL, &theFSRef);
466
467 if (parentURLRef)
468 {
469 fullURLRef =
470 ::CFURLCreateCopyAppendingPathComponent(NULL,
471 parentURLRef,
472 navReply.saveFileName,
473 false);
474 ::CFRelease(parentURLRef);
475 }
476 }
477 else
478 {
479 fullURLRef = ::CFURLCreateFromFSRef(NULL, &theFSRef);
480 }
481 #ifdef __UNIX__
482 CFURLPathStyle pathstyle = kCFURLPOSIXPathStyle;
483 #else
484 CFURLPathStyle pathstyle = kCFURLHFSPathStyle;
485 #endif
486 CFStringRef cfString = CFURLCopyFileSystemPath(fullURLRef, pathstyle);
487 thePath = wxMacCFStringHolder(cfString).AsString();
488 if (!thePath)
489 {
490 ::NavDisposeReply(&navReply);
491 return wxID_CANCEL;
492 }
493 m_path = thePath;
494 m_paths.Add(m_path);
495 m_fileName = wxFileNameFromPath(m_path);
496 m_fileNames.Add(m_fileName);
497 }
498 // set these to the first hit
499 m_path = m_paths[0];
500 m_fileName = wxFileNameFromPath(m_path);
501 m_dir = wxPathOnly(m_path);
502 }
503 ::NavDisposeReply(&navReply);
504
505 return (err == noErr) ? wxID_OK : wxID_CANCEL;
506 #else // TARGET_CARBON
507
508 NavDialogOptions mNavOptions;
509 NavObjectFilterUPP mNavFilterUPP = NULL;
510 NavPreviewUPP mNavPreviewUPP = NULL ;
511 NavReplyRecord mNavReply;
512 AEDesc mDefaultLocation ;
513 bool mSelectDefault = false ;
514 OSStatus err = noErr ;
515 // setup dialog
516
517 mNavFilterUPP = nil;
518 mNavPreviewUPP = nil;
519 mSelectDefault = false;
520 mDefaultLocation.descriptorType = typeNull;
521 mDefaultLocation.dataHandle = nil;
522
523 NavGetDefaultDialogOptions(&mNavOptions);
524 wxMacStringToPascal( m_message , (StringPtr)mNavOptions.message ) ;
525 wxMacStringToPascal( m_fileName , (StringPtr)mNavOptions.savedFileName ) ;
526
527 // Set default location, the location
528 // that's displayed when the dialog
529 // first appears
530
531 FSSpec location ;
532 wxMacFilename2FSSpec( m_dir , &location ) ;
533
534 err = ::AECreateDesc(typeFSS, &location, sizeof(FSSpec), &mDefaultLocation );
535
536 if ( mDefaultLocation.dataHandle )
537 {
538 if (mSelectDefault)
539 {
540 mNavOptions.dialogOptionFlags |= kNavSelectDefaultLocation;
541 } else {
542 mNavOptions.dialogOptionFlags &= ~kNavSelectDefaultLocation;
543 }
544 }
545
546 memset( &mNavReply , 0 , sizeof( mNavReply ) ) ;
547 mNavReply.validRecord = false;
548 mNavReply.replacing = false;
549 mNavReply.isStationery = false;
550 mNavReply.translationNeeded = false;
551 mNavReply.selection.descriptorType = typeNull;
552 mNavReply.selection.dataHandle = nil;
553 mNavReply.keyScript = smSystemScript;
554 mNavReply.fileTranslation = nil;
555 mNavReply.version = kNavReplyRecordVersion ;
556
557 // zero all data
558
559 m_path = wxEmptyString ;
560 m_fileName = wxEmptyString ;
561 m_paths.Empty();
562 m_fileNames.Empty();
563
564 OpenUserDataRec myData;
565 MakeUserDataRec( &myData , m_wildCard ) ;
566 myData.currentfilter = m_filterIndex ;
567 if ( myData.extensions.GetCount() > 0 )
568 {
569 mNavOptions.popupExtension = (NavMenuItemSpecArrayHandle) NewHandle( sizeof( NavMenuItemSpec ) * myData.extensions.GetCount() ) ;
570 myData.menuitems = mNavOptions.popupExtension ;
571 for ( size_t i = 0 ; i < myData.extensions.GetCount() ; ++i )
572 {
573 (*mNavOptions.popupExtension)[i].version = kNavMenuItemSpecVersion ;
574 (*mNavOptions.popupExtension)[i].menuCreator = 'WXNG' ;
575 // TODO : according to the new docs -1 to 10 are reserved for the OS
576 (*mNavOptions.popupExtension)[i].menuType = i ;
577 wxMacStringToPascal( myData.name[i] , (StringPtr)(*mNavOptions.popupExtension)[i].menuItemName ) ;
578 }
579 }
580 if ( m_dialogStyle & wxSAVE )
581 {
582 myData.saveMode = true ;
583
584 mNavOptions.dialogOptionFlags |= kNavDontAutoTranslate ;
585 mNavOptions.dialogOptionFlags |= kNavDontAddTranslateItems ;
586
587 err = ::NavPutFile(
588 &mDefaultLocation,
589 &mNavReply,
590 &mNavOptions,
591 sStandardNavEventFilter ,
592 NULL,
593 kNavGenericSignature,
594 &myData); // User Data
595 m_filterIndex = myData.currentfilter ;
596 }
597 else
598 {
599 myData.saveMode = false ;
600
601 mNavFilterUPP = NewNavObjectFilterUPP( CrossPlatformFilterCallback ) ;
602 if ( m_dialogStyle & wxMULTIPLE )
603 mNavOptions.dialogOptionFlags |= kNavAllowMultipleFiles ;
604 else
605 mNavOptions.dialogOptionFlags &= ~kNavAllowMultipleFiles ;
606
607 err = ::NavGetFile(
608 &mDefaultLocation,
609 &mNavReply,
610 &mNavOptions,
611 sStandardNavEventFilter ,
612 mNavPreviewUPP,
613 mNavFilterUPP,
614 NULL ,
615 &myData);
616 m_filterIndex = myData.currentfilter ;
617 }
618
619 DisposeNavObjectFilterUPP(mNavFilterUPP);
620 if ( mDefaultLocation.dataHandle != nil )
621 {
622 ::AEDisposeDesc(&mDefaultLocation);
623 }
624
625 if ( (err != noErr) && (err != userCanceledErr) ) {
626 return wxID_CANCEL ;
627 }
628
629 if (mNavReply.validRecord)
630 {
631 FSSpec outFileSpec ;
632 AEDesc specDesc ;
633 AEKeyword keyWord ;
634
635 long count ;
636 ::AECountItems( &mNavReply.selection , &count ) ;
637 for ( long i = 1 ; i <= count ; ++i )
638 {
639 OSErr err = ::AEGetNthDesc( &mNavReply.selection , i , typeFSS, &keyWord , &specDesc);
640 if ( err != noErr )
641 {
642 m_path = wxT("") ;
643 return wxID_CANCEL ;
644 }
645 outFileSpec = **(FSSpec**) specDesc.dataHandle;
646 if (specDesc.dataHandle != nil) {
647 ::AEDisposeDesc(&specDesc);
648 }
649 m_path = wxMacFSSpec2MacFilename( &outFileSpec ) ;
650
651 m_paths.Add( m_path ) ;
652 m_fileName = wxFileNameFromPath(m_path);
653 m_fileNames.Add(m_fileName);
654 }
655 // set these to the first hit
656 m_path = m_paths[ 0 ] ;
657 m_fileName = wxFileNameFromPath(m_path);
658 m_dir = wxPathOnly(m_path);
659 NavDisposeReply( &mNavReply ) ;
660 return wxID_OK ;
661 }
662 return wxID_CANCEL;
663 #endif // TARGET_CARBON
664 }
665