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)
169 bool wxFileDialog::SupportsExtraControl() const
174 NSArray* GetTypesFromExtension( const wxString extensiongroup, wxArrayString& extensions )
176 NSMutableArray* types = nil;
179 wxStringTokenizer tokenizer( extensiongroup, wxT(";") ) ;
180 while ( tokenizer.HasMoreTokens() )
182 wxString extension = tokenizer.GetNextToken() ;
183 // Remove leading '*'
184 if ( extension.length() && (extension.GetChar(0) == '*') )
185 extension = extension.Mid( 1 );
187 // Remove leading '.'
188 if ( extension.length() && (extension.GetChar(0) == '.') )
189 extension = extension.Mid( 1 );
191 // Remove leading '*', this is for handling *.*
192 if ( extension.length() && (extension.GetChar(0) == '*') )
193 extension = extension.Mid( 1 );
195 if ( extension.IsEmpty() )
204 types = [[NSMutableArray alloc] init];
206 extensions.Add(extension.Lower());
207 wxCFStringRef cfext(extension);
208 [types addObject: (NSString*)cfext.AsNSString() ];
210 // add support for classic fileType / creator here
211 wxUint32 fileType, creator;
212 // extension -> mactypes
219 NSArray* GetTypesFromFilter( const wxString& filter, wxArrayString& names, wxArrayString& extensiongroups )
221 NSMutableArray* types = nil;
222 bool allowAll = false;
225 extensiongroups.Clear();
227 if ( !filter.empty() )
229 wxStringTokenizer tokenizer( filter, wxT("|") );
230 int numtokens = (int)tokenizer.CountTokens();
233 // we allow for compatibility reason to have a single filter expression (like *.*) without
234 // an explanatory text, in that case the first part is name and extension at the same time
235 wxString extension = tokenizer.GetNextToken();
236 names.Add( extension );
237 extensiongroups.Add( extension );
241 int numextensions = numtokens / 2;
242 for(int i = 0; i < numextensions; i++)
244 wxString name = tokenizer.GetNextToken();
245 wxString extension = tokenizer.GetNextToken();
247 extensiongroups.Add( extension );
251 const size_t extCount = extensiongroups.GetCount();
252 wxArrayString extensions;
253 for ( size_t i = 0 ; i < extCount; i++ )
255 NSArray* exttypes = GetTypesFromExtension(extensiongroups[i], extensions);
256 if ( exttypes != nil )
258 if ( allowAll == false )
261 types = [[NSMutableArray alloc] init];
263 [types addObjectsFromArray:exttypes];
278 void wxFileDialog::ShowWindowModal()
280 wxCFStringRef cf( m_message );
281 wxCFStringRef dir( m_dir );
282 wxCFStringRef file( m_fileName );
284 wxNonOwnedWindow* parentWindow = NULL;
286 m_modality = wxDIALOG_MODALITY_WINDOW_MODAL;
289 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
291 wxASSERT_MSG(parentWindow, "Window modal display requires parent.");
293 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
294 if ( HasFlag(wxFD_SAVE) )
296 NSSavePanel* sPanel = [NSSavePanel savePanel];
298 SetupExtraControls(sPanel);
300 // makes things more convenient:
301 [sPanel setCanCreateDirectories:YES];
302 [sPanel setMessage:cf.AsNSString()];
303 // if we should be able to descend into pacakges we must somehow
304 // be able to pass this in
305 [sPanel setTreatsFilePackagesAsDirectories:NO];
306 [sPanel setCanSelectHiddenExtension:YES];
307 [sPanel setAllowedFileTypes:types];
308 [sPanel setAllowsOtherFileTypes:NO];
310 NSWindow* nativeParent = parentWindow->GetWXWindow();
311 ModalDialogDelegate* sheetDelegate = [[ModalDialogDelegate alloc] init];
312 [sheetDelegate setImplementation: this];
313 [sPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
314 modalForWindow: nativeParent modalDelegate: sheetDelegate
315 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
320 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
322 SetupExtraControls(oPanel);
324 [oPanel setTreatsFilePackagesAsDirectories:NO];
325 [oPanel setCanChooseDirectories:NO];
326 [oPanel setResolvesAliases:YES];
327 [oPanel setCanChooseFiles:YES];
328 [oPanel setMessage:cf.AsNSString()];
329 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
331 NSWindow* nativeParent = parentWindow->GetWXWindow();
332 ModalDialogDelegate* sheetDelegate = [[ModalDialogDelegate alloc] init];
333 [sheetDelegate setImplementation: this];
334 [oPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
335 types: types modalForWindow: nativeParent
336 modalDelegate: sheetDelegate
337 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
342 // Create a panel with the file type drop down list
343 // If extra controls need to be added (see wxFileDialog::SetExtraControlCreator), add
344 // them to the panel as well
345 // Returns the newly created wxPanel
347 wxWindow* wxFileDialog::CreateFilterPanel(wxWindow *extracontrol)
349 wxPanel *extrapanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize);
350 wxBoxSizer *verticalSizer = new wxBoxSizer(wxVERTICAL);
351 extrapanel->SetSizer(verticalSizer);
353 // the file type control
355 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
356 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
357 wxStaticText *stattext = new wxStaticText( extrapanel, wxID_ANY, _("File type:") );
358 horizontalSizer->Add(stattext, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
359 m_filterChoice = new wxChoice(extrapanel, wxID_ANY);
360 horizontalSizer->Add(m_filterChoice, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
361 m_filterChoice->Append(m_filterNames);
362 if( m_filterNames.GetCount() > 0)
364 if ( m_firstFileTypeFilter >= 0 )
365 m_filterChoice->SetSelection(m_firstFileTypeFilter);
367 m_filterChoice->Connect(wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(wxFileDialog::OnFilterSelected), NULL, this);
372 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
373 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
375 extracontrol->Reparent(extrapanel);
376 horizontalSizer->Add(extracontrol);
379 verticalSizer->Layout();
380 verticalSizer->SetSizeHints(extrapanel);
384 void wxFileDialog::DoOnFilterSelected(int index)
386 NSArray* types = GetTypesFromExtension(m_filterExtensions[index],m_currentExtensions);
387 NSSavePanel* panel = (NSSavePanel*) GetWXWindow();
389 [panel validateVisibleColumns];
391 [panel setAllowedFileTypes:types];
394 // An item has been selected in the file filter wxChoice:
395 void wxFileDialog::OnFilterSelected( wxCommandEvent &WXUNUSED(event) )
397 DoOnFilterSelected( m_filterChoice->GetSelection() );
400 bool wxFileDialog::CheckFile( const wxString& filename )
402 if ( m_currentExtensions.GetCount() == 0 )
405 wxString ext = filename.AfterLast('.').Lower();
407 for ( size_t i = 0; i < m_currentExtensions.GetCount(); ++i )
409 if ( ext == m_currentExtensions[i] )
415 void wxFileDialog::SetupExtraControls(WXWindow nativeWindow)
417 NSSavePanel* panel = (NSSavePanel*) nativeWindow;
419 wxNonOwnedWindow::Create( GetParent(), nativeWindow );
420 wxWindow* extracontrol = NULL;
421 if ( HasExtraControlCreator() )
423 CreateExtraControl();
424 extracontrol = GetExtraControl();
427 NSView* accView = nil;
430 if ( m_useFileTypeFilter )
432 m_filterPanel = CreateFilterPanel(extracontrol);
433 accView = m_filterPanel->GetHandle();
434 if( HasFlag(wxFD_OPEN) )
436 if ( 1 /* UMAGetSystemVersion() < 0x1060 */ )
438 wxOpenPanelDelegate* del = [[wxOpenPanelDelegate alloc]init];
439 [del setFileDialog:this];
440 [panel setDelegate:del];
447 m_filterPanel = NULL;
448 m_filterChoice = NULL;
449 if ( extracontrol != nil )
450 accView = extracontrol->GetHandle();
453 if ( accView != nil )
455 [accView removeFromSuperview];
456 [panel setAccessoryView:accView];
460 [panel setAccessoryView:nil];
464 int wxFileDialog::ShowModal()
466 wxCFStringRef cf( m_message );
468 wxCFStringRef dir( m_dir );
469 wxCFStringRef file( m_fileName );
471 m_path = wxEmptyString;
475 wxNonOwnedWindow* parentWindow = NULL;
480 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
484 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
486 m_useFileTypeFilter = m_filterExtensions.GetCount() > 1;
488 if( HasFlag(wxFD_OPEN) )
490 if ( !(wxSystemOptions::HasOption( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) && (wxSystemOptions::GetOptionInt( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) == 1)) )
491 m_useFileTypeFilter = false;
494 m_firstFileTypeFilter = -1;
496 if ( m_useFileTypeFilter
497 && m_filterIndex >= 0 && m_filterIndex < m_filterExtensions.GetCount() )
499 m_firstFileTypeFilter = m_filterIndex;
501 else if ( m_useFileTypeFilter )
504 bool useDefault = true;
505 for ( size_t i = 0; i < m_filterExtensions.GetCount(); ++i )
507 types = GetTypesFromExtension(m_filterExtensions[i], m_currentExtensions);
508 if ( m_currentExtensions.GetCount() == 0 )
511 m_firstFileTypeFilter = i;
515 for ( size_t j = 0; j < m_currentExtensions.GetCount(); ++j )
517 if ( m_fileName.EndsWith(m_currentExtensions[j]) )
519 m_firstFileTypeFilter = i;
529 types = GetTypesFromExtension(m_filterExtensions[0], m_currentExtensions);
530 m_firstFileTypeFilter = 0;
534 if ( HasFlag(wxFD_SAVE) )
536 NSSavePanel* sPanel = [NSSavePanel savePanel];
538 SetupExtraControls(sPanel);
540 // makes things more convenient:
541 [sPanel setCanCreateDirectories:YES];
542 [sPanel setMessage:cf.AsNSString()];
543 // if we should be able to descend into pacakges we must somehow
544 // be able to pass this in
545 [sPanel setTreatsFilePackagesAsDirectories:NO];
546 [sPanel setCanSelectHiddenExtension:YES];
547 [sPanel setAllowedFileTypes:types];
548 [sPanel setAllowsOtherFileTypes:NO];
550 if ( HasFlag(wxFD_OVERWRITE_PROMPT) )
555 Let the file dialog know what file type should be used initially.
556 If this is not done then when setting the filter index
557 programmatically to 1 the file will still have the extension
558 of the first file type instead of the second one. E.g. when file
559 types are foo and bar, a filename "myletter" with SetDialogIndex(1)
560 would result in saving as myletter.foo, while we want myletter.bar.
562 if(m_firstFileTypeFilter > 0)
564 DoOnFilterSelected(m_firstFileTypeFilter);
567 returnCode = [sPanel runModalForDirectory:dir.AsNSString() file:file.AsNSString() ];
568 ModalFinishedCallback(sPanel, returnCode);
572 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
574 SetupExtraControls(oPanel);
576 [oPanel setTreatsFilePackagesAsDirectories:NO];
577 [oPanel setCanChooseDirectories:NO];
578 [oPanel setResolvesAliases:YES];
579 [oPanel setCanChooseFiles:YES];
580 [oPanel setMessage:cf.AsNSString()];
581 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
583 if ( UMAGetSystemVersion() < 0x1060 )
585 returnCode = [oPanel runModalForDirectory:dir.AsNSString()
586 file:file.AsNSString() types:(m_delegate == nil ? types : nil)];
590 [oPanel setAllowedFileTypes: (m_delegate == nil ? types : nil)];
591 [oPanel setDirectoryURL:[NSURL fileURLWithPath:dir.AsNSString()
593 returnCode = [oPanel runModal];
596 ModalFinishedCallback(oPanel, returnCode);
599 return GetReturnCode();
602 void wxFileDialog::ModalFinishedCallback(void* panel, int returnCode)
604 int result = wxID_CANCEL;
605 if (HasFlag(wxFD_SAVE))
607 if (returnCode == NSOKButton )
609 NSSavePanel* sPanel = (NSSavePanel*)panel;
612 m_path = wxCFStringRef::AsString([sPanel filename]);
613 m_fileName = wxFileNameFromPath(m_path);
614 m_dir = wxPathOnly( m_path );
617 m_filterIndex = m_filterChoice->GetSelection();
623 NSOpenPanel* oPanel = (NSOpenPanel*)panel;
624 if (returnCode == NSOKButton )
628 NSArray* filenames = [oPanel filenames];
629 for ( size_t i = 0 ; i < [filenames count] ; ++ i )
631 wxString fnstr = wxCFStringRef::AsString([filenames objectAtIndex:i]);
632 m_paths.Add( fnstr );
633 m_fileNames.Add( wxFileNameFromPath(fnstr) );
637 m_fileName = wxFileNameFromPath(fnstr);
638 m_dir = wxPathOnly( fnstr );
644 [oPanel setDelegate:nil];
645 [m_delegate release];
649 SetReturnCode(result);
651 if (GetModality() == wxDIALOG_MODALITY_WINDOW_MODAL)
652 SendWindowModalDialogEvent ( wxEVT_WINDOW_MODAL_DIALOG_CLOSED );
655 [(NSSavePanel*) panel setAccessoryView:nil];
658 #endif // wxUSE_FILEDLG