]> git.mxchange.org Git - flightgear.git/blob - src/GUI/CocoaFileDialog.mm
Initial work on native file dialog support.
[flightgear.git] / src / GUI / CocoaFileDialog.mm
1
2
3 #include "CocoaFileDialog.hxx"
4
5 // bring it all in!
6 #include <Cocoa/Cocoa.h>
7
8 #include <boost/foreach.hpp>
9
10 #include <simgear/debug/logstream.hxx>
11 #include <simgear/misc/strutils.hxx>
12
13 #include <Main/globals.hxx>
14 #include <Main/fg_props.hxx>
15
16 static NSString* stdStringToCocoa(const std::string& s)
17 {
18     return [NSString stringWithUTF8String:s.c_str()];
19 }
20
21 static NSURL* pathToNSURL(const SGPath& aPath)
22 {
23     return [NSURL fileURLWithPath:stdStringToCocoa(aPath.str())];
24 }
25
26 class CocoaFileDialog::CocoaFileDialogPrivate
27 {
28 public:
29     CocoaFileDialogPrivate() :
30         panel(nil)
31     {
32         
33     }
34     
35     ~CocoaFileDialogPrivate()
36     {
37         [panel release];
38     }
39     
40     NSSavePanel* panel;
41 };
42
43 CocoaFileDialog::CocoaFileDialog(const std::string& aTitle, FGFileDialog::Usage use) :
44     FGFileDialog(aTitle, use)
45 {
46     d.reset(new CocoaFileDialogPrivate);
47     if (use == USE_SAVE_FILE) {
48         d->panel = [NSSavePanel savePanel];
49     } else {
50         d->panel = [NSOpenPanel openPanel];
51     }
52     
53     if (use == USE_CHOOSE_DIR) {
54         [d->panel setCanChooseDirectories:YES];
55     }
56 }
57
58 CocoaFileDialog::~CocoaFileDialog()
59 {
60     
61 }
62
63 void CocoaFileDialog::exec()
64 {
65     if (_usage == USE_SAVE_FILE) {
66         [d->panel setNameFieldStringValue:stdStringToCocoa(_placeholder)];
67     }
68     
69     NSMutableArray* extensions = [NSMutableArray arrayWithCapacity:0];
70     BOOST_FOREACH(std::string ext, _filterPatterns) {
71         if (!simgear::strutils::starts_with(ext, "*.")) {
72             SG_LOG(SG_GENERAL, SG_INFO, "can't use pattern on Cococa:" << ext);
73             continue;
74         }
75         [extensions addObject:stdStringToCocoa(ext.substr(2))];
76     }
77
78     [d->panel setAllowedFileTypes:extensions];
79     [d->panel setTitle:stdStringToCocoa(_title)];
80     if (_showHidden) {
81         [d->panel setShowsHiddenFiles:YES];
82     }
83     
84     [d->panel setDirectoryURL: pathToNSURL(_initialPath)];
85     
86     [d->panel beginWithCompletionHandler:^(NSInteger result)
87     {
88         if (result == NSFileHandlingPanelOKButton) {
89             NSURL*  theDoc = [d->panel URL];
90             NSLog(@"the URL is: %@", theDoc);
91             // Open  the document.
92         }
93         
94     }];
95 }