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"
38 #include "wx/osx/private.h"
39 #include "wx/sysopt.h"
41 // ============================================================================
43 // ============================================================================
46 // - parameter support for descending into packages as directories (setTreatsFilePackagesAsDirectories)
47 // - as setAllowedFileTypes is only functional for NSOpenPanel on 10.6+, on earlier systems, the file
48 // type choice will not be shown, but all possible file items will be shown, if a popup must be working
49 // then the delegate method - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename will have to
52 @interface wxOpenPanelDelegate : NSObject wxOSX_10_6_AND_LATER(<NSOpenSavePanelDelegate>)
54 wxFileDialog* _dialog;
57 - (wxFileDialog*) fileDialog;
58 - (void) setFileDialog:(wxFileDialog*) dialog;
60 - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename;
64 @implementation wxOpenPanelDelegate
73 - (wxFileDialog*) fileDialog
78 - (void) setFileDialog:(wxFileDialog*) dialog
83 - (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename
85 BOOL showObject = YES;
87 NSString* resolvedLink = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath:filename];
88 if ( resolvedLink != nil )
89 filename = resolvedLink;
91 NSDictionary* fileAttribs = [[NSFileManager defaultManager]
92 fileAttributesAtPath:filename traverseLink:YES];
96 if ([NSFileTypeDirectory isEqualTo:[fileAttribs objectForKey:NSFileType]])
98 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:filename] == NO)
99 showObject = YES; // it's a folder, OK to show
102 // it's a packaged directory, apply check
103 wxCFStringRef filecf([filename retain]);
104 showObject = _dialog->CheckFile(filecf.AsString());
109 // the code above only solves links, not aliases, do this here:
111 NSString* resolvedAlias = nil;
113 CFURLRef url = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,
114 (CFStringRef)filename,
115 kCFURLPOSIXPathStyle,
120 if (CFURLGetFSRef(url, &fsRef))
122 Boolean targetIsFolder, wasAliased;
123 OSErr err = FSResolveAliasFile (&fsRef, true, &targetIsFolder, &wasAliased);
125 if ((err == noErr) && wasAliased)
127 CFURLRef resolvedUrl = CFURLCreateFromFSRef(kCFAllocatorDefault, &fsRef);
128 if (resolvedUrl != NULL)
130 resolvedAlias = (NSString*) CFURLCopyFileSystemPath(resolvedUrl,
131 kCFURLPOSIXPathStyle);
132 CFRelease(resolvedUrl);
139 if (resolvedAlias != nil)
142 [resolvedAlias autorelease];
143 showObject = [self panel:sender shouldShowFilename:resolvedAlias];
147 wxCFStringRef filecf([filename retain]);
148 showObject = _dialog->CheckFile(filecf.AsString());
158 IMPLEMENT_CLASS(wxFileDialog, wxFileDialogBase)
160 wxFileDialog::wxFileDialog(
161 wxWindow *parent, const wxString& message,
162 const wxString& defaultDir, const wxString& defaultFileName, const wxString& wildCard,
163 long style, const wxPoint& pos, const wxSize& sz, const wxString& name)
164 : wxFileDialogBase(parent, message, defaultDir, defaultFileName, wildCard, style, pos, sz, name)
167 m_sheetDelegate = [[ModalDialogDelegate alloc] init];
168 [(ModalDialogDelegate*)m_sheetDelegate setImplementation: this];
171 wxFileDialog::~wxFileDialog()
173 [m_sheetDelegate release];
176 bool wxFileDialog::SupportsExtraControl() const
181 NSArray* GetTypesFromExtension( const wxString extensiongroup, wxArrayString& extensions )
183 NSMutableArray* types = nil;
186 wxStringTokenizer tokenizer( extensiongroup, wxT(";") ) ;
187 while ( tokenizer.HasMoreTokens() )
189 wxString extension = tokenizer.GetNextToken() ;
190 // Remove leading '*'
191 if ( extension.length() && (extension.GetChar(0) == '*') )
192 extension = extension.Mid( 1 );
194 // Remove leading '.'
195 if ( extension.length() && (extension.GetChar(0) == '.') )
196 extension = extension.Mid( 1 );
198 // Remove leading '*', this is for handling *.*
199 if ( extension.length() && (extension.GetChar(0) == '*') )
200 extension = extension.Mid( 1 );
202 if ( extension.IsEmpty() )
211 types = [[NSMutableArray alloc] init];
213 extensions.Add(extension.Lower());
214 wxCFStringRef cfext(extension);
215 [types addObject: (NSString*)cfext.AsNSString() ];
217 // add support for classic fileType / creator here
218 wxUint32 fileType, creator;
219 // extension -> mactypes
226 NSArray* GetTypesFromFilter( const wxString& filter, wxArrayString& names, wxArrayString& extensiongroups )
228 NSMutableArray* types = nil;
229 bool allowAll = false;
232 extensiongroups.Clear();
234 if ( !filter.empty() )
236 wxStringTokenizer tokenizer( filter, wxT("|") );
237 int numtokens = (int)tokenizer.CountTokens();
240 // we allow for compatibility reason to have a single filter expression (like *.*) without
241 // an explanatory text, in that case the first part is name and extension at the same time
242 wxString extension = tokenizer.GetNextToken();
243 names.Add( extension );
244 extensiongroups.Add( extension );
248 int numextensions = numtokens / 2;
249 for(int i = 0; i < numextensions; i++)
251 wxString name = tokenizer.GetNextToken();
252 wxString extension = tokenizer.GetNextToken();
254 extensiongroups.Add( extension );
258 const size_t extCount = extensiongroups.GetCount();
259 wxArrayString extensions;
260 for ( size_t i = 0 ; i < extCount; i++ )
262 NSArray* exttypes = GetTypesFromExtension(extensiongroups[i], extensions);
263 if ( exttypes != nil )
265 if ( allowAll == false )
268 types = [[NSMutableArray alloc] init];
270 [types addObjectsFromArray:exttypes];
285 void wxFileDialog::ShowWindowModal()
287 wxCFStringRef cf( m_message );
288 wxCFStringRef dir( m_dir );
289 wxCFStringRef file( m_fileName );
291 wxNonOwnedWindow* parentWindow = NULL;
293 m_modality = wxDIALOG_MODALITY_WINDOW_MODAL;
296 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
298 wxASSERT_MSG(parentWindow, "Window modal display requires parent.");
300 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
301 if ( HasFlag(wxFD_SAVE) )
303 NSSavePanel* sPanel = [NSSavePanel savePanel];
305 SetupExtraControls(sPanel);
307 // makes things more convenient:
308 [sPanel setCanCreateDirectories:YES];
309 [sPanel setMessage:cf.AsNSString()];
310 // if we should be able to descend into pacakges we must somehow
311 // be able to pass this in
312 [sPanel setTreatsFilePackagesAsDirectories:NO];
313 [sPanel setCanSelectHiddenExtension:YES];
314 [sPanel setAllowedFileTypes:types];
315 [sPanel setAllowsOtherFileTypes:NO];
317 NSWindow* nativeParent = parentWindow->GetWXWindow();
318 [sPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
319 modalForWindow: nativeParent modalDelegate: m_sheetDelegate
320 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
325 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
327 SetupExtraControls(oPanel);
329 [oPanel setTreatsFilePackagesAsDirectories:NO];
330 [oPanel setCanChooseDirectories:NO];
331 [oPanel setResolvesAliases:YES];
332 [oPanel setCanChooseFiles:YES];
333 [oPanel setMessage:cf.AsNSString()];
334 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
336 NSWindow* nativeParent = parentWindow->GetWXWindow();
337 [oPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
338 types: types modalForWindow: nativeParent
339 modalDelegate: m_sheetDelegate
340 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
345 // Create a panel with the file type drop down list
346 // If extra controls need to be added (see wxFileDialog::SetExtraControlCreator), add
347 // them to the panel as well
348 // Returns the newly created wxPanel
350 wxWindow* wxFileDialog::CreateFilterPanel(wxWindow *extracontrol)
352 wxPanel *extrapanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize);
353 wxBoxSizer *verticalSizer = new wxBoxSizer(wxVERTICAL);
354 extrapanel->SetSizer(verticalSizer);
356 // the file type control
358 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
359 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
360 wxStaticText *stattext = new wxStaticText( extrapanel, wxID_ANY, _("File type:") );
361 horizontalSizer->Add(stattext, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
362 m_filterChoice = new wxChoice(extrapanel, wxID_ANY);
363 horizontalSizer->Add(m_filterChoice, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
364 m_filterChoice->Append(m_filterNames);
365 if( m_filterNames.GetCount() > 0)
367 if ( m_firstFileTypeFilter >= 0 )
368 m_filterChoice->SetSelection(m_firstFileTypeFilter);
370 m_filterChoice->Connect(wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(wxFileDialog::OnFilterSelected), NULL, this);
375 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
376 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
378 extracontrol->Reparent(extrapanel);
379 horizontalSizer->Add(extracontrol);
382 verticalSizer->Layout();
383 verticalSizer->SetSizeHints(extrapanel);
387 void wxFileDialog::DoOnFilterSelected(int index)
389 NSArray* types = GetTypesFromExtension(m_filterExtensions[index],m_currentExtensions);
390 NSSavePanel* panel = (NSSavePanel*) GetWXWindow();
392 [panel validateVisibleColumns];
394 [panel setAllowedFileTypes:types];
397 // An item has been selected in the file filter wxChoice:
398 void wxFileDialog::OnFilterSelected( wxCommandEvent &WXUNUSED(event) )
400 DoOnFilterSelected( m_filterChoice->GetSelection() );
403 bool wxFileDialog::CheckFile( const wxString& filename )
405 if ( m_currentExtensions.GetCount() == 0 )
408 wxString ext = filename.AfterLast('.').Lower();
410 for ( size_t i = 0; i < m_currentExtensions.GetCount(); ++i )
412 if ( ext == m_currentExtensions[i] )
418 void wxFileDialog::SetupExtraControls(WXWindow nativeWindow)
420 NSSavePanel* panel = (NSSavePanel*) nativeWindow;
422 wxNonOwnedWindow::Create( GetParent(), nativeWindow );
423 wxWindow* extracontrol = NULL;
424 if ( HasExtraControlCreator() )
426 CreateExtraControl();
427 extracontrol = GetExtraControl();
430 NSView* accView = nil;
433 if ( m_useFileTypeFilter )
435 m_filterPanel = CreateFilterPanel(extracontrol);
436 accView = m_filterPanel->GetHandle();
437 if( HasFlag(wxFD_OPEN) )
439 if ( UMAGetSystemVersion() < 0x1060 )
441 wxOpenPanelDelegate* del = [[wxOpenPanelDelegate alloc]init];
442 [del setFileDialog:this];
443 [panel setDelegate:del];
450 m_filterPanel = NULL;
451 m_filterChoice = NULL;
452 if ( extracontrol != nil )
453 accView = extracontrol->GetHandle();
456 if ( accView != nil )
458 [accView removeFromSuperview];
459 [panel setAccessoryView:accView];
463 [panel setAccessoryView:nil];
467 int wxFileDialog::ShowModal()
469 wxMacAutoreleasePool autoreleasepool;
471 wxCFStringRef cf( m_message );
473 wxCFStringRef dir( m_dir );
474 wxCFStringRef file( m_fileName );
476 m_path = wxEmptyString;
480 wxNonOwnedWindow* parentWindow = NULL;
485 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
489 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
491 m_useFileTypeFilter = m_filterExtensions.GetCount() > 1;
493 if( HasFlag(wxFD_OPEN) )
495 if ( !(wxSystemOptions::HasOption( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) && (wxSystemOptions::GetOptionInt( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) == 1)) )
496 m_useFileTypeFilter = false;
499 m_firstFileTypeFilter = -1;
501 if ( m_useFileTypeFilter
502 && m_filterIndex >= 0 && m_filterIndex < m_filterExtensions.GetCount() )
504 m_firstFileTypeFilter = m_filterIndex;
506 else if ( m_useFileTypeFilter )
509 bool useDefault = true;
510 for ( size_t i = 0; i < m_filterExtensions.GetCount(); ++i )
512 types = GetTypesFromExtension(m_filterExtensions[i], m_currentExtensions);
513 if ( m_currentExtensions.GetCount() == 0 )
516 m_firstFileTypeFilter = i;
520 for ( size_t j = 0; j < m_currentExtensions.GetCount(); ++j )
522 if ( m_fileName.EndsWith(m_currentExtensions[j]) )
524 m_firstFileTypeFilter = i;
534 types = GetTypesFromExtension(m_filterExtensions[0], m_currentExtensions);
535 m_firstFileTypeFilter = 0;
539 if ( HasFlag(wxFD_SAVE) )
541 NSSavePanel* sPanel = [NSSavePanel savePanel];
543 SetupExtraControls(sPanel);
545 // makes things more convenient:
546 [sPanel setCanCreateDirectories:YES];
547 [sPanel setMessage:cf.AsNSString()];
548 // if we should be able to descend into pacakges we must somehow
549 // be able to pass this in
550 [sPanel setTreatsFilePackagesAsDirectories:NO];
551 [sPanel setCanSelectHiddenExtension:YES];
552 [sPanel setAllowedFileTypes:types];
553 [sPanel setAllowsOtherFileTypes:NO];
555 if ( HasFlag(wxFD_OVERWRITE_PROMPT) )
560 Let the file dialog know what file type should be used initially.
561 If this is not done then when setting the filter index
562 programmatically to 1 the file will still have the extension
563 of the first file type instead of the second one. E.g. when file
564 types are foo and bar, a filename "myletter" with SetDialogIndex(1)
565 would result in saving as myletter.foo, while we want myletter.bar.
567 if(m_firstFileTypeFilter > 0)
569 DoOnFilterSelected(m_firstFileTypeFilter);
572 returnCode = [sPanel runModalForDirectory: m_dir.IsEmpty() ? nil : dir.AsNSString() file:file.AsNSString() ];
573 ModalFinishedCallback(sPanel, returnCode);
577 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
579 SetupExtraControls(oPanel);
581 [oPanel setTreatsFilePackagesAsDirectories:NO];
582 [oPanel setCanChooseDirectories:NO];
583 [oPanel setResolvesAliases:YES];
584 [oPanel setCanChooseFiles:YES];
585 [oPanel setMessage:cf.AsNSString()];
586 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
588 if ( UMAGetSystemVersion() < 0x1060 )
590 returnCode = [oPanel runModalForDirectory:m_dir.IsEmpty() ? nil : dir.AsNSString()
591 file:file.AsNSString() types:(m_delegate == nil ? types : nil)];
595 [oPanel setAllowedFileTypes: (m_delegate == nil ? types : nil)];
596 if ( !m_dir.IsEmpty() )
597 [oPanel setDirectoryURL:[NSURL fileURLWithPath:dir.AsNSString()
599 returnCode = [oPanel runModal];
602 ModalFinishedCallback(oPanel, returnCode);
605 return GetReturnCode();
608 void wxFileDialog::ModalFinishedCallback(void* panel, int returnCode)
610 int result = wxID_CANCEL;
611 if (HasFlag(wxFD_SAVE))
613 if (returnCode == NSOKButton )
615 NSSavePanel* sPanel = (NSSavePanel*)panel;
618 m_path = wxCFStringRef::AsString([sPanel filename]);
619 m_fileName = wxFileNameFromPath(m_path);
620 m_dir = wxPathOnly( m_path );
623 m_filterIndex = m_filterChoice->GetSelection();
629 NSOpenPanel* oPanel = (NSOpenPanel*)panel;
630 if (returnCode == NSOKButton )
634 NSArray* filenames = [oPanel filenames];
635 for ( size_t i = 0 ; i < [filenames count] ; ++ i )
637 wxString fnstr = wxCFStringRef::AsString([filenames objectAtIndex:i]);
638 m_paths.Add( fnstr );
639 m_fileNames.Add( wxFileNameFromPath(fnstr) );
643 m_fileName = wxFileNameFromPath(fnstr);
644 m_dir = wxPathOnly( fnstr );
650 [oPanel setDelegate:nil];
651 [m_delegate release];
655 SetReturnCode(result);
657 if (GetModality() == wxDIALOG_MODALITY_WINDOW_MODAL)
658 SendWindowModalDialogEvent ( wxEVT_WINDOW_MODAL_DIALOG_CLOSED );
661 [(NSSavePanel*) panel setAccessoryView:nil];
664 #endif // wxUSE_FILEDLG