file_dialog_win.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 "atom/browser/ui/file_dialog.h"
  5. #include <windows.h> // windows.h must be included first
  6. #include <atlbase.h>
  7. #include <commdlg.h>
  8. #include <shlobj.h>
  9. #include "atom/browser/native_window_views.h"
  10. #include "atom/browser/unresponsive_suppressor.h"
  11. #include "base/files/file_util.h"
  12. #include "base/i18n/case_conversion.h"
  13. #include "base/strings/string_split.h"
  14. #include "base/strings/string_util.h"
  15. #include "base/strings/utf_string_conversions.h"
  16. #include "base/threading/thread.h"
  17. #include "base/threading/thread_task_runner_handle.h"
  18. #include "base/win/registry.h"
  19. #include "third_party/wtl/include/atlapp.h"
  20. #include "third_party/wtl/include/atldlgs.h"
  21. namespace file_dialog {
  22. DialogSettings::DialogSettings() = default;
  23. DialogSettings::~DialogSettings() = default;
  24. namespace {
  25. // Distinguish directories from regular files.
  26. bool IsDirectory(const base::FilePath& path) {
  27. base::File::Info file_info;
  28. return base::GetFileInfo(path, &file_info) ? file_info.is_directory
  29. : path.EndsWithSeparator();
  30. }
  31. void ConvertFilters(const Filters& filters,
  32. std::vector<std::wstring>* buffer,
  33. std::vector<COMDLG_FILTERSPEC>* filterspec) {
  34. if (filters.empty()) {
  35. COMDLG_FILTERSPEC spec = {L"All Files (*.*)", L"*.*"};
  36. filterspec->push_back(spec);
  37. return;
  38. }
  39. buffer->reserve(filters.size() * 2);
  40. for (size_t i = 0; i < filters.size(); ++i) {
  41. const Filter& filter = filters[i];
  42. COMDLG_FILTERSPEC spec;
  43. buffer->push_back(base::UTF8ToWide(filter.first));
  44. spec.pszName = buffer->back().c_str();
  45. std::vector<std::string> extensions(filter.second);
  46. for (size_t j = 0; j < extensions.size(); ++j)
  47. extensions[j].insert(0, "*.");
  48. buffer->push_back(base::UTF8ToWide(base::JoinString(extensions, ";")));
  49. spec.pszSpec = buffer->back().c_str();
  50. filterspec->push_back(spec);
  51. }
  52. }
  53. // Generic class to delegate common open/save dialog's behaviours, users need to
  54. // call interface methods via GetPtr().
  55. template <typename T>
  56. class FileDialog {
  57. public:
  58. FileDialog(const DialogSettings& settings, int options) {
  59. std::wstring file_part;
  60. if (!IsDirectory(settings.default_path))
  61. file_part = settings.default_path.BaseName().value();
  62. std::vector<std::wstring> buffer;
  63. std::vector<COMDLG_FILTERSPEC> filterspec;
  64. ConvertFilters(settings.filters, &buffer, &filterspec);
  65. dialog_.reset(new T(file_part.c_str(), options, NULL, filterspec.data(),
  66. filterspec.size()));
  67. if (!settings.title.empty())
  68. GetPtr()->SetTitle(base::UTF8ToUTF16(settings.title).c_str());
  69. if (!settings.button_label.empty())
  70. GetPtr()->SetOkButtonLabel(
  71. base::UTF8ToUTF16(settings.button_label).c_str());
  72. // By default, *.* will be added to the file name if file type is "*.*". In
  73. // Electron, we disable it to make a better experience.
  74. //
  75. // From MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/
  76. // bb775970(v=vs.85).aspx
  77. //
  78. // If SetDefaultExtension is not called, the dialog will not update
  79. // automatically when user choose a new file type in the file dialog.
  80. //
  81. // We set file extension to the first none-wildcard extension to make
  82. // sure the dialog will update file extension automatically.
  83. for (size_t i = 0; i < filterspec.size(); ++i) {
  84. if (std::wstring(filterspec[i].pszSpec) != L"*.*") {
  85. // SetFileTypeIndex is regarded as one-based index.
  86. GetPtr()->SetFileTypeIndex(i + 1);
  87. GetPtr()->SetDefaultExtension(filterspec[i].pszSpec);
  88. break;
  89. }
  90. }
  91. if (settings.default_path.IsAbsolute()) {
  92. SetDefaultFolder(settings.default_path);
  93. }
  94. }
  95. bool Show(atom::NativeWindow* parent_window) {
  96. atom::UnresponsiveSuppressor suppressor;
  97. HWND window = parent_window
  98. ? static_cast<atom::NativeWindowViews*>(parent_window)
  99. ->GetAcceleratedWidget()
  100. : NULL;
  101. return dialog_->DoModal(window) == IDOK;
  102. }
  103. T* GetDialog() { return dialog_.get(); }
  104. IFileDialog* GetPtr() const { return dialog_->GetPtr(); }
  105. private:
  106. // Set up the initial directory for the dialog.
  107. void SetDefaultFolder(const base::FilePath file_path) {
  108. std::wstring directory = IsDirectory(file_path)
  109. ? file_path.value()
  110. : file_path.DirName().value();
  111. ATL::CComPtr<IShellItem> folder_item;
  112. HRESULT hr = SHCreateItemFromParsingName(directory.c_str(), NULL,
  113. IID_PPV_ARGS(&folder_item));
  114. if (SUCCEEDED(hr))
  115. GetPtr()->SetFolder(folder_item);
  116. }
  117. std::unique_ptr<T> dialog_;
  118. DISALLOW_COPY_AND_ASSIGN(FileDialog);
  119. };
  120. struct RunState {
  121. base::Thread* dialog_thread;
  122. scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner;
  123. };
  124. bool CreateDialogThread(RunState* run_state) {
  125. std::unique_ptr<base::Thread> thread(
  126. new base::Thread(ATOM_PRODUCT_NAME "FileDialogThread"));
  127. thread->init_com_with_mta(false);
  128. if (!thread->Start())
  129. return false;
  130. run_state->dialog_thread = thread.release();
  131. run_state->ui_task_runner = base::ThreadTaskRunnerHandle::Get();
  132. return true;
  133. }
  134. void RunOpenDialogInNewThread(const RunState& run_state,
  135. const DialogSettings& settings,
  136. const OpenDialogCallback& callback) {
  137. std::vector<base::FilePath> paths;
  138. bool result = ShowOpenDialog(settings, &paths);
  139. run_state.ui_task_runner->PostTask(FROM_HERE,
  140. base::Bind(callback, result, paths));
  141. run_state.ui_task_runner->DeleteSoon(FROM_HERE, run_state.dialog_thread);
  142. }
  143. void RunSaveDialogInNewThread(const RunState& run_state,
  144. const DialogSettings& settings,
  145. const SaveDialogCallback& callback) {
  146. base::FilePath path;
  147. bool result = ShowSaveDialog(settings, &path);
  148. run_state.ui_task_runner->PostTask(FROM_HERE,
  149. base::Bind(callback, result, path));
  150. run_state.ui_task_runner->DeleteSoon(FROM_HERE, run_state.dialog_thread);
  151. }
  152. } // namespace
  153. bool ShowOpenDialog(const DialogSettings& settings,
  154. std::vector<base::FilePath>* paths) {
  155. int options = FOS_FORCEFILESYSTEM | FOS_FILEMUSTEXIST;
  156. if (settings.properties & FILE_DIALOG_OPEN_DIRECTORY)
  157. options |= FOS_PICKFOLDERS;
  158. if (settings.properties & FILE_DIALOG_MULTI_SELECTIONS)
  159. options |= FOS_ALLOWMULTISELECT;
  160. if (settings.properties & FILE_DIALOG_SHOW_HIDDEN_FILES)
  161. options |= FOS_FORCESHOWHIDDEN;
  162. if (settings.properties & FILE_DIALOG_PROMPT_TO_CREATE)
  163. options |= FOS_CREATEPROMPT;
  164. FileDialog<CShellFileOpenDialog> open_dialog(settings, options);
  165. if (!open_dialog.Show(settings.parent_window))
  166. return false;
  167. ATL::CComPtr<IShellItemArray> items;
  168. HRESULT hr =
  169. static_cast<IFileOpenDialog*>(open_dialog.GetPtr())->GetResults(&items);
  170. if (FAILED(hr))
  171. return false;
  172. ATL::CComPtr<IShellItem> item;
  173. DWORD count = 0;
  174. hr = items->GetCount(&count);
  175. if (FAILED(hr))
  176. return false;
  177. paths->reserve(count);
  178. for (DWORD i = 0; i < count; ++i) {
  179. hr = items->GetItemAt(i, &item);
  180. if (FAILED(hr))
  181. return false;
  182. wchar_t file_name[MAX_PATH];
  183. hr = CShellFileOpenDialog::GetFileNameFromShellItem(item, SIGDN_FILESYSPATH,
  184. file_name, MAX_PATH);
  185. if (FAILED(hr))
  186. return false;
  187. paths->push_back(base::FilePath(file_name));
  188. }
  189. return true;
  190. }
  191. void ShowOpenDialog(const DialogSettings& settings,
  192. const OpenDialogCallback& callback) {
  193. RunState run_state;
  194. if (!CreateDialogThread(&run_state)) {
  195. callback.Run(false, std::vector<base::FilePath>());
  196. return;
  197. }
  198. run_state.dialog_thread->task_runner()->PostTask(
  199. FROM_HERE,
  200. base::Bind(&RunOpenDialogInNewThread, run_state, settings, callback));
  201. }
  202. bool ShowSaveDialog(const DialogSettings& settings, base::FilePath* path) {
  203. FileDialog<CShellFileSaveDialog> save_dialog(
  204. settings, FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_OVERWRITEPROMPT);
  205. if (!save_dialog.Show(settings.parent_window))
  206. return false;
  207. wchar_t buffer[MAX_PATH];
  208. HRESULT hr = save_dialog.GetDialog()->GetFilePath(buffer, MAX_PATH);
  209. if (FAILED(hr))
  210. return false;
  211. *path = base::FilePath(buffer);
  212. return true;
  213. }
  214. void ShowSaveDialog(const DialogSettings& settings,
  215. const SaveDialogCallback& callback) {
  216. RunState run_state;
  217. if (!CreateDialogThread(&run_state)) {
  218. callback.Run(false, base::FilePath());
  219. return;
  220. }
  221. run_state.dialog_thread->task_runner()->PostTask(
  222. FROM_HERE,
  223. base::Bind(&RunSaveDialogInNewThread, run_state, settings, callback));
  224. }
  225. } // namespace file_dialog