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)
168 bool wxFileDialog::SupportsExtraControl() const
173 NSArray* GetTypesFromExtension( const wxString extensiongroup, wxArrayString& extensions )
175 NSMutableArray* types = nil;
178 wxStringTokenizer tokenizer( extensiongroup, wxT(";") ) ;
179 while ( tokenizer.HasMoreTokens() )
181 wxString extension = tokenizer.GetNextToken() ;
182 // Remove leading '*'
183 if ( extension.length() && (extension.GetChar(0) == '*') )
184 extension = extension.Mid( 1 );
186 // Remove leading '.'
187 if ( extension.length() && (extension.GetChar(0) == '.') )
188 extension = extension.Mid( 1 );
190 // Remove leading '*', this is for handling *.*
191 if ( extension.length() && (extension.GetChar(0) == '*') )
192 extension = extension.Mid( 1 );
194 if ( extension.IsEmpty() )
203 types = [[NSMutableArray alloc] init];
205 extensions.Add(extension.Lower());
206 wxCFStringRef cfext(extension);
207 [types addObject: (NSString*)cfext.AsNSString() ];
209 // add support for classic fileType / creator here
210 wxUint32 fileType, creator;
211 // extension -> mactypes
218 NSArray* GetTypesFromFilter( const wxString& filter, wxArrayString& names, wxArrayString& extensiongroups )
220 NSMutableArray* types = nil;
221 bool allowAll = false;
224 extensiongroups.Clear();
226 if ( !filter.empty() )
228 wxStringTokenizer tokenizer( filter, wxT("|") );
229 int numtokens = (int)tokenizer.CountTokens();
232 // we allow for compatibility reason to have a single filter expression (like *.*) without
233 // an explanatory text, in that case the first part is name and extension at the same time
234 wxString extension = tokenizer.GetNextToken();
235 names.Add( extension );
236 extensiongroups.Add( extension );
240 int numextensions = numtokens / 2;
241 for(int i = 0; i < numextensions; i++)
243 wxString name = tokenizer.GetNextToken();
244 wxString extension = tokenizer.GetNextToken();
246 extensiongroups.Add( extension );
250 const size_t extCount = extensiongroups.GetCount();
251 wxArrayString extensions;
252 for ( size_t i = 0 ; i < extCount; i++ )
254 NSArray* exttypes = GetTypesFromExtension(extensiongroups[i], extensions);
255 if ( exttypes != nil )
257 if ( allowAll == false )
260 types = [[NSMutableArray alloc] init];
262 [types addObjectsFromArray:exttypes];
277 void wxFileDialog::ShowWindowModal()
279 wxCFStringRef cf( m_message );
280 wxCFStringRef dir( m_dir );
281 wxCFStringRef file( m_fileName );
283 wxNonOwnedWindow* parentWindow = NULL;
285 m_modality = wxDIALOG_MODALITY_WINDOW_MODAL;
288 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
290 wxASSERT_MSG(parentWindow, "Window modal display requires parent.");
292 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
293 if ( HasFlag(wxFD_SAVE) )
295 NSSavePanel* sPanel = [NSSavePanel savePanel];
297 SetupExtraControls(sPanel);
299 // makes things more convenient:
300 [sPanel setCanCreateDirectories:YES];
301 [sPanel setMessage:cf.AsNSString()];
302 // if we should be able to descend into pacakges we must somehow
303 // be able to pass this in
304 [sPanel setTreatsFilePackagesAsDirectories:NO];
305 [sPanel setCanSelectHiddenExtension:YES];
306 [sPanel setAllowedFileTypes:types];
307 [sPanel setAllowsOtherFileTypes:NO];
309 NSWindow* nativeParent = parentWindow->GetWXWindow();
310 ModalDialogDelegate* sheetDelegate = [[ModalDialogDelegate alloc] init];
311 [sheetDelegate setImplementation: this];
312 [sPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
313 modalForWindow: nativeParent modalDelegate: sheetDelegate
314 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
319 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
321 SetupExtraControls(oPanel);
323 [oPanel setTreatsFilePackagesAsDirectories:NO];
324 [oPanel setCanChooseDirectories:NO];
325 [oPanel setResolvesAliases:YES];
326 [oPanel setCanChooseFiles:YES];
327 [oPanel setMessage:cf.AsNSString()];
328 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
330 NSWindow* nativeParent = parentWindow->GetWXWindow();
331 ModalDialogDelegate* sheetDelegate = [[ModalDialogDelegate alloc] init];
332 [sheetDelegate setImplementation: this];
333 [oPanel beginSheetForDirectory:dir.AsNSString() file:file.AsNSString()
334 types: types modalForWindow: nativeParent
335 modalDelegate: sheetDelegate
336 didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:)
341 // Create a panel with the file type drop down list
342 // If extra controls need to be added (see wxFileDialog::SetExtraControlCreator), add
343 // them to the panel as well
344 // Returns the newly created wxPanel
346 wxWindow* wxFileDialog::CreateFilterPanel(wxWindow *extracontrol)
348 wxPanel *extrapanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize);
349 wxBoxSizer *verticalSizer = new wxBoxSizer(wxVERTICAL);
350 extrapanel->SetSizer(verticalSizer);
352 // the file type control
354 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
355 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
356 wxStaticText *stattext = new wxStaticText( extrapanel, wxID_ANY, _("File type:") );
357 horizontalSizer->Add(stattext, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
358 m_filterChoice = new wxChoice(extrapanel, wxID_ANY);
359 horizontalSizer->Add(m_filterChoice, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
360 m_filterChoice->Append(m_filterNames);
361 if( m_filterNames.GetCount() > 0)
363 if ( m_firstFileTypeFilter >= 0 )
364 m_filterChoice->SetSelection(m_firstFileTypeFilter);
366 m_filterChoice->Connect(wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(wxFileDialog::OnFilterSelected), NULL, this);
371 wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
372 verticalSizer->Add(horizontalSizer, 0, wxEXPAND, 0);
374 extracontrol->Reparent(extrapanel);
375 horizontalSizer->Add(extracontrol);
378 verticalSizer->Layout();
379 verticalSizer->SetSizeHints(extrapanel);
383 // An item has been selected in the file filter wxChoice:
384 void wxFileDialog::OnFilterSelected( wxCommandEvent &WXUNUSED(event) )
386 int index = m_filterChoice->GetSelection();
388 NSArray* types = GetTypesFromExtension(m_filterExtensions[index],m_currentExtensions);
389 NSSavePanel* panel = (NSSavePanel*) GetWXWindow();
391 [panel validateVisibleColumns];
393 [panel setAllowedFileTypes:types];
396 bool wxFileDialog::CheckFile( const wxString& filename )
398 if ( m_currentExtensions.GetCount() == 0 )
401 wxString ext = filename.AfterLast('.').Lower();
403 for ( size_t i = 0; i < m_currentExtensions.GetCount(); ++i )
405 if ( ext == m_currentExtensions[i] )
411 void wxFileDialog::SetupExtraControls(WXWindow nativeWindow)
413 NSSavePanel* panel = (NSSavePanel*) nativeWindow;
415 wxNonOwnedWindow::Create( GetParent(), nativeWindow );
416 wxWindow* extracontrol = NULL;
417 if ( HasExtraControlCreator() )
419 CreateExtraControl();
420 extracontrol = GetExtraControl();
423 NSView* accView = nil;
426 if ( m_useFileTypeFilter )
428 m_filterPanel = CreateFilterPanel(extracontrol);
429 accView = m_filterPanel->GetHandle();
430 if( HasFlag(wxFD_OPEN) )
432 if ( 1 /* UMAGetSystemVersion() < 0x1060 */ )
434 wxOpenPanelDelegate* del = [[wxOpenPanelDelegate alloc]init];
435 [del setFileDialog:this];
436 [panel setDelegate:del];
443 m_filterPanel = NULL;
444 m_filterChoice = NULL;
445 if ( extracontrol != nil )
446 accView = extracontrol->GetHandle();
449 if ( accView != nil )
451 [accView removeFromSuperview];
452 [panel setAccessoryView:accView];
456 [panel setAccessoryView:nil];
460 int wxFileDialog::ShowModal()
462 wxCFStringRef cf( m_message );
464 wxCFStringRef dir( m_dir );
465 wxCFStringRef file( m_fileName );
467 m_path = wxEmptyString;
470 // since we don't support retrieving the matching filter
473 wxNonOwnedWindow* parentWindow = NULL;
478 parentWindow = dynamic_cast<wxNonOwnedWindow*>(wxGetTopLevelParent(GetParent()));
482 NSArray* types = GetTypesFromFilter( m_wildCard, m_filterNames, m_filterExtensions ) ;
484 m_useFileTypeFilter = m_filterExtensions.GetCount() > 1;
486 if( HasFlag(wxFD_OPEN) )
488 if ( !(wxSystemOptions::HasOption( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) && (wxSystemOptions::GetOptionInt( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES ) == 1)) )
489 m_useFileTypeFilter = false;
492 m_firstFileTypeFilter = -1;
494 if ( m_useFileTypeFilter )
497 bool useDefault = true;
498 for ( size_t i = 0; i < m_filterExtensions.GetCount(); ++i )
500 types = GetTypesFromExtension(m_filterExtensions[i], m_currentExtensions);
501 if ( m_currentExtensions.GetCount() == 0 )
504 m_firstFileTypeFilter = i;
508 for ( size_t j = 0; j < m_currentExtensions.GetCount(); ++j )
510 if ( m_fileName.EndsWith(m_currentExtensions[j]) )
512 m_firstFileTypeFilter = i;
522 types = GetTypesFromExtension(m_filterExtensions[0], m_currentExtensions);
523 m_firstFileTypeFilter = 0;
527 if ( HasFlag(wxFD_SAVE) )
529 NSSavePanel* sPanel = [NSSavePanel savePanel];
531 SetupExtraControls(sPanel);
533 // makes things more convenient:
534 [sPanel setCanCreateDirectories:YES];
535 [sPanel setMessage:cf.AsNSString()];
536 // if we should be able to descend into pacakges we must somehow
537 // be able to pass this in
538 [sPanel setTreatsFilePackagesAsDirectories:NO];
539 [sPanel setCanSelectHiddenExtension:YES];
540 [sPanel setAllowedFileTypes:types];
541 [sPanel setAllowsOtherFileTypes:NO];
543 if ( HasFlag(wxFD_OVERWRITE_PROMPT) )
547 returnCode = [sPanel runModalForDirectory:dir.AsNSString() file:file.AsNSString() ];
548 ModalFinishedCallback(sPanel, returnCode);
552 NSOpenPanel* oPanel = [NSOpenPanel openPanel];
554 SetupExtraControls(oPanel);
556 [oPanel setTreatsFilePackagesAsDirectories:NO];
557 [oPanel setCanChooseDirectories:NO];
558 [oPanel setResolvesAliases:YES];
559 [oPanel setCanChooseFiles:YES];
560 [oPanel setMessage:cf.AsNSString()];
561 [oPanel setAllowsMultipleSelection: (HasFlag(wxFD_MULTIPLE) ? YES : NO )];
563 if ( UMAGetSystemVersion() < 0x1060 )
565 returnCode = [oPanel runModalForDirectory:dir.AsNSString()
566 file:file.AsNSString() types:(m_delegate == nil ? types : nil)];
570 [oPanel setAllowedFileTypes: (m_delegate == nil ? types : nil)];
571 [oPanel setDirectoryURL:[NSURL fileURLWithPath:dir.AsNSString()
573 returnCode = [oPanel runModal];
576 ModalFinishedCallback(oPanel, returnCode);
579 return GetReturnCode();
582 void wxFileDialog::ModalFinishedCallback(void* panel, int returnCode)
584 int result = wxID_CANCEL;
585 if (HasFlag(wxFD_SAVE))
587 if (returnCode == NSOKButton )
589 NSSavePanel* sPanel = (NSSavePanel*)panel;
592 m_path = wxCFStringRef::AsString([sPanel filename]);
593 m_fileName = wxFileNameFromPath(m_path);
594 m_dir = wxPathOnly( m_path );
599 NSOpenPanel* oPanel = (NSOpenPanel*)panel;
600 if (returnCode == NSOKButton )
604 NSArray* filenames = [oPanel filenames];
605 for ( size_t i = 0 ; i < [filenames count] ; ++ i )
607 wxString fnstr = wxCFStringRef::AsString([filenames objectAtIndex:i]);
608 m_paths.Add( fnstr );
609 m_fileNames.Add( wxFileNameFromPath(fnstr) );
613 m_fileName = wxFileNameFromPath(fnstr);
614 m_dir = wxPathOnly( fnstr );
620 [oPanel setDelegate:nil];
621 [m_delegate release];
625 SetReturnCode(result);
627 if (GetModality() == wxDIALOG_MODALITY_WINDOW_MODAL)
628 SendWindowModalDialogEvent ( wxEVT_WINDOW_MODAL_DIALOG_CLOSED );
631 [(NSSavePanel*) panel setAccessoryView:nil];
634 #endif // wxUSE_FILEDLG