execute_select_file_win.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ui/shell_dialogs/execute_select_file_win.h"
  5. #include <shlobj.h>
  6. #include <wrl/client.h>
  7. #include "base/callback.h"
  8. #include "base/files/file.h"
  9. #include "base/files/file_util.h"
  10. #include "base/strings/string_util.h"
  11. #include "base/win/com_init_util.h"
  12. #include "base/win/registry.h"
  13. #include "base/win/scoped_co_mem.h"
  14. #include "base/win/shortcut.h"
  15. #include "ui/base/l10n/l10n_util.h"
  16. #include "ui/shell_dialogs/base_shell_dialog_win.h"
  17. #include "ui/shell_dialogs/select_file_utils_win.h"
  18. #include "ui/strings/grit/ui_strings.h"
  19. namespace ui {
  20. namespace {
  21. // Distinguish directories from regular files.
  22. bool IsDirectory(const base::FilePath& path) {
  23. base::File::Info file_info;
  24. return base::GetFileInfo(path, &file_info) ? file_info.is_directory
  25. : path.EndsWithSeparator();
  26. }
  27. // Sets which path is going to be open when the dialog will be shown. If
  28. // |default_path| is not only a directory, also sets the contents of the text
  29. // box equals to the basename of the path.
  30. bool SetDefaultPath(IFileDialog* file_dialog,
  31. const base::FilePath& default_path) {
  32. if (default_path.empty())
  33. return true;
  34. base::FilePath default_folder;
  35. base::FilePath default_file_name;
  36. if (IsDirectory(default_path)) {
  37. default_folder = default_path;
  38. } else {
  39. default_folder = default_path.DirName();
  40. std::wstring sanitized = RemoveEnvVarFromFileName<wchar_t>(
  41. default_path.BaseName().value(), std::wstring(L"%"));
  42. default_file_name = base::FilePath(sanitized);
  43. }
  44. // Do not fail the file dialog operation if the specified folder is invalid.
  45. Microsoft::WRL::ComPtr<IShellItem> default_folder_shell_item;
  46. if (SUCCEEDED(SHCreateItemFromParsingName(
  47. default_folder.value().c_str(), nullptr,
  48. IID_PPV_ARGS(&default_folder_shell_item)))) {
  49. if (FAILED(file_dialog->SetFolder(default_folder_shell_item.Get())))
  50. return false;
  51. }
  52. return SUCCEEDED(file_dialog->SetFileName(default_file_name.value().c_str()));
  53. }
  54. // Sets the file extension filters on the dialog.
  55. bool SetFilters(IFileDialog* file_dialog,
  56. const std::vector<FileFilterSpec>& filter,
  57. int filter_index) {
  58. if (filter.empty())
  59. return true;
  60. // A COMDLG_FILTERSPEC instance does not own any memory. |filter| must still
  61. // be alive at the time the dialog is shown.
  62. std::vector<COMDLG_FILTERSPEC> comdlg_filterspec(filter.size());
  63. for (size_t i = 0; i < filter.size(); ++i) {
  64. comdlg_filterspec[i].pszName = base::as_wcstr(filter[i].description);
  65. comdlg_filterspec[i].pszSpec = base::as_wcstr(filter[i].extension_spec);
  66. }
  67. return SUCCEEDED(file_dialog->SetFileTypes(comdlg_filterspec.size(),
  68. comdlg_filterspec.data())) &&
  69. SUCCEEDED(file_dialog->SetFileTypeIndex(filter_index));
  70. }
  71. // Sets the requested |dialog_options|, making sure to keep the default values
  72. // when not overwritten.
  73. bool SetOptions(IFileDialog* file_dialog, DWORD dialog_options) {
  74. // First retrieve the default options for a file dialog.
  75. DWORD options;
  76. if (FAILED(file_dialog->GetOptions(&options)))
  77. return false;
  78. options |= dialog_options;
  79. return SUCCEEDED(file_dialog->SetOptions(options));
  80. }
  81. // Configures a |file_dialog| object given the specified parameters.
  82. bool ConfigureDialog(IFileDialog* file_dialog,
  83. const std::u16string& title,
  84. const std::u16string& ok_button_label,
  85. const base::FilePath& default_path,
  86. const std::vector<FileFilterSpec>& filter,
  87. int filter_index,
  88. DWORD dialog_options) {
  89. // Set title.
  90. if (!title.empty()) {
  91. if (FAILED(file_dialog->SetTitle(base::as_wcstr(title))))
  92. return false;
  93. }
  94. if (!ok_button_label.empty()) {
  95. if (FAILED(file_dialog->SetOkButtonLabel(base::as_wcstr(ok_button_label))))
  96. return false;
  97. }
  98. return SetDefaultPath(file_dialog, default_path) &&
  99. SetOptions(file_dialog, dialog_options) &&
  100. SetFilters(file_dialog, filter, filter_index);
  101. }
  102. // Prompt the user for location to save a file.
  103. // Callers should provide the filter string, and also a filter index.
  104. // The parameter |index| indicates the initial index of filter description and
  105. // filter pattern for the dialog box. If |index| is zero or greater than the
  106. // number of total filter types, the system uses the first filter in the
  107. // |filter| buffer. |index| is used to specify the initial selected extension,
  108. // and when done contains the extension the user chose. The parameter |path|
  109. // returns the file name which contains the drive designator, path, file name,
  110. // and extension of the user selected file name. |def_ext| is the default
  111. // extension to give to the file if the user did not enter an extension.
  112. bool RunSaveFileDialog(HWND owner,
  113. const std::u16string& title,
  114. const base::FilePath& default_path,
  115. const std::vector<FileFilterSpec>& filter,
  116. DWORD dialog_options,
  117. const std::wstring& def_ext,
  118. int* filter_index,
  119. base::FilePath* path) {
  120. Microsoft::WRL::ComPtr<IFileSaveDialog> file_save_dialog;
  121. if (FAILED(::CoCreateInstance(CLSID_FileSaveDialog, nullptr,
  122. CLSCTX_INPROC_SERVER,
  123. IID_PPV_ARGS(&file_save_dialog)))) {
  124. return false;
  125. }
  126. if (!ConfigureDialog(file_save_dialog.Get(), title, std::u16string(),
  127. default_path, filter, *filter_index, dialog_options)) {
  128. return false;
  129. }
  130. file_save_dialog->SetDefaultExtension(def_ext.c_str());
  131. HRESULT hr = file_save_dialog->Show(owner);
  132. BaseShellDialogImpl::DisableOwner(owner);
  133. if (FAILED(hr))
  134. return false;
  135. UINT file_type_index;
  136. if (FAILED(file_save_dialog->GetFileTypeIndex(&file_type_index)))
  137. return false;
  138. *filter_index = static_cast<int>(file_type_index);
  139. Microsoft::WRL::ComPtr<IShellItem> result;
  140. if (FAILED(file_save_dialog->GetResult(&result)))
  141. return false;
  142. base::win::ScopedCoMem<wchar_t> display_name;
  143. if (FAILED(result->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING,
  144. &display_name))) {
  145. return false;
  146. }
  147. *path = base::FilePath(display_name.get());
  148. return true;
  149. }
  150. // Runs an Open file dialog box, with similar semantics for input parameters as
  151. // RunSaveFileDialog.
  152. bool RunOpenFileDialog(HWND owner,
  153. const std::u16string& title,
  154. const std::u16string& ok_button_label,
  155. const base::FilePath& default_path,
  156. const std::vector<FileFilterSpec>& filter,
  157. DWORD dialog_options,
  158. int* filter_index,
  159. std::vector<base::FilePath>* paths) {
  160. Microsoft::WRL::ComPtr<IFileOpenDialog> file_open_dialog;
  161. if (FAILED(::CoCreateInstance(CLSID_FileOpenDialog, nullptr,
  162. CLSCTX_INPROC_SERVER,
  163. IID_PPV_ARGS(&file_open_dialog)))) {
  164. return false;
  165. }
  166. // The FOS_FORCEFILESYSTEM option ensures that if the user enters a URL in the
  167. // "File name" box, it will be downloaded locally and its new file path will
  168. // be returned by the dialog. This was a default option in the deprecated
  169. // GetOpenFileName API.
  170. dialog_options |= FOS_FORCEFILESYSTEM;
  171. if (!ConfigureDialog(file_open_dialog.Get(), title, ok_button_label,
  172. default_path, filter, *filter_index, dialog_options)) {
  173. return false;
  174. }
  175. HRESULT hr = file_open_dialog->Show(owner);
  176. BaseShellDialogImpl::DisableOwner(owner);
  177. if (FAILED(hr))
  178. return false;
  179. UINT file_type_index;
  180. if (FAILED(file_open_dialog->GetFileTypeIndex(&file_type_index)))
  181. return false;
  182. *filter_index = static_cast<int>(file_type_index);
  183. Microsoft::WRL::ComPtr<IShellItemArray> selected_items;
  184. if (FAILED(file_open_dialog->GetResults(&selected_items)))
  185. return false;
  186. DWORD result_count;
  187. if (FAILED(selected_items->GetCount(&result_count)))
  188. return false;
  189. DCHECK(result_count == 1 || (dialog_options & FOS_ALLOWMULTISELECT));
  190. std::vector<base::FilePath> result(result_count);
  191. for (DWORD i = 0; i < result_count; ++i) {
  192. Microsoft::WRL::ComPtr<IShellItem> shell_item;
  193. if (FAILED(selected_items->GetItemAt(i, &shell_item)))
  194. return false;
  195. base::win::ScopedCoMem<wchar_t> display_name;
  196. if (FAILED(shell_item->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING,
  197. &display_name))) {
  198. return false;
  199. }
  200. result[i] = base::FilePath(display_name.get());
  201. }
  202. // Only modify the out parameter if the enumeration didn't fail.
  203. *paths = std::move(result);
  204. return !paths->empty();
  205. }
  206. // Runs a Folder selection dialog box, passes back the selected folder in |path|
  207. // and returns true if the user clicks OK. If the user cancels the dialog box
  208. // the value in |path| is not modified and returns false. Run on the dialog
  209. // thread.
  210. bool ExecuteSelectFolder(HWND owner,
  211. SelectFileDialog::Type type,
  212. const std::u16string& title,
  213. const base::FilePath& default_path,
  214. std::vector<base::FilePath>* paths) {
  215. DCHECK(paths);
  216. std::u16string new_title = title;
  217. if (new_title.empty() && type == SelectFileDialog::SELECT_UPLOAD_FOLDER) {
  218. // If it's for uploading don't use default dialog title to
  219. // make sure we clearly tell it's for uploading.
  220. new_title =
  221. l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE);
  222. }
  223. std::u16string ok_button_label;
  224. if (type == SelectFileDialog::SELECT_UPLOAD_FOLDER) {
  225. ok_button_label = l10n_util::GetStringUTF16(
  226. IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON);
  227. }
  228. DWORD dialog_options = FOS_PICKFOLDERS;
  229. std::vector<FileFilterSpec> no_filter;
  230. int filter_index = 0;
  231. return RunOpenFileDialog(owner, new_title, ok_button_label, default_path,
  232. no_filter, dialog_options, &filter_index, paths);
  233. }
  234. bool ExecuteSelectSingleFile(HWND owner,
  235. const std::u16string& title,
  236. const base::FilePath& default_path,
  237. const std::vector<FileFilterSpec>& filter,
  238. int* filter_index,
  239. std::vector<base::FilePath>* paths) {
  240. // Note: The title is not passed down for historical reasons.
  241. // TODO(pmonette): Figure out if it's a worthwhile improvement.
  242. return RunOpenFileDialog(owner, std::u16string(), std::u16string(),
  243. default_path, filter, 0, filter_index, paths);
  244. }
  245. bool ExecuteSelectMultipleFile(HWND owner,
  246. const std::u16string& title,
  247. const base::FilePath& default_path,
  248. const std::vector<FileFilterSpec>& filter,
  249. int* filter_index,
  250. std::vector<base::FilePath>* paths) {
  251. DWORD dialog_options = FOS_ALLOWMULTISELECT;
  252. // Note: The title is not passed down for historical reasons.
  253. // TODO(pmonette): Figure out if it's a worthwhile improvement.
  254. return RunOpenFileDialog(owner, std::u16string(), std::u16string(),
  255. default_path, filter, dialog_options, filter_index,
  256. paths);
  257. }
  258. bool ExecuteSaveFile(HWND owner,
  259. const base::FilePath& default_path,
  260. const std::vector<FileFilterSpec>& filter,
  261. const std::wstring& def_ext,
  262. int* filter_index,
  263. base::FilePath* path) {
  264. DCHECK(path);
  265. // Having an empty filter for a bad user experience. We should always
  266. // specify a filter when saving.
  267. DCHECK(!filter.empty());
  268. DWORD dialog_options = FOS_OVERWRITEPROMPT;
  269. // Note: The title is not passed down for historical reasons.
  270. // TODO(pmonette): Figure out if it's a worthwhile improvement.
  271. return RunSaveFileDialog(owner, std::u16string(), default_path, filter,
  272. dialog_options, def_ext, filter_index, path);
  273. }
  274. } // namespace
  275. void ExecuteSelectFile(
  276. SelectFileDialog::Type type,
  277. const std::u16string& title,
  278. const base::FilePath& default_path,
  279. const std::vector<FileFilterSpec>& filter,
  280. int file_type_index,
  281. const std::wstring& default_extension,
  282. HWND owner,
  283. OnSelectFileExecutedCallback on_select_file_executed_callback) {
  284. base::win::AssertComInitialized();
  285. std::vector<base::FilePath> paths;
  286. switch (type) {
  287. case SelectFileDialog::SELECT_FOLDER:
  288. case SelectFileDialog::SELECT_UPLOAD_FOLDER:
  289. case SelectFileDialog::SELECT_EXISTING_FOLDER:
  290. ExecuteSelectFolder(owner, type, title, default_path, &paths);
  291. break;
  292. case SelectFileDialog::SELECT_SAVEAS_FILE: {
  293. base::FilePath path;
  294. if (ExecuteSaveFile(owner, default_path, filter, default_extension,
  295. &file_type_index, &path)) {
  296. paths.push_back(std::move(path));
  297. }
  298. break;
  299. }
  300. case SelectFileDialog::SELECT_OPEN_FILE:
  301. ExecuteSelectSingleFile(owner, title, default_path, filter,
  302. &file_type_index, &paths);
  303. break;
  304. case SelectFileDialog::SELECT_OPEN_MULTI_FILE:
  305. ExecuteSelectMultipleFile(owner, title, default_path, filter,
  306. &file_type_index, &paths);
  307. break;
  308. case SelectFileDialog::SELECT_NONE:
  309. NOTREACHED();
  310. }
  311. std::move(on_select_file_executed_callback).Run(paths, file_type_index);
  312. }
  313. } // namespace ui