1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/cocoa/filedlg.mm
3 // Purpose: wxFileDialog for wxCocoa
8 // Copyright: (c) Ryan Norton
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
25 #include "wx/filedlg.h"
28 #include "wx/msgdlg.h"
31 #include "wx/stattext.h"
32 #include "wx/choice.h"
35 #include "wx/filename.h"
36 #include "wx/tokenzr.h"
37 #include "wx/evtloop.h"
39 #include "wx/osx/private.h"
40 #include "wx/sysopt.h"
42 #include <mach-o/dyld.h>
44 // ============================================================================
46 // ============================================================================
49 // - parameter support for descending into packages as directories (setTreatsFilePackagesAsDirectories)
50 // - as setAllowedFileTypes is only functional for NSOpenPanel on 10.6+, on earlier systems, the file
51 // type choice will not be shown, but all possible file items will be shown, if a popup must be working
52 // then the delegate method - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename will have to
60 // Even if we require 10.6, we might be loaded by an application that
61 // was linked against 10.5. setAllowedFileTypes will still be ignored
62 // in this case. From NSSavePanel.h:
63 // NSOpenPanel: On versions less than 10.6, this property is ignored.
64 // For applications that link against 10.6 and higher, this property will
65 // determine which files should be enabled in the open panel.
66 int32_t version = NSVersionOfLinkTimeLibrary("AppKit");
69 // If we're loaded by an application that doesn't link against AppKit,
70 // use the runtime version instead. This check will not work for the
72 version = NSVersionOfRunTimeLibrary("AppKit");
75 // Notice that this still works correctly even if version is -1.
76 return version >= 0x40e2400 /* version of 10.6 AppKit */;
79 } // anonymous namespace
81 @interface wxOpenPanelDelegate : NSObject wxOSX_10_6_AND_LATER(<NSOpenSavePanelDelegate>)
83 wxFileDialog* _dialog;
86 - (wxFileDialog*) fileDialog;
87 - (void) setFileDialog:(wxFileDialog*) dialog;
89 - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename;
93 @implementation wxOpenPanelDelegate
102 - (wxFileDialog*) fileDialog
107 - (void) setFileDialog:(wxFileDialog*) dialog
112 - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename
114 BOOL showObject = YES;
116 NSString* resolvedLink = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath:filename];
117 if ( resolvedLink != nil )
118 filename = resolvedLink;
120 NSDictionary* fileAttribs = [[NSFileManager defaultManager]
121 fileAttributesAtPath:filename traverseLink:YES];
124 // check for packages
125 if ([NSFileTypeDirectory isEqualTo:[fileAttribs objectForKey:NSFileType]])
127 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:filename] == NO)
128 showObject = YES; // it's a folder, OK to show
131 // it's a packaged directory, apply check
132 wxCFStringRef filecf([filename retain]);
133 showObject = _dialog->CheckFile(filecf.AsString());
138 // the code above only solves links, not aliases, do this here:
140 NSString* resolvedAlias = nil;
142 CFURLRef url = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,
143 (CFStringRef)filename,
144 kCFURLPOSIXPathStyle,
149 if (CFURLGetFSRef(url, &fsRef))
151 Boolean targetIsFolder, wasAliased;
152 OSErr err = FSResolveAliasFile (&fsRef, true, &targetIsFolder, &wasAliased);
154 if ((err == noErr) && wasAliased)
156 CFURLRef resolvedUrl = CFURLCreateFromFSRef(kCFAllocatorDefault, &fsRef);
157 if (resolvedUrl != NULL)
159 resolvedAlias = (NSString*) CFURLCopyFileSystemPath(resolvedUrl,
160 kCFURLPOSIXPathStyle);
161 CFRelease(resolvedUrl);
168 if (resolvedAlias != nil)
171 [resolvedAlias autorelease];
172 showObject = [self panel:sender shouldShowFilename:resolvedAlias];
176 wxCFStringRef filecf([filename retain]);
177 showObject = _dialog->CheckFile(filecf.AsString());
187 IMPLEMENT_CLASS(wxFileDialog, wxFileDialogBase)
189 wxFileDialog::wxFileDialog(
190 wxWindow *parent, const wxString& message,
191 const wxString& defaultDir, const wxString& defaultFileName, const wxString& wildCard,
192 long style, const wxPoint& pos, const wxSize& sz, const wxString& name)
193 : wxFileDialogBase(parent, message, defaultDir, defaultFileName, wildCard, style, pos, sz, name)
196 m_sheetDelegate = [[ModalDialogDelegate alloc] init];
197 [(ModalDialogDelegate*)m_sheetDelegate setImplementation: this];
200 wxFileDialog::~wxFileDialog()
202 [m_sheetDelegate release];
205 bool wxFileDialog::SupportsExtraControl() const
210 NSArray* GetTypesFromExtension( const wxString extensiongroup, wxArrayString& extensions )
212 NSMutableArray* types = nil;
215 wxStringTokenizer tokenizer( extensiongroup, wxT(";") ) ;
216 while ( tokenizer.HasMoreTokens() )
218 wxString extension = tokenizer.GetNextToken() ;
219 // Remove leading '*'
220 if ( extension.length() && (extension.GetChar(0) == '*') )
221 extension = extension.Mid( 1 );
223 // Remove leading '.'
224 if ( extension.length() && (extension.GetChar(0) == '.') )
225 extension = extension.Mid( 1 );
227 // Remove leading '*', this is for handling *.*
228 if ( extension.length() && (extension.GetChar(0) == '*') )
229 extension = extension.Mid( 1 );
231 if ( extension.IsEmpty() )
240 types = [[NSMutableArray alloc] init];
242 extensions.Add(extension.Lower());
243 wxCFStringRef cfext(extension);
244 [types addObject: (NSString*)cfext.AsNSString() ];
246 // add support for classic fileType / creator here
247 wxUint32 fileType, creator;
248 // extension -> mactypes
255 NSArray* GetTypesFromFilter( const wxString& filter, wxArrayString& names, wxArrayString& extensiongroups )
257 NSMutableArray* types = nil;
258 bool allowAll = false;
261 extensiongroups.Clear();
263 if ( !filter.empty() )
265 wxStringTokenizer tokenizer( filter, wxT("|") );
266 int numtokens = (int)tokenizer.CountTokens();
269 // we allow for compatibility reason to have a single filter expression (like *.*) without
270 // an explanatory text, in that case the first part is name and extension at the same time
271 wxString extension = tokenizer.GetNextToken();
272 names.Add( extension );
273 extensiongroups.Add( extension );
277 int numextensions = numtokens / 2;
278 for(int i = 0; i < numextensions; i++)
280 wxString name = tokenizer.GetNextToken();
281 wxString extension = tokenizer.GetNextToken();
283 extensiongroups.Add( extension );
287 const size_t extCount = extensiongroups.GetCount();
288 wxArrayString extensions;
289 for ( size_t i = 0 ; i < extCount; i++ )
291 NSArray* exttypes = GetTypesFromExtension(extensiongroups[i], extensions);
292 if ( exttypes != nil )
294 if ( allowAll == false )
297 types = [[NSMutableArray alloc] init];
299 [types addObjectsFromArray:exttypes];
314 void wxFileDialog::ShowWindowModal()
316 wxCFStringRef cf( m_message );
317 wxCFStringRef dir( m_dir );
318 wxCFStringRef file( m_fileName );
320 wxNonOwnedWindow* parentWindow = NULL;
322 m_modality = wxDIALOG_MODALITY_WINDOW_MODAL;
325 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
327 wxASSERT_MSG(parentWindow, "Window modal display requires parent.");
329 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
330 if ( HasFlag(wxFD_SAVE) )
332 NSSavePanel* sPanel = [NSSavePanel savePanel];
334 SetupExtraControls(sPanel);
336 // makes things more convenient:
337 [sPanel setCanCreateDirectories:YES];
338 [sPanel setMessage:cf.AsNSString()];
339 // if we should be able to descend into pacakges we must somehow
340 // be able to pass this in
341 [sPanel setTreatsFilePackagesAsDirectories:NO];
342 [sPanel setCanSelectHiddenExtension:YES];
343 [sPanel setAllowedFileTypes:types];
344 [sPanel setAllowsOtherFileTypes:NO];
346 NSWindow* nativeParent = parentWindow->GetWXWindow();
347 [sPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
348 modalForWindow: nativeParent modalDelegate: m_sheetDelegate
349 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
354 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
356 SetupExtraControls(oPanel);
358 [oPanel setTreatsFilePackagesAsDirectories:NO];
359 [oPanel setCanChooseDirectories:NO];
360 [oPanel setResolvesAliases:YES];
361 [oPanel setCanChooseFiles:YES];
362 [oPanel setMessage:cf.AsNSString()];
363 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
365 NSWindow* nativeParent = parentWindow->GetWXWindow();
366 [oPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
367 types: types modalForWindow: nativeParent
368 modalDelegate: m_sheetDelegate
369 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
374 // Create a panel with the file type drop down list
375 // If extra controls need to be added (see wxFileDialog::SetExtraControlCreator), add
376 // them to the panel as well
377 // Returns the newly created wxPanel
379 wxWindow* wxFileDialog::CreateFilterPanel(wxWindow *extracontrol)
381 wxPanel *extrapanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize);
382 wxBoxSizer *verticalSizer = new wxBoxSizer(wxVERTICAL);
383 extrapanel->SetSizer(verticalSizer);
385 // the file type control
387 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
388 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
389 wxStaticText *stattext = new wxStaticText( extrapanel, wxID_ANY, _("File type:") );
390 horizontalSizer->Add(stattext, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
391 m_filterChoice = new wxChoice(extrapanel, wxID_ANY);
392 horizontalSizer->Add(m_filterChoice, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
393 m_filterChoice->Append(m_filterNames);
394 if( m_filterNames.GetCount() > 0)
396 if ( m_firstFileTypeFilter >= 0 )
397 m_filterChoice->SetSelection(m_firstFileTypeFilter);
399 m_filterChoice->Connect(wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(wxFileDialog::OnFilterSelected), NULL, this);
404 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
405 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
407 extracontrol->Reparent(extrapanel);
408 horizontalSizer->Add(extracontrol);
411 verticalSizer->Layout();
412 verticalSizer->SetSizeHints(extrapanel);
416 void wxFileDialog::DoOnFilterSelected(int index)
418 NSArray* types = GetTypesFromExtension(m_filterExtensions[index],m_currentExtensions);
419 NSSavePanel* panel = (NSSavePanel*) GetWXWindow();
421 [panel validateVisibleColumns];
423 [panel setAllowedFileTypes:types];
426 // An item has been selected in the file filter wxChoice:
427 void wxFileDialog::OnFilterSelected( wxCommandEvent &WXUNUSED(event) )
429 DoOnFilterSelected( m_filterChoice->GetSelection() );
432 bool wxFileDialog::CheckFile( const wxString& filename )
434 if ( m_currentExtensions.GetCount() == 0 )
437 wxString ext = filename.AfterLast('.').Lower();
439 for ( size_t i = 0; i < m_currentExtensions.GetCount(); ++i )
441 if ( ext == m_currentExtensions[i] )
447 void wxFileDialog::SetupExtraControls(WXWindow nativeWindow)
449 NSSavePanel* panel = (NSSavePanel*) nativeWindow;
451 wxNonOwnedWindow::Create( GetParent(), nativeWindow );
452 wxWindow* extracontrol = NULL;
453 if ( HasExtraControlCreator() )
455 CreateExtraControl();
456 extracontrol = GetExtraControl();
459 NSView* accView = nil;
462 if ( m_useFileTypeFilter )
464 m_filterPanel = CreateFilterPanel(extracontrol);
465 accView = m_filterPanel->GetHandle();
466 if( HasFlag(wxFD_OPEN) )
468 if ( UMAGetSystemVersion() < 0x1060 || !HasAppKit_10_6() )
470 wxOpenPanelDelegate* del = [[wxOpenPanelDelegate alloc]init];
471 [del setFileDialog:this];
472 [panel setDelegate:del];
479 m_filterPanel = NULL;
480 m_filterChoice = NULL;
481 if ( extracontrol != nil )
482 accView = extracontrol->GetHandle();
485 if ( accView != nil )
487 [accView removeFromSuperview];
488 [panel setAccessoryView:accView];
492 [panel setAccessoryView:nil];
496 int wxFileDialog::ShowModal()
498 wxCFEventLoopPauseIdleEvents pause;
500 wxMacAutoreleasePool autoreleasepool;
502 wxCFStringRef cf( m_message );
504 wxCFStringRef dir( m_dir );
505 wxCFStringRef file( m_fileName );
507 m_path = wxEmptyString;
511 wxNonOwnedWindow* parentWindow = NULL;
516 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
520 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
522 m_useFileTypeFilter = m_filterExtensions.GetCount() > 1;
524 if( HasFlag(wxFD_OPEN) )
526 if ( !(wxSystemOptions::HasOption( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) && (wxSystemOptions::GetOptionInt( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) == 1)) )
527 m_useFileTypeFilter = false;
530 m_firstFileTypeFilter = -1;
532 if ( m_useFileTypeFilter
533 && m_filterIndex >= 0 && m_filterIndex < m_filterExtensions.GetCount() )
535 m_firstFileTypeFilter = m_filterIndex;
537 else if ( m_useFileTypeFilter )
540 bool useDefault = true;
541 for ( size_t i = 0; i < m_filterExtensions.GetCount(); ++i )
543 types = GetTypesFromExtension(m_filterExtensions[i], m_currentExtensions);
544 if ( m_currentExtensions.GetCount() == 0 )
547 m_firstFileTypeFilter = i;
551 for ( size_t j = 0; j < m_currentExtensions.GetCount(); ++j )
553 if ( m_fileName.EndsWith(m_currentExtensions[j]) )
555 m_firstFileTypeFilter = i;
565 types = GetTypesFromExtension(m_filterExtensions[0], m_currentExtensions);
566 m_firstFileTypeFilter = 0;
570 if ( HasFlag(wxFD_SAVE) )
572 NSSavePanel* sPanel = [NSSavePanel savePanel];
574 SetupExtraControls(sPanel);
576 // makes things more convenient:
577 [sPanel setCanCreateDirectories:YES];
578 [sPanel setMessage:cf.AsNSString()];
579 // if we should be able to descend into pacakges we must somehow
580 // be able to pass this in
581 [sPanel setTreatsFilePackagesAsDirectories:NO];
582 [sPanel setCanSelectHiddenExtension:YES];
583 [sPanel setAllowedFileTypes:types];
584 [sPanel setAllowsOtherFileTypes:NO];
586 if ( HasFlag(wxFD_OVERWRITE_PROMPT) )
591 Let the file dialog know what file type should be used initially.
592 If this is not done then when setting the filter index
593 programmatically to 1 the file will still have the extension
594 of the first file type instead of the second one. E.g. when file
595 types are foo and bar, a filename "myletter" with SetDialogIndex(1)
596 would result in saving as myletter.foo, while we want myletter.bar.
598 if(m_firstFileTypeFilter > 0)
600 DoOnFilterSelected(m_firstFileTypeFilter);
603 returnCode = [sPanel runModalForDirectory: m_dir.IsEmpty() ? nil : dir.AsNSString() file:file.AsNSString() ];
604 ModalFinishedCallback(sPanel, returnCode);
608 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
610 SetupExtraControls(oPanel);
612 [oPanel setTreatsFilePackagesAsDirectories:NO];
613 [oPanel setCanChooseDirectories:NO];
614 [oPanel setResolvesAliases:YES];
615 [oPanel setCanChooseFiles:YES];
616 [oPanel setMessage:cf.AsNSString()];
617 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
619 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
620 if ( UMAGetSystemVersion() >= 0x1060 && HasAppKit_10_6() )
622 [oPanel setAllowedFileTypes: (m_delegate == nil ? types : nil)];
623 if ( !m_dir.IsEmpty() )
624 [oPanel setDirectoryURL:[NSURL fileURLWithPath:dir.AsNSString()
626 returnCode = [oPanel runModal];
631 returnCode = [oPanel runModalForDirectory:m_dir.IsEmpty() ? nil : dir.AsNSString()
632 file:file.AsNSString() types:(m_delegate == nil ? types : nil)];
635 ModalFinishedCallback(oPanel, returnCode);
638 return GetReturnCode();
641 void wxFileDialog::ModalFinishedCallback(void* panel, int returnCode)
643 int result = wxID_CANCEL;
644 if (HasFlag(wxFD_SAVE))
646 if (returnCode == NSOKButton )
648 NSSavePanel* sPanel = (NSSavePanel*)panel;
651 m_path = wxCFStringRef::AsString([sPanel filename]);
652 m_fileName = wxFileNameFromPath(m_path);
653 m_dir = wxPathOnly( m_path );
656 m_filterIndex = m_filterChoice->GetSelection();
662 NSOpenPanel* oPanel = (NSOpenPanel*)panel;
663 if (returnCode == NSOKButton )
667 NSArray* filenames = [oPanel filenames];
668 for ( size_t i = 0 ; i < [filenames count] ; ++ i )
670 wxString fnstr = wxCFStringRef::AsString([filenames objectAtIndex:i]);
671 m_paths.Add( fnstr );
672 m_fileNames.Add( wxFileNameFromPath(fnstr) );
676 m_fileName = wxFileNameFromPath(fnstr);
677 m_dir = wxPathOnly( fnstr );
683 [oPanel setDelegate:nil];
684 [m_delegate release];
688 SetReturnCode(result);
690 if (GetModality() == wxDIALOG_MODALITY_WINDOW_MODAL)
691 SendWindowModalDialogEvent ( wxEVT_WINDOW_MODAL_DIALOG_CLOSED );
694 [(NSSavePanel*) panel setAccessoryView:nil];
697 #endif // wxUSE_FILEDLG