select_file_dialog_win_unittest.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Copyright (c) 2012 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/select_file_dialog_win.h"
  5. #include <stddef.h>
  6. #include <memory>
  7. #include <string>
  8. #include <vector>
  9. #include "base/files/file_path.h"
  10. #include "base/files/file_util.h"
  11. #include "base/files/scoped_temp_dir.h"
  12. #include "base/logging.h"
  13. #include "base/memory/scoped_refptr.h"
  14. #include "base/strings/stringprintf.h"
  15. #include "base/strings/utf_string_conversions.h"
  16. #include "base/test/task_environment.h"
  17. #include "base/test/test_timeouts.h"
  18. #include "base/threading/platform_thread.h"
  19. #include "base/win/scoped_com_initializer.h"
  20. #include "base/win/windows_version.h"
  21. #include "testing/gtest/include/gtest/gtest.h"
  22. #include "ui/base/l10n/l10n_util.h"
  23. #include "ui/shell_dialogs/select_file_dialog.h"
  24. #include "ui/shell_dialogs/select_file_policy.h"
  25. #include "ui/strings/grit/ui_strings.h"
  26. namespace {
  27. // The default title for the various dialogs.
  28. constexpr wchar_t kSelectFolderDefaultTitle[] = L"Select Folder";
  29. constexpr wchar_t kSelectFileDefaultTitle[] = L"Open";
  30. constexpr wchar_t kSaveFileDefaultTitle[] = L"Save As";
  31. // Returns the title of |window|.
  32. std::wstring GetWindowTitle(HWND window) {
  33. wchar_t buffer[256];
  34. UINT count = ::GetWindowText(window, buffer, std::size(buffer));
  35. return std::wstring(buffer, count);
  36. }
  37. // Waits for a dialog window whose title is |dialog_title| to show and returns
  38. // its handle.
  39. HWND WaitForDialogWindow(const std::wstring& dialog_title) {
  40. // File dialogs uses this class name.
  41. static constexpr wchar_t kDialogClassName[] = L"#32770";
  42. HWND result = nullptr;
  43. base::TimeDelta max_wait_time = TestTimeouts::action_timeout();
  44. base::TimeDelta retry_interval = base::Milliseconds(20);
  45. while (!result && (max_wait_time.InMilliseconds() > 0)) {
  46. result = ::FindWindow(kDialogClassName, dialog_title.c_str());
  47. base::PlatformThread::Sleep(retry_interval);
  48. max_wait_time -= retry_interval;
  49. }
  50. if (!result) {
  51. LOG(ERROR) << "Wait for dialog window timed out.";
  52. }
  53. // Check the name of the dialog specifically. That's because if multiple file
  54. // dialogs are opened in quick successions (e.g. from one test to another),
  55. // the ::FindWindow() call above will work for both the previous dialog title
  56. // and the current.
  57. return GetWindowTitle(result) == dialog_title ? result : nullptr;
  58. }
  59. struct EnumWindowsParam {
  60. // The owner of the dialog. This is used to differentiate the dialog prompt
  61. // from the file dialog since they could have the same title.
  62. HWND owner;
  63. // Holds the resulting window.
  64. HWND result;
  65. };
  66. BOOL CALLBACK EnumWindowsCallback(HWND hwnd, LPARAM param) {
  67. EnumWindowsParam* enum_param = reinterpret_cast<EnumWindowsParam*>(param);
  68. // Early continue if the current hwnd is the file dialog.
  69. if (hwnd == enum_param->owner)
  70. return TRUE;
  71. // Only consider visible windows.
  72. if (!::IsWindowVisible(hwnd))
  73. return TRUE;
  74. // If the window doesn't have |enum_param->owner| as the owner, it can't be
  75. // the prompt dialog.
  76. if (::GetWindow(hwnd, GW_OWNER) != enum_param->owner)
  77. return TRUE;
  78. enum_param->result = hwnd;
  79. return FALSE;
  80. }
  81. HWND WaitForDialogPrompt(HWND owner) {
  82. // The dialog prompt could have the same title as the file dialog. This means
  83. // that it would not be possible to make sure the right window is found using
  84. // ::FindWindow(). Instead enumerate all top-level windows and return the one
  85. // whose owner is the file dialog.
  86. EnumWindowsParam param = {owner, nullptr};
  87. base::TimeDelta max_wait_time = TestTimeouts::action_timeout();
  88. base::TimeDelta retry_interval = base::Milliseconds(20);
  89. while (!param.result && (max_wait_time.InMilliseconds() > 0)) {
  90. ::EnumWindows(&EnumWindowsCallback, reinterpret_cast<LPARAM>(&param));
  91. base::PlatformThread::Sleep(retry_interval);
  92. max_wait_time -= retry_interval;
  93. }
  94. if (!param.result) {
  95. LOG(ERROR) << "Wait for dialog prompt timed out.";
  96. }
  97. return param.result;
  98. }
  99. // Returns the text of the dialog item in |window| whose id is |dialog_item_id|.
  100. std::wstring GetDialogItemText(HWND window, int dialog_item_id) {
  101. if (!window)
  102. return std::wstring();
  103. wchar_t buffer[256];
  104. UINT count =
  105. ::GetDlgItemText(window, dialog_item_id, buffer, std::size(buffer));
  106. return std::wstring(buffer, count);
  107. }
  108. // Sends a command to |window| using PostMessage().
  109. void SendCommand(HWND window, int id) {
  110. ASSERT_TRUE(window);
  111. // Make sure the window is visible first or the WM_COMMAND may not have any
  112. // effect.
  113. base::TimeDelta max_wait_time = TestTimeouts::action_timeout();
  114. base::TimeDelta retry_interval = base::Milliseconds(20);
  115. while (!::IsWindowVisible(window) && (max_wait_time.InMilliseconds() > 0)) {
  116. base::PlatformThread::Sleep(retry_interval);
  117. max_wait_time -= retry_interval;
  118. }
  119. if (!::IsWindowVisible(window)) {
  120. LOG(ERROR) << "SendCommand timed out.";
  121. }
  122. ::PostMessage(window, WM_COMMAND, id, 0);
  123. }
  124. } // namespace
  125. class SelectFileDialogWinTest : public ::testing::Test,
  126. public ui::SelectFileDialog::Listener {
  127. public:
  128. SelectFileDialogWinTest() = default;
  129. SelectFileDialogWinTest(const SelectFileDialogWinTest&) = delete;
  130. SelectFileDialogWinTest& operator=(const SelectFileDialogWinTest&) = delete;
  131. ~SelectFileDialogWinTest() override = default;
  132. // ui::SelectFileDialog::Listener:
  133. void FileSelected(const base::FilePath& path,
  134. int index,
  135. void* params) override {
  136. selected_paths_.push_back(path);
  137. }
  138. void MultiFilesSelected(const std::vector<base::FilePath>& files,
  139. void* params) override {
  140. selected_paths_ = files;
  141. }
  142. void FileSelectionCanceled(void* params) override { was_cancelled_ = true; }
  143. // Runs the scheduler until no tasks are executing anymore.
  144. void RunUntilIdle() { task_environment_.RunUntilIdle(); }
  145. const std::vector<base::FilePath>& selected_paths() {
  146. return selected_paths_;
  147. }
  148. // Return a fake NativeWindow. This will result in the dialog having no
  149. // parent window but the tests will still work.
  150. static gfx::NativeWindow native_window() {
  151. return reinterpret_cast<gfx::NativeWindow>(0);
  152. }
  153. bool was_cancelled() { return was_cancelled_; }
  154. // Resets the results so that this instance can be reused as a
  155. // SelectFileDialog listener.
  156. void ResetResults() {
  157. was_cancelled_ = false;
  158. selected_paths_.clear();
  159. }
  160. private:
  161. base::test::TaskEnvironment task_environment_;
  162. std::vector<base::FilePath> selected_paths_;
  163. bool was_cancelled_ = false;
  164. };
  165. TEST_F(SelectFileDialogWinTest, CancelAllDialogs) {
  166. // TODO(crbug.com/1265379): Flaky on Windows 7.
  167. if (base::win::GetVersion() <= base::win::Version::WIN7)
  168. GTEST_SKIP() << "Skipping test for Windows 7";
  169. // Intentionally not testing SELECT_UPLOAD_FOLDER because the dialog is
  170. // customized for that case.
  171. struct {
  172. ui::SelectFileDialog::Type dialog_type;
  173. const wchar_t* dialog_title;
  174. } kTestCases[] = {
  175. {
  176. ui::SelectFileDialog::SELECT_FOLDER, kSelectFolderDefaultTitle,
  177. },
  178. {
  179. ui::SelectFileDialog::SELECT_EXISTING_FOLDER,
  180. kSelectFolderDefaultTitle,
  181. },
  182. {
  183. ui::SelectFileDialog::SELECT_SAVEAS_FILE, kSaveFileDefaultTitle,
  184. },
  185. {
  186. ui::SelectFileDialog::SELECT_OPEN_FILE, kSelectFileDefaultTitle,
  187. },
  188. {
  189. ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE, kSelectFileDefaultTitle,
  190. }};
  191. for (size_t i = 0; i < std::size(kTestCases); ++i) {
  192. SCOPED_TRACE(base::StringPrintf("i=%zu", i));
  193. const auto& test_case = kTestCases[i];
  194. scoped_refptr<ui::SelectFileDialog> dialog =
  195. ui::SelectFileDialog::Create(this, nullptr);
  196. std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> file_type_info;
  197. int file_type_info_index = 0;
  198. // The Save As dialog requires a filetype info.
  199. if (test_case.dialog_type == ui::SelectFileDialog::SELECT_SAVEAS_FILE) {
  200. file_type_info = std::make_unique<ui::SelectFileDialog::FileTypeInfo>();
  201. file_type_info->extensions.push_back({L"html"});
  202. file_type_info_index = 1;
  203. }
  204. dialog->SelectFile(test_case.dialog_type, std::u16string(),
  205. base::FilePath(), file_type_info.get(),
  206. file_type_info_index, std::wstring(), native_window(),
  207. nullptr);
  208. // Accept the default value.
  209. HWND window = WaitForDialogWindow(test_case.dialog_title);
  210. SendCommand(window, IDCANCEL);
  211. RunUntilIdle();
  212. EXPECT_TRUE(was_cancelled());
  213. EXPECT_TRUE(selected_paths().empty());
  214. ResetResults();
  215. }
  216. }
  217. // When using SELECT_UPLOAD_FOLDER, the title and the ok button strings are
  218. // modified to put emphasis on the fact that the whole folder will be uploaded.
  219. TEST_F(SelectFileDialogWinTest, UploadFolderCheckStrings) {
  220. base::ScopedTempDir scoped_temp_dir;
  221. ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
  222. base::FilePath default_path = scoped_temp_dir.GetPath();
  223. scoped_refptr<ui::SelectFileDialog> dialog =
  224. ui::SelectFileDialog::Create(this, nullptr);
  225. dialog->SelectFile(ui::SelectFileDialog::SELECT_UPLOAD_FOLDER,
  226. std::u16string(), default_path, nullptr, 0, L"",
  227. native_window(), nullptr);
  228. // Wait for the window to open and make sure the window title was changed from
  229. // the default title for a regular select folder operation.
  230. HWND window = WaitForDialogWindow(base::UTF16ToWide(
  231. l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE)));
  232. EXPECT_NE(GetWindowTitle(window), kSelectFolderDefaultTitle);
  233. // Check the OK button text.
  234. EXPECT_EQ(GetDialogItemText(window, 1),
  235. base::UTF16ToWide(l10n_util::GetStringUTF16(
  236. IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON)));
  237. // Close the dialog.
  238. SendCommand(window, IDOK);
  239. RunUntilIdle();
  240. EXPECT_FALSE(was_cancelled());
  241. ASSERT_EQ(1u, selected_paths().size());
  242. EXPECT_EQ(selected_paths()[0], default_path);
  243. }
  244. // Specifying the title when opening a dialog to select a file, select multiple
  245. // files or save a file doesn't do anything.
  246. TEST_F(SelectFileDialogWinTest, SpecifyTitle) {
  247. static constexpr char16_t kTitle[] = u"FooBar Title";
  248. // Create some file in a test folder.
  249. base::ScopedTempDir scoped_temp_dir;
  250. ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
  251. // Create an existing file since it is required.
  252. base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
  253. std::string contents = "Hello test!";
  254. ASSERT_TRUE(base::WriteFile(default_path, contents));
  255. scoped_refptr<ui::SelectFileDialog> dialog =
  256. ui::SelectFileDialog::Create(this, nullptr);
  257. dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, kTitle,
  258. default_path, nullptr, 0, L"", native_window(), nullptr);
  259. // Wait for the window to open. The title is unchanged. Note that if this
  260. // hangs, it possibly is because the title changed.
  261. HWND window = WaitForDialogWindow(kSelectFileDefaultTitle);
  262. // Close the dialog and the result doesn't matter.
  263. SendCommand(window, IDCANCEL);
  264. }
  265. // Tests the selection of one file in both the single and multiple case. It's
  266. // too much trouble to select a different file in the dialog so the default_path
  267. // is used to pre-select a file and the OK button is clicked as soon as the
  268. // dialog opens. This tests the default_path parameter and the single file
  269. // selection.
  270. TEST_F(SelectFileDialogWinTest, TestSelectFile) {
  271. // Create some file in a test folder.
  272. base::ScopedTempDir scoped_temp_dir;
  273. ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
  274. // Create an existing file since it is required.
  275. base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
  276. std::string contents = "Hello test!";
  277. ASSERT_TRUE(base::WriteFile(default_path, contents));
  278. scoped_refptr<ui::SelectFileDialog> dialog =
  279. ui::SelectFileDialog::Create(this, nullptr);
  280. dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(),
  281. default_path, nullptr, 0, L"", native_window(), nullptr);
  282. // Wait for the window to open
  283. HWND window = WaitForDialogWindow(kSelectFileDefaultTitle);
  284. SendCommand(window, IDOK);
  285. RunUntilIdle();
  286. EXPECT_FALSE(was_cancelled());
  287. ASSERT_EQ(1u, selected_paths().size());
  288. EXPECT_EQ(selected_paths()[0], default_path);
  289. }
  290. // Tests that the file extension is automatically added.
  291. TEST_F(SelectFileDialogWinTest, TestSaveFile) {
  292. // Create some file in a test folder.
  293. base::ScopedTempDir scoped_temp_dir;
  294. ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
  295. base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo");
  296. ui::SelectFileDialog::FileTypeInfo file_type_info;
  297. file_type_info.extensions.push_back({L"html"});
  298. scoped_refptr<ui::SelectFileDialog> dialog =
  299. ui::SelectFileDialog::Create(this, nullptr);
  300. dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
  301. default_path, &file_type_info, 1, L"", native_window(),
  302. nullptr);
  303. // Wait for the window to open
  304. HWND window = WaitForDialogWindow(kSaveFileDefaultTitle);
  305. SendCommand(window, IDOK);
  306. RunUntilIdle();
  307. EXPECT_FALSE(was_cancelled());
  308. ASSERT_EQ(1u, selected_paths().size());
  309. EXPECT_EQ(selected_paths()[0], default_path.AddExtension(L"html"));
  310. }
  311. // Tests that only specifying a basename as the default path works.
  312. TEST_F(SelectFileDialogWinTest, OnlyBasename) {
  313. base::FilePath default_path(L"foobar.html");
  314. ui::SelectFileDialog::FileTypeInfo file_type_info;
  315. file_type_info.extensions.push_back({L"html"});
  316. scoped_refptr<ui::SelectFileDialog> dialog =
  317. ui::SelectFileDialog::Create(this, nullptr);
  318. dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
  319. default_path, &file_type_info, 1, L"", native_window(),
  320. nullptr);
  321. // Wait for the window to open
  322. HWND window = WaitForDialogWindow(kSaveFileDefaultTitle);
  323. SendCommand(window, IDOK);
  324. RunUntilIdle();
  325. EXPECT_FALSE(was_cancelled());
  326. ASSERT_EQ(1u, selected_paths().size());
  327. EXPECT_EQ(selected_paths()[0].BaseName(), default_path);
  328. }
  329. TEST_F(SelectFileDialogWinTest, SaveAsDifferentExtension) {
  330. // Create some file in a test folder.
  331. base::ScopedTempDir scoped_temp_dir;
  332. ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
  333. base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
  334. ui::SelectFileDialog::FileTypeInfo file_type_info;
  335. file_type_info.extensions.push_back({L"exe"});
  336. scoped_refptr<ui::SelectFileDialog> dialog =
  337. ui::SelectFileDialog::Create(this, nullptr);
  338. dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
  339. default_path, &file_type_info, 1, L"html", native_window(),
  340. nullptr);
  341. HWND window = WaitForDialogWindow(kSaveFileDefaultTitle);
  342. SendCommand(window, IDOK);
  343. RunUntilIdle();
  344. EXPECT_FALSE(was_cancelled());
  345. EXPECT_EQ(selected_paths()[0], default_path);
  346. }
  347. TEST_F(SelectFileDialogWinTest, OpenFileDifferentExtension) {
  348. // Create some file in a test folder.
  349. base::ScopedTempDir scoped_temp_dir;
  350. ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
  351. base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
  352. std::string contents = "Hello test!";
  353. ASSERT_TRUE(base::WriteFile(default_path, contents));
  354. ui::SelectFileDialog::FileTypeInfo file_type_info;
  355. file_type_info.extensions.push_back({L"exe"});
  356. scoped_refptr<ui::SelectFileDialog> dialog =
  357. ui::SelectFileDialog::Create(this, nullptr);
  358. dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(),
  359. default_path, &file_type_info, 1, L"html", native_window(),
  360. nullptr);
  361. HWND window = WaitForDialogWindow(kSelectFileDefaultTitle);
  362. SendCommand(window, IDOK);
  363. RunUntilIdle();
  364. EXPECT_FALSE(was_cancelled());
  365. EXPECT_EQ(selected_paths()[0], default_path);
  366. }
  367. TEST_F(SelectFileDialogWinTest, SelectNonExistingFile) {
  368. // Create some file in a test folder.
  369. base::ScopedTempDir scoped_temp_dir;
  370. ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
  371. base::FilePath default_path =
  372. scoped_temp_dir.GetPath().Append(L"does-not-exist.html");
  373. scoped_refptr<ui::SelectFileDialog> dialog =
  374. ui::SelectFileDialog::Create(this, nullptr);
  375. dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(),
  376. default_path, nullptr, 0, L"", native_window(), nullptr);
  377. HWND window = WaitForDialogWindow(kSelectFileDefaultTitle);
  378. SendCommand(window, IDOK);
  379. // Since selecting a non-existing file is not supported, a error dialog box
  380. // should have appeared.
  381. HWND error_box = WaitForDialogPrompt(window);
  382. SendCommand(error_box, IDOK);
  383. // Now actually cancel the file dialog box.
  384. SendCommand(window, IDCANCEL);
  385. RunUntilIdle();
  386. EXPECT_TRUE(was_cancelled());
  387. EXPECT_TRUE(selected_paths().empty());
  388. }
  389. // Tests that selecting an existing file when saving should prompt the user with
  390. // a dialog to confirm the overwrite.
  391. TEST_F(SelectFileDialogWinTest, SaveFileOverwritePrompt) {
  392. // Create some file in a test folder.
  393. base::ScopedTempDir scoped_temp_dir;
  394. ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
  395. base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
  396. std::string contents = "Hello test!";
  397. ASSERT_TRUE(base::WriteFile(default_path, contents));
  398. ui::SelectFileDialog::FileTypeInfo file_type_info;
  399. file_type_info.extensions.push_back({L"txt"});
  400. scoped_refptr<ui::SelectFileDialog> dialog =
  401. ui::SelectFileDialog::Create(this, nullptr);
  402. dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
  403. default_path, &file_type_info, 1, L"", native_window(),
  404. nullptr);
  405. HWND window = WaitForDialogWindow(kSaveFileDefaultTitle);
  406. SendCommand(window, IDOK);
  407. // Check that the prompt appears and close it. By default, the "no" option is
  408. // selected so sending IDOK cancels the operation.
  409. HWND error_box = WaitForDialogPrompt(window);
  410. SendCommand(error_box, IDOK);
  411. // Cancel the dialog.
  412. SendCommand(window, IDCANCEL);
  413. RunUntilIdle();
  414. EXPECT_TRUE(was_cancelled());
  415. EXPECT_TRUE(selected_paths().empty());
  416. }