file_dialog_mac.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/browser/ui/file_dialog.h"
  5. #include <string>
  6. #include <utility>
  7. #include <vector>
  8. #import <Cocoa/Cocoa.h>
  9. #import <CoreServices/CoreServices.h>
  10. #include "base/files/file_util.h"
  11. #include "base/mac/foundation_util.h"
  12. #include "base/mac/mac_util.h"
  13. #include "base/mac/scoped_cftyperef.h"
  14. #include "base/strings/sys_string_conversions.h"
  15. #include "content/public/browser/browser_task_traits.h"
  16. #include "content/public/browser/browser_thread.h"
  17. #include "shell/browser/native_window.h"
  18. #include "shell/common/gin_converters/file_path_converter.h"
  19. #include "shell/common/thread_restrictions.h"
  20. @interface PopUpButtonHandler : NSObject
  21. @property(nonatomic, assign) NSSavePanel* savePanel;
  22. @property(nonatomic, strong) NSArray* fileTypesList;
  23. - (instancetype)initWithPanel:(NSSavePanel*)panel
  24. andTypesList:(NSArray*)typesList;
  25. - (void)selectFormat:(id)sender;
  26. @end
  27. @implementation PopUpButtonHandler
  28. @synthesize savePanel;
  29. @synthesize fileTypesList;
  30. - (instancetype)initWithPanel:(NSSavePanel*)panel
  31. andTypesList:(NSArray*)typesList {
  32. self = [super init];
  33. if (self) {
  34. [self setSavePanel:panel];
  35. [self setFileTypesList:typesList];
  36. }
  37. return self;
  38. }
  39. - (void)selectFormat:(id)sender {
  40. NSPopUpButton* button = (NSPopUpButton*)sender;
  41. NSInteger selectedItemIndex = [button indexOfSelectedItem];
  42. NSArray* list = [self fileTypesList];
  43. NSArray* fileTypes = [list objectAtIndex:selectedItemIndex];
  44. // If we meet a '*' file extension, we allow all the file types and no
  45. // need to set the specified file types.
  46. if ([fileTypes count] == 0 || [fileTypes containsObject:@"*"])
  47. [[self savePanel] setAllowedFileTypes:nil];
  48. else
  49. [[self savePanel] setAllowedFileTypes:fileTypes];
  50. }
  51. @end
  52. // Manages the PopUpButtonHandler.
  53. @interface ElectronAccessoryView : NSView
  54. @end
  55. @implementation ElectronAccessoryView
  56. - (void)dealloc {
  57. auto* popupButton =
  58. static_cast<NSPopUpButton*>([[self subviews] objectAtIndex:1]);
  59. [[popupButton target] release];
  60. [super dealloc];
  61. }
  62. @end
  63. namespace file_dialog {
  64. DialogSettings::DialogSettings() = default;
  65. DialogSettings::DialogSettings(const DialogSettings&) = default;
  66. DialogSettings::~DialogSettings() = default;
  67. namespace {
  68. void SetAllowedFileTypes(NSSavePanel* dialog, const Filters& filters) {
  69. NSMutableArray* file_types_list = [NSMutableArray array];
  70. NSMutableArray* filter_names = [NSMutableArray array];
  71. // Create array to keep file types and their name.
  72. for (const Filter& filter : filters) {
  73. NSMutableOrderedSet* file_type_set =
  74. [NSMutableOrderedSet orderedSetWithCapacity:filters.size()];
  75. [filter_names addObject:@(filter.first.c_str())];
  76. for (std::string ext : filter.second) {
  77. // macOS is incapable of understanding multiple file extensions,
  78. // so we need to tokenize the extension that's been passed in.
  79. // We want to err on the side of allowing files, so we pass
  80. // along only the final extension ('tar.gz' => 'gz').
  81. auto pos = ext.rfind('.');
  82. if (pos != std::string::npos) {
  83. ext.erase(0, pos + 1);
  84. }
  85. [file_type_set addObject:@(ext.c_str())];
  86. }
  87. [file_types_list addObject:[file_type_set array]];
  88. }
  89. // Passing empty array to setAllowedFileTypes will cause exception.
  90. NSArray* file_types = nil;
  91. NSUInteger count = [file_types_list count];
  92. if (count > 0) {
  93. file_types = [[file_types_list objectAtIndex:0] allObjects];
  94. // If we meet a '*' file extension, we allow all the file types and no
  95. // need to set the specified file types.
  96. if ([file_types count] == 0 || [file_types containsObject:@"*"])
  97. file_types = nil;
  98. }
  99. [dialog setAllowedFileTypes:file_types];
  100. if (count <= 1)
  101. return; // don't add file format picker
  102. // Add file format picker.
  103. ElectronAccessoryView* accessoryView = [[ElectronAccessoryView alloc]
  104. initWithFrame:NSMakeRect(0.0, 0.0, 200, 32.0)];
  105. NSTextField* label =
  106. [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)];
  107. [label setEditable:NO];
  108. [label setStringValue:@"Format:"];
  109. [label setBordered:NO];
  110. [label setBezeled:NO];
  111. [label setDrawsBackground:NO];
  112. NSPopUpButton* popupButton =
  113. [[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 140, 22.0)
  114. pullsDown:NO];
  115. PopUpButtonHandler* popUpButtonHandler =
  116. [[PopUpButtonHandler alloc] initWithPanel:dialog
  117. andTypesList:file_types_list];
  118. [popupButton addItemsWithTitles:filter_names];
  119. [popupButton setTarget:popUpButtonHandler];
  120. [popupButton setAction:@selector(selectFormat:)];
  121. [accessoryView addSubview:[label autorelease]];
  122. [accessoryView addSubview:[popupButton autorelease]];
  123. [dialog setAccessoryView:[accessoryView autorelease]];
  124. }
  125. void SetupDialog(NSSavePanel* dialog, const DialogSettings& settings) {
  126. if (!settings.title.empty())
  127. [dialog setTitle:base::SysUTF8ToNSString(settings.title)];
  128. if (!settings.button_label.empty())
  129. [dialog setPrompt:base::SysUTF8ToNSString(settings.button_label)];
  130. if (!settings.message.empty())
  131. [dialog setMessage:base::SysUTF8ToNSString(settings.message)];
  132. if (!settings.name_field_label.empty())
  133. [dialog
  134. setNameFieldLabel:base::SysUTF8ToNSString(settings.name_field_label)];
  135. [dialog setShowsTagField:settings.shows_tag_field];
  136. NSString* default_dir = nil;
  137. NSString* default_filename = nil;
  138. if (!settings.default_path.empty()) {
  139. electron::ScopedAllowBlockingForElectron allow_blocking;
  140. if (base::DirectoryExists(settings.default_path)) {
  141. default_dir = base::SysUTF8ToNSString(settings.default_path.value());
  142. } else {
  143. if (settings.default_path.IsAbsolute()) {
  144. default_dir =
  145. base::SysUTF8ToNSString(settings.default_path.DirName().value());
  146. }
  147. default_filename =
  148. base::SysUTF8ToNSString(settings.default_path.BaseName().value());
  149. }
  150. }
  151. if (settings.filters.empty()) {
  152. [dialog setAllowsOtherFileTypes:YES];
  153. } else {
  154. // Set setAllowedFileTypes before setNameFieldStringValue as it might
  155. // override the extension set using setNameFieldStringValue
  156. SetAllowedFileTypes(dialog, settings.filters);
  157. }
  158. // Make sure the extension is always visible. Without this, the extension in
  159. // the default filename will not be used in the saved file.
  160. [dialog setExtensionHidden:NO];
  161. if (default_dir)
  162. [dialog setDirectoryURL:[NSURL fileURLWithPath:default_dir]];
  163. if (default_filename)
  164. [dialog setNameFieldStringValue:default_filename];
  165. }
  166. void SetupOpenDialogForProperties(NSOpenPanel* dialog, int properties) {
  167. [dialog setCanChooseFiles:(properties & OPEN_DIALOG_OPEN_FILE)];
  168. if (properties & OPEN_DIALOG_OPEN_DIRECTORY)
  169. [dialog setCanChooseDirectories:YES];
  170. if (properties & OPEN_DIALOG_CREATE_DIRECTORY)
  171. [dialog setCanCreateDirectories:YES];
  172. if (properties & OPEN_DIALOG_MULTI_SELECTIONS)
  173. [dialog setAllowsMultipleSelection:YES];
  174. if (properties & OPEN_DIALOG_SHOW_HIDDEN_FILES)
  175. [dialog setShowsHiddenFiles:YES];
  176. if (properties & OPEN_DIALOG_NO_RESOLVE_ALIASES)
  177. [dialog setResolvesAliases:NO];
  178. if (properties & OPEN_DIALOG_TREAT_PACKAGE_APP_AS_DIRECTORY)
  179. [dialog setTreatsFilePackagesAsDirectories:YES];
  180. }
  181. void SetupSaveDialogForProperties(NSSavePanel* dialog, int properties) {
  182. if (properties & SAVE_DIALOG_CREATE_DIRECTORY)
  183. [dialog setCanCreateDirectories:YES];
  184. if (properties & SAVE_DIALOG_SHOW_HIDDEN_FILES)
  185. [dialog setShowsHiddenFiles:YES];
  186. if (properties & SAVE_DIALOG_TREAT_PACKAGE_APP_AS_DIRECTORY)
  187. [dialog setTreatsFilePackagesAsDirectories:YES];
  188. }
  189. // Run modal dialog with parent window and return user's choice.
  190. int RunModalDialog(NSSavePanel* dialog, const DialogSettings& settings) {
  191. __block int chosen = NSModalResponseCancel;
  192. if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
  193. settings.force_detached) {
  194. chosen = [dialog runModal];
  195. } else {
  196. NSWindow* window =
  197. settings.parent_window->GetNativeWindow().GetNativeNSWindow();
  198. [dialog beginSheetModalForWindow:window
  199. completionHandler:^(NSInteger c) {
  200. chosen = c;
  201. [NSApp stopModal];
  202. }];
  203. [NSApp runModalForWindow:window];
  204. }
  205. return chosen;
  206. }
  207. // Create bookmark data and serialise it into a base64 string.
  208. std::string GetBookmarkDataFromNSURL(NSURL* url) {
  209. // Create the file if it doesn't exist (necessary for NSSavePanel options).
  210. NSFileManager* defaultManager = [NSFileManager defaultManager];
  211. if (![defaultManager fileExistsAtPath:[url path]]) {
  212. [defaultManager createFileAtPath:[url path] contents:nil attributes:nil];
  213. }
  214. NSError* error = nil;
  215. NSData* bookmarkData =
  216. [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
  217. includingResourceValuesForKeys:nil
  218. relativeToURL:nil
  219. error:&error];
  220. if (error != nil) {
  221. // Send back an empty string if there was an error.
  222. return "";
  223. } else {
  224. // Encode NSData in base64 then convert to NSString.
  225. NSString* base64data = [[NSString alloc]
  226. initWithData:[bookmarkData base64EncodedDataWithOptions:0]
  227. encoding:NSUTF8StringEncoding];
  228. return base::SysNSStringToUTF8(base64data);
  229. }
  230. }
  231. void ReadDialogPathsWithBookmarks(NSOpenPanel* dialog,
  232. std::vector<base::FilePath>* paths,
  233. std::vector<std::string>* bookmarks) {
  234. NSArray* urls = [dialog URLs];
  235. for (NSURL* url in urls)
  236. if ([url isFileURL]) {
  237. paths->emplace_back(base::SysNSStringToUTF8([url path]));
  238. bookmarks->push_back(GetBookmarkDataFromNSURL(url));
  239. }
  240. }
  241. void ReadDialogPaths(NSOpenPanel* dialog, std::vector<base::FilePath>* paths) {
  242. std::vector<std::string> ignored_bookmarks;
  243. ReadDialogPathsWithBookmarks(dialog, paths, &ignored_bookmarks);
  244. }
  245. void ResolvePromiseInNextTick(gin_helper::Promise<v8::Local<v8::Value>> promise,
  246. v8::Local<v8::Value> value) {
  247. // The completionHandler runs inside a transaction commit, and we should
  248. // not do any runModal inside it. However since we can not control what
  249. // users will run in the microtask, we have to delay the resolution until
  250. // next tick, otherwise crash like this may happen:
  251. // https://github.com/electron/electron/issues/26884
  252. content::GetUIThreadTaskRunner({})->PostTask(
  253. FROM_HERE,
  254. base::BindOnce(
  255. [](gin_helper::Promise<v8::Local<v8::Value>> promise,
  256. v8::Global<v8::Value> global) {
  257. v8::Isolate* isolate = promise.isolate();
  258. v8::HandleScope handle_scope(isolate);
  259. v8::Local<v8::Value> value = global.Get(isolate);
  260. promise.Resolve(value);
  261. },
  262. std::move(promise), v8::Global<v8::Value>(promise.isolate(), value)));
  263. }
  264. } // namespace
  265. bool ShowOpenDialogSync(const DialogSettings& settings,
  266. std::vector<base::FilePath>* paths) {
  267. DCHECK(paths);
  268. NSOpenPanel* dialog = [NSOpenPanel openPanel];
  269. SetupDialog(dialog, settings);
  270. SetupOpenDialogForProperties(dialog, settings.properties);
  271. int chosen = RunModalDialog(dialog, settings);
  272. if (chosen == NSModalResponseCancel)
  273. return false;
  274. ReadDialogPaths(dialog, paths);
  275. return true;
  276. }
  277. void OpenDialogCompletion(int chosen,
  278. NSOpenPanel* dialog,
  279. bool security_scoped_bookmarks,
  280. gin_helper::Promise<gin_helper::Dictionary> promise) {
  281. v8::HandleScope scope(promise.isolate());
  282. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
  283. if (chosen == NSModalResponseCancel) {
  284. dict.Set("canceled", true);
  285. dict.Set("filePaths", std::vector<base::FilePath>());
  286. #if IS_MAS_BUILD()
  287. dict.Set("bookmarks", std::vector<std::string>());
  288. #endif
  289. } else {
  290. std::vector<base::FilePath> paths;
  291. dict.Set("canceled", false);
  292. #if IS_MAS_BUILD()
  293. std::vector<std::string> bookmarks;
  294. if (security_scoped_bookmarks)
  295. ReadDialogPathsWithBookmarks(dialog, &paths, &bookmarks);
  296. else
  297. ReadDialogPaths(dialog, &paths);
  298. dict.Set("filePaths", paths);
  299. dict.Set("bookmarks", bookmarks);
  300. #else
  301. ReadDialogPaths(dialog, &paths);
  302. dict.Set("filePaths", paths);
  303. #endif
  304. }
  305. ResolvePromiseInNextTick(promise.As<v8::Local<v8::Value>>(),
  306. dict.GetHandle());
  307. }
  308. void ShowOpenDialog(const DialogSettings& settings,
  309. gin_helper::Promise<gin_helper::Dictionary> promise) {
  310. NSOpenPanel* dialog = [NSOpenPanel openPanel];
  311. SetupDialog(dialog, settings);
  312. SetupOpenDialogForProperties(dialog, settings.properties);
  313. // Capture the value of the security_scoped_bookmarks settings flag
  314. // and pass it to the completion handler.
  315. bool security_scoped_bookmarks = settings.security_scoped_bookmarks;
  316. __block gin_helper::Promise<gin_helper::Dictionary> p = std::move(promise);
  317. if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
  318. settings.force_detached) {
  319. [dialog beginWithCompletionHandler:^(NSInteger chosen) {
  320. OpenDialogCompletion(chosen, dialog, security_scoped_bookmarks,
  321. std::move(p));
  322. }];
  323. } else {
  324. NSWindow* window =
  325. settings.parent_window->GetNativeWindow().GetNativeNSWindow();
  326. [dialog
  327. beginSheetModalForWindow:window
  328. completionHandler:^(NSInteger chosen) {
  329. OpenDialogCompletion(chosen, dialog, security_scoped_bookmarks,
  330. std::move(p));
  331. }];
  332. }
  333. }
  334. bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) {
  335. DCHECK(path);
  336. NSSavePanel* dialog = [NSSavePanel savePanel];
  337. SetupDialog(dialog, settings);
  338. SetupSaveDialogForProperties(dialog, settings.properties);
  339. int chosen = RunModalDialog(dialog, settings);
  340. if (chosen == NSModalResponseCancel || ![[dialog URL] isFileURL])
  341. return false;
  342. *path = base::FilePath(base::SysNSStringToUTF8([[dialog URL] path]));
  343. return true;
  344. }
  345. void SaveDialogCompletion(int chosen,
  346. NSSavePanel* dialog,
  347. bool security_scoped_bookmarks,
  348. gin_helper::Promise<gin_helper::Dictionary> promise) {
  349. v8::HandleScope scope(promise.isolate());
  350. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
  351. if (chosen == NSModalResponseCancel) {
  352. dict.Set("canceled", true);
  353. dict.Set("filePath", base::FilePath());
  354. #if IS_MAS_BUILD()
  355. dict.Set("bookmark", base::StringPiece());
  356. #endif
  357. } else {
  358. std::string path = base::SysNSStringToUTF8([[dialog URL] path]);
  359. dict.Set("filePath", base::FilePath(path));
  360. dict.Set("canceled", false);
  361. #if IS_MAS_BUILD()
  362. std::string bookmark;
  363. if (security_scoped_bookmarks) {
  364. bookmark = GetBookmarkDataFromNSURL([dialog URL]);
  365. dict.Set("bookmark", bookmark);
  366. }
  367. #endif
  368. }
  369. ResolvePromiseInNextTick(promise.As<v8::Local<v8::Value>>(),
  370. dict.GetHandle());
  371. }
  372. void ShowSaveDialog(const DialogSettings& settings,
  373. gin_helper::Promise<gin_helper::Dictionary> promise) {
  374. NSSavePanel* dialog = [NSSavePanel savePanel];
  375. SetupDialog(dialog, settings);
  376. SetupSaveDialogForProperties(dialog, settings.properties);
  377. [dialog setCanSelectHiddenExtension:YES];
  378. // Capture the value of the security_scoped_bookmarks settings flag
  379. // and pass it to the completion handler.
  380. bool security_scoped_bookmarks = settings.security_scoped_bookmarks;
  381. __block gin_helper::Promise<gin_helper::Dictionary> p = std::move(promise);
  382. if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
  383. settings.force_detached) {
  384. [dialog beginWithCompletionHandler:^(NSInteger chosen) {
  385. SaveDialogCompletion(chosen, dialog, security_scoped_bookmarks,
  386. std::move(p));
  387. }];
  388. } else {
  389. NSWindow* window =
  390. settings.parent_window->GetNativeWindow().GetNativeNSWindow();
  391. [dialog
  392. beginSheetModalForWindow:window
  393. completionHandler:^(NSInteger chosen) {
  394. SaveDialogCompletion(chosen, dialog, security_scoped_bookmarks,
  395. std::move(p));
  396. }];
  397. }
  398. }
  399. } // namespace file_dialog