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"
41 #include "wx/testing.h"
43 #include <mach-o/dyld.h>
45 // ============================================================================
47 // ============================================================================
50 // - parameter support for descending into packages as directories (setTreatsFilePackagesAsDirectories)
51 // - as setAllowedFileTypes is only functional for NSOpenPanel on 10.6+, on earlier systems, the file
52 // type choice will not be shown, but all possible file items will be shown, if a popup must be working
53 // then the delegate method - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename will have to
61 // Even if we require 10.6, we might be loaded by an application that
62 // was linked against 10.5. setAllowedFileTypes will still be ignored
63 // in this case. From NSSavePanel.h:
64 // NSOpenPanel: On versions less than 10.6, this property is ignored.
65 // For applications that link against 10.6 and higher, this property will
66 // determine which files should be enabled in the open panel.
67 int32_t version = NSVersionOfLinkTimeLibrary("AppKit");
70 // If we're loaded by an application that doesn't link against AppKit,
71 // use the runtime version instead. This check will not work for the
73 version = NSVersionOfRunTimeLibrary("AppKit");
76 // Notice that this still works correctly even if version is -1.
77 return version >= 0x40e2400 /* version of 10.6 AppKit */;
80 } // anonymous namespace
82 @interface wxOpenPanelDelegate : NSObject wxOSX_10_6_AND_LATER(<NSOpenSavePanelDelegate>)
84 wxFileDialog* _dialog;
87 - (wxFileDialog*) fileDialog;
88 - (void) setFileDialog:(wxFileDialog*) dialog;
90 - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename;
94 @implementation wxOpenPanelDelegate
103 - (wxFileDialog*) fileDialog
108 - (void) setFileDialog:(wxFileDialog*) dialog
113 - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename
115 BOOL showObject = YES;
117 NSString* resolvedLink = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath:filename];
118 if ( resolvedLink != nil )
119 filename = resolvedLink;
121 NSDictionary* fileAttribs = [[NSFileManager defaultManager]
122 fileAttributesAtPath:filename traverseLink:YES];
125 // check for packages
126 if ([NSFileTypeDirectory isEqualTo:[fileAttribs objectForKey:NSFileType]])
128 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:filename] == NO)
129 showObject = YES; // it's a folder, OK to show
132 // it's a packaged directory, apply check
133 wxCFStringRef filecf([filename retain]);
134 showObject = _dialog->CheckFile(filecf.AsString());
139 // the code above only solves links, not aliases, do this here:
141 NSString* resolvedAlias = nil;
143 CFURLRef url = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,
144 (CFStringRef)filename,
145 kCFURLPOSIXPathStyle,
150 if (CFURLGetFSRef(url, &fsRef))
152 Boolean targetIsFolder, wasAliased;
153 OSErr err = FSResolveAliasFile (&fsRef, true, &targetIsFolder, &wasAliased);
155 if ((err == noErr) && wasAliased)
157 CFURLRef resolvedUrl = CFURLCreateFromFSRef(kCFAllocatorDefault, &fsRef);
158 if (resolvedUrl != NULL)
160 resolvedAlias = (NSString*) CFURLCopyFileSystemPath(resolvedUrl,
161 kCFURLPOSIXPathStyle);
162 CFRelease(resolvedUrl);
169 if (resolvedAlias != nil)
172 [resolvedAlias autorelease];
173 showObject = [self panel:sender shouldShowFilename:resolvedAlias];
177 wxCFStringRef filecf([filename retain]);
178 showObject = _dialog->CheckFile(filecf.AsString());
188 IMPLEMENT_CLASS(wxFileDialog, wxFileDialogBase)
190 wxFileDialog::wxFileDialog(
191 wxWindow *parent, const wxString& message,
192 const wxString& defaultDir, const wxString& defaultFileName, const wxString& wildCard,
193 long style, const wxPoint& pos, const wxSize& sz, const wxString& name)
194 : wxFileDialogBase(parent, message, defaultDir, defaultFileName, wildCard, style, pos, sz, name)
197 m_sheetDelegate = [[ModalDialogDelegate alloc] init];
198 [(ModalDialogDelegate*)m_sheetDelegate setImplementation: this];
201 wxFileDialog::~wxFileDialog()
203 [m_sheetDelegate release];
206 bool wxFileDialog::SupportsExtraControl() const
211 NSArray* GetTypesFromExtension( const wxString extensiongroup, wxArrayString& extensions )
213 NSMutableArray* types = nil;
216 wxStringTokenizer tokenizer( extensiongroup, wxT(";") ) ;
217 while ( tokenizer.HasMoreTokens() )
219 wxString extension = tokenizer.GetNextToken() ;
220 // Remove leading '*'
221 if ( extension.length() && (extension.GetChar(0) == '*') )
222 extension = extension.Mid( 1 );
224 // Remove leading '.'
225 if ( extension.length() && (extension.GetChar(0) == '.') )
226 extension = extension.Mid( 1 );
228 // Remove leading '*', this is for handling *.*
229 if ( extension.length() && (extension.GetChar(0) == '*') )
230 extension = extension.Mid( 1 );
232 if ( extension.IsEmpty() )
241 types = [[NSMutableArray alloc] init];
243 extensions.Add(extension.Lower());
244 wxCFStringRef cfext(extension);
245 [types addObject: (NSString*)cfext.AsNSString() ];
247 // add support for classic fileType / creator here
248 wxUint32 fileType, creator;
249 // extension -> mactypes
256 NSArray* GetTypesFromFilter( const wxString& filter, wxArrayString& names, wxArrayString& extensiongroups )
258 NSMutableArray* types = nil;
259 bool allowAll = false;
262 extensiongroups.Clear();
264 if ( !filter.empty() )
266 wxStringTokenizer tokenizer( filter, wxT("|") );
267 int numtokens = (int)tokenizer.CountTokens();
270 // we allow for compatibility reason to have a single filter expression (like *.*) without
271 // an explanatory text, in that case the first part is name and extension at the same time
272 wxString extension = tokenizer.GetNextToken();
273 names.Add( extension );
274 extensiongroups.Add( extension );
278 int numextensions = numtokens / 2;
279 for(int i = 0; i < numextensions; i++)
281 wxString name = tokenizer.GetNextToken();
282 wxString extension = tokenizer.GetNextToken();
284 extensiongroups.Add( extension );
288 const size_t extCount = extensiongroups.GetCount();
289 wxArrayString extensions;
290 for ( size_t i = 0 ; i < extCount; i++ )
292 NSArray* exttypes = GetTypesFromExtension(extensiongroups[i], extensions);
293 if ( exttypes != nil )
295 if ( allowAll == false )
298 types = [[NSMutableArray alloc] init];
300 [types addObjectsFromArray:exttypes];
315 void wxFileDialog::ShowWindowModal()
317 wxCFStringRef cf( m_message );
318 wxCFStringRef dir( m_dir );
319 wxCFStringRef file( m_fileName );
321 wxNonOwnedWindow* parentWindow = NULL;
323 m_modality = wxDIALOG_MODALITY_WINDOW_MODAL;
326 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
328 wxASSERT_MSG(parentWindow, "Window modal display requires parent.");
330 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
331 if ( HasFlag(wxFD_SAVE) )
333 NSSavePanel* sPanel = [NSSavePanel savePanel];
335 SetupExtraControls(sPanel);
337 // makes things more convenient:
338 [sPanel setCanCreateDirectories:YES];
339 [sPanel setMessage:cf.AsNSString()];
340 // if we should be able to descend into pacakges we must somehow
341 // be able to pass this in
342 [sPanel setTreatsFilePackagesAsDirectories:NO];
343 [sPanel setCanSelectHiddenExtension:YES];
344 [sPanel setAllowedFileTypes:types];
345 [sPanel setAllowsOtherFileTypes:NO];
347 NSWindow* nativeParent = parentWindow->GetWXWindow();
348 [sPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
349 modalForWindow: nativeParent modalDelegate: m_sheetDelegate
350 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
355 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
357 SetupExtraControls(oPanel);
359 [oPanel setTreatsFilePackagesAsDirectories:NO];
360 [oPanel setCanChooseDirectories:NO];
361 [oPanel setResolvesAliases:YES];
362 [oPanel setCanChooseFiles:YES];
363 [oPanel setMessage:cf.AsNSString()];
364 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
366 NSWindow* nativeParent = parentWindow->GetWXWindow();
367 [oPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
368 types: types modalForWindow: nativeParent
369 modalDelegate: m_sheetDelegate
370 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
375 // Create a panel with the file type drop down list
376 // If extra controls need to be added (see wxFileDialog::SetExtraControlCreator), add
377 // them to the panel as well
378 // Returns the newly created wxPanel
380 wxWindow* wxFileDialog::CreateFilterPanel(wxWindow *extracontrol)
382 wxPanel *extrapanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize);
383 wxBoxSizer *verticalSizer = new wxBoxSizer(wxVERTICAL);
384 extrapanel->SetSizer(verticalSizer);
386 // the file type control
388 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
389 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
390 wxStaticText *stattext = new wxStaticText( extrapanel, wxID_ANY, _("File type:") );
391 horizontalSizer->Add(stattext, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
392 m_filterChoice = new wxChoice(extrapanel, wxID_ANY);
393 horizontalSizer->Add(m_filterChoice, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
394 m_filterChoice->Append(m_filterNames);
395 if( m_filterNames.GetCount() > 0)
397 if ( m_firstFileTypeFilter >= 0 )
398 m_filterChoice->SetSelection(m_firstFileTypeFilter);
400 m_filterChoice->Connect(wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(wxFileDialog::OnFilterSelected), NULL, this);
405 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
406 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
408 extracontrol->Reparent(extrapanel);
409 horizontalSizer->Add(extracontrol);
412 verticalSizer->Layout();
413 verticalSizer->SetSizeHints(extrapanel);
417 void wxFileDialog::DoOnFilterSelected(int index)
419 NSArray* types = GetTypesFromExtension(m_filterExtensions[index],m_currentExtensions);
420 NSSavePanel* panel = (NSSavePanel*) GetWXWindow();
422 [panel validateVisibleColumns];
424 [panel setAllowedFileTypes:types];
427 // An item has been selected in the file filter wxChoice:
428 void wxFileDialog::OnFilterSelected( wxCommandEvent &WXUNUSED(event) )
430 DoOnFilterSelected( m_filterChoice->GetSelection() );
433 bool wxFileDialog::CheckFile( const wxString& filename )
435 if ( m_currentExtensions.GetCount() == 0 )
438 wxString ext = filename.AfterLast('.').Lower();
440 for ( size_t i = 0; i < m_currentExtensions.GetCount(); ++i )
442 if ( ext == m_currentExtensions[i] )
448 void wxFileDialog::SetupExtraControls(WXWindow nativeWindow)
450 NSSavePanel* panel = (NSSavePanel*) nativeWindow;
452 wxNonOwnedWindow::Create( GetParent(), nativeWindow );
453 wxWindow* extracontrol = NULL;
454 if ( HasExtraControlCreator() )
456 CreateExtraControl();
457 extracontrol = GetExtraControl();
460 NSView* accView = nil;
463 if ( m_useFileTypeFilter )
465 m_filterPanel = CreateFilterPanel(extracontrol);
466 accView = m_filterPanel->GetHandle();
467 if( HasFlag(wxFD_OPEN) )
469 if ( UMAGetSystemVersion() < 0x1060 || !HasAppKit_10_6() )
471 wxOpenPanelDelegate* del = [[wxOpenPanelDelegate alloc]init];
472 [del setFileDialog:this];
473 [panel setDelegate:del];
480 m_filterPanel = NULL;
481 m_filterChoice = NULL;
482 if ( extracontrol != nil )
483 accView = extracontrol->GetHandle();
486 if ( accView != nil )
488 [accView removeFromSuperview];
489 [panel setAccessoryView:accView];
493 [panel setAccessoryView:nil];
497 int wxFileDialog::ShowModal()
499 WX_TESTING_SHOW_MODAL_HOOK();
501 wxCFEventLoopPauseIdleEvents pause;
503 wxMacAutoreleasePool autoreleasepool;
505 wxCFStringRef cf( m_message );
507 wxCFStringRef dir( m_dir );
508 wxCFStringRef file( m_fileName );
510 m_path = wxEmptyString;
514 wxNonOwnedWindow* parentWindow = NULL;
519 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
523 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
525 m_useFileTypeFilter = m_filterExtensions.GetCount() > 1;
527 if( HasFlag(wxFD_OPEN) )
529 if ( !(wxSystemOptions::HasOption( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) && (wxSystemOptions::GetOptionInt( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) == 1)) )
530 m_useFileTypeFilter = false;
533 m_firstFileTypeFilter = -1;
535 if ( m_useFileTypeFilter
536 && m_filterIndex >= 0 && m_filterIndex < m_filterExtensions.GetCount() )
538 m_firstFileTypeFilter = m_filterIndex;
540 else if ( m_useFileTypeFilter )
543 bool useDefault = true;
544 for ( size_t i = 0; i < m_filterExtensions.GetCount(); ++i )
546 types = GetTypesFromExtension(m_filterExtensions[i], m_currentExtensions);
547 if ( m_currentExtensions.GetCount() == 0 )
550 m_firstFileTypeFilter = i;
554 for ( size_t j = 0; j < m_currentExtensions.GetCount(); ++j )
556 if ( m_fileName.EndsWith(m_currentExtensions[j]) )
558 m_firstFileTypeFilter = i;
568 types = GetTypesFromExtension(m_filterExtensions[0], m_currentExtensions);
569 m_firstFileTypeFilter = 0;
573 if ( HasFlag(wxFD_SAVE) )
575 NSSavePanel* sPanel = [NSSavePanel savePanel];
577 SetupExtraControls(sPanel);
579 // makes things more convenient:
580 [sPanel setCanCreateDirectories:YES];
581 [sPanel setMessage:cf.AsNSString()];
582 // if we should be able to descend into pacakges we must somehow
583 // be able to pass this in
584 [sPanel setTreatsFilePackagesAsDirectories:NO];
585 [sPanel setCanSelectHiddenExtension:YES];
586 [sPanel setAllowedFileTypes:types];
587 [sPanel setAllowsOtherFileTypes:NO];
589 if ( HasFlag(wxFD_OVERWRITE_PROMPT) )
594 Let the file dialog know what file type should be used initially.
595 If this is not done then when setting the filter index
596 programmatically to 1 the file will still have the extension
597 of the first file type instead of the second one. E.g. when file
598 types are foo and bar, a filename "myletter" with SetDialogIndex(1)
599 would result in saving as myletter.foo, while we want myletter.bar.
601 if(m_firstFileTypeFilter > 0)
603 DoOnFilterSelected(m_firstFileTypeFilter);
606 returnCode = [sPanel runModalForDirectory: m_dir.IsEmpty() ? nil : dir.AsNSString() file:file.AsNSString() ];
607 ModalFinishedCallback(sPanel, returnCode);
611 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
613 SetupExtraControls(oPanel);
615 [oPanel setTreatsFilePackagesAsDirectories:NO];
616 [oPanel setCanChooseDirectories:NO];
617 [oPanel setResolvesAliases:YES];
618 [oPanel setCanChooseFiles:YES];
619 [oPanel setMessage:cf.AsNSString()];
620 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
622 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
623 if ( UMAGetSystemVersion() >= 0x1060 && HasAppKit_10_6() )
625 [oPanel setAllowedFileTypes: (m_delegate == nil ? types : nil)];
626 if ( !m_dir.IsEmpty() )
627 [oPanel setDirectoryURL:[NSURL fileURLWithPath:dir.AsNSString()
629 returnCode = [oPanel runModal];
634 returnCode = [oPanel runModalForDirectory:m_dir.IsEmpty() ? nil : dir.AsNSString()
635 file:file.AsNSString() types:(m_delegate == nil ? types : nil)];
638 ModalFinishedCallback(oPanel, returnCode);
641 return GetReturnCode();
644 void wxFileDialog::ModalFinishedCallback(void* panel, int returnCode)
646 int result = wxID_CANCEL;
647 if (HasFlag(wxFD_SAVE))
649 if (returnCode == NSOKButton )
651 NSSavePanel* sPanel = (NSSavePanel*)panel;
654 m_path = wxCFStringRef::AsString([sPanel filename]);
655 m_fileName = wxFileNameFromPath(m_path);
656 m_dir = wxPathOnly( m_path );
659 m_filterIndex = m_filterChoice->GetSelection();
665 NSOpenPanel* oPanel = (NSOpenPanel*)panel;
666 if (returnCode == NSOKButton )
670 NSArray* filenames = [oPanel filenames];
671 for ( size_t i = 0 ; i < [filenames count] ; ++ i )
673 wxString fnstr = wxCFStringRef::AsString([filenames objectAtIndex:i]);
674 m_paths.Add( fnstr );
675 m_fileNames.Add( wxFileNameFromPath(fnstr) );
679 m_fileName = wxFileNameFromPath(fnstr);
680 m_dir = wxPathOnly( fnstr );
686 [oPanel setDelegate:nil];
687 [m_delegate release];
691 SetReturnCode(result);
693 if (GetModality() == wxDIALOG_MODALITY_WINDOW_MODAL)
694 SendWindowModalDialogEvent ( wxEVT_WINDOW_MODAL_DIALOG_CLOSED );
697 [(NSSavePanel*) panel setAccessoryView:nil];
700 #endif // wxUSE_FILEDLG