#include "ui/shell_dialogs/select_file_dialog_win.h"
#include <stddef.h>
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/task_environment.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/win/scoped_com_initializer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/shell_dialogs/select_file_dialog.h"
#include "ui/shell_dialogs/select_file_policy.h"
#include "ui/shell_dialogs/selected_file_info.h"
#include "ui/strings/grit/ui_strings.h"
namespace {
constexpr wchar_t kSelectFolderDefaultTitle[] = L"Select Folder";
constexpr wchar_t kSelectFileDefaultTitle[] = L"Open";
constexpr wchar_t kSaveFileDefaultTitle[] = L"Save As";
std::wstring GetWindowTitle(HWND window) {
wchar_t buffer[256];
UINT count = ::GetWindowText(window, buffer, std::size(buffer));
return std::wstring(buffer, count);
}
HWND WaitForDialogWindow(const std::wstring& dialog_title) {
static constexpr wchar_t kDialogClassName[] = L"#32770";
HWND result = nullptr;
base::TimeDelta max_wait_time = TestTimeouts::action_timeout();
base::TimeDelta retry_interval = base::Milliseconds(20);
while (!result && (max_wait_time.InMilliseconds() > 0)) {
result = ::FindWindow(kDialogClassName, dialog_title.c_str());
base::PlatformThread::Sleep(retry_interval);
max_wait_time -= retry_interval;
}
if (!result) {
LOG(ERROR) << "Wait for dialog window timed out.";
}
return GetWindowTitle(result) == dialog_title ? result : nullptr;
}
struct EnumWindowsParam {
HWND owner;
HWND result;
};
BOOL CALLBACK EnumWindowsCallback(HWND hwnd, LPARAM param) {
EnumWindowsParam* enum_param = reinterpret_cast<EnumWindowsParam*>(param);
if (hwnd == enum_param->owner)
return TRUE;
if (!::IsWindowVisible(hwnd))
return TRUE;
if (::GetWindow(hwnd, GW_OWNER) != enum_param->owner)
return TRUE;
enum_param->result = hwnd;
return FALSE;
}
HWND WaitForDialogPrompt(HWND owner) {
EnumWindowsParam param = {owner, nullptr};
base::TimeDelta max_wait_time = TestTimeouts::action_timeout();
base::TimeDelta retry_interval = base::Milliseconds(20);
while (!param.result && (max_wait_time.InMilliseconds() > 0)) {
::EnumWindows(&EnumWindowsCallback, reinterpret_cast<LPARAM>(¶m));
base::PlatformThread::Sleep(retry_interval);
max_wait_time -= retry_interval;
}
if (!param.result) {
LOG(ERROR) << "Wait for dialog prompt timed out.";
}
return param.result;
}
std::wstring GetDialogItemText(HWND window, int dialog_item_id) {
if (!window)
return std::wstring();
wchar_t buffer[256];
UINT count =
::GetDlgItemText(window, dialog_item_id, buffer, std::size(buffer));
return std::wstring(buffer, count);
}
void SendCommand(HWND window, int id) {
ASSERT_TRUE(window);
base::TimeDelta max_wait_time = TestTimeouts::action_timeout();
base::TimeDelta retry_interval = base::Milliseconds(20);
while (!::IsWindowVisible(window) && (max_wait_time.InMilliseconds() > 0)) {
base::PlatformThread::Sleep(retry_interval);
max_wait_time -= retry_interval;
}
if (!::IsWindowVisible(window)) {
LOG(ERROR) << "SendCommand timed out.";
}
::PostMessage(window, WM_COMMAND, id, 0);
}
}
class SelectFileDialogWinTest : public ::testing::Test,
public ui::SelectFileDialog::Listener {
public:
SelectFileDialogWinTest() = default;
SelectFileDialogWinTest(const SelectFileDialogWinTest&) = delete;
SelectFileDialogWinTest& operator=(const SelectFileDialogWinTest&) = delete;
~SelectFileDialogWinTest() override = default;
void FileSelected(const ui::SelectedFileInfo& file, int index) override {
selected_paths_.push_back(file.path());
}
void MultiFilesSelected(
const std::vector<ui::SelectedFileInfo>& files) override {
selected_paths_ = ui::SelectedFileInfoListToFilePathList(files);
}
void FileSelectionCanceled() override { was_cancelled_ = true; }
void RunUntilIdle() { task_environment_.RunUntilIdle(); }
const std::vector<base::FilePath>& selected_paths() {
return selected_paths_;
}
static gfx::NativeWindow native_window() {
return reinterpret_cast<gfx::NativeWindow>(0);
}
bool was_cancelled() { return was_cancelled_; }
void ResetResults() {
was_cancelled_ = false;
selected_paths_.clear();
}
private:
base::test::TaskEnvironment task_environment_;
std::vector<base::FilePath> selected_paths_;
bool was_cancelled_ = false;
};
TEST_F(SelectFileDialogWinTest, CancelAllDialogs) {
struct {
ui::SelectFileDialog::Type dialog_type;
const wchar_t* dialog_title;
} kTestCases[] = {
{
ui::SelectFileDialog::SELECT_FOLDER, kSelectFolderDefaultTitle,
},
{
ui::SelectFileDialog::SELECT_EXISTING_FOLDER,
kSelectFolderDefaultTitle,
},
{
ui::SelectFileDialog::SELECT_SAVEAS_FILE, kSaveFileDefaultTitle,
},
{
ui::SelectFileDialog::SELECT_OPEN_FILE, kSelectFileDefaultTitle,
},
{
ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE, kSelectFileDefaultTitle,
}};
for (size_t i = 0; i < std::size(kTestCases); ++i) {
SCOPED_TRACE(base::StringPrintf("i=%zu", i));
const auto& test_case = UNSAFE_TODO(kTestCases[i]);
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> file_type_info;
int file_type_info_index = 0;
if (test_case.dialog_type == ui::SelectFileDialog::SELECT_SAVEAS_FILE) {
file_type_info = std::make_unique<ui::SelectFileDialog::FileTypeInfo>();
file_type_info->extensions.push_back({L"html"});
file_type_info_index = 1;
}
dialog->SelectFile(test_case.dialog_type, std::u16string(),
base::FilePath(), file_type_info.get(),
file_type_info_index, std::wstring(), native_window());
HWND window = WaitForDialogWindow(test_case.dialog_title);
SendCommand(window, IDCANCEL);
RunUntilIdle();
EXPECT_TRUE(was_cancelled());
EXPECT_TRUE(selected_paths().empty());
ResetResults();
}
}
TEST_F(SelectFileDialogWinTest, UploadFolderCheckStrings) {
base::ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath default_path = scoped_temp_dir.GetPath();
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_UPLOAD_FOLDER,
std::u16string(), default_path, nullptr, 0, L"",
native_window());
HWND window = WaitForDialogWindow(base::UTF16ToWide(
l10n_util::GetStringUTF16(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE)));
EXPECT_NE(GetWindowTitle(window), kSelectFolderDefaultTitle);
EXPECT_EQ(GetDialogItemText(window, 1),
base::UTF16ToWide(l10n_util::GetStringUTF16(
IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON)));
SendCommand(window, IDOK);
RunUntilIdle();
EXPECT_FALSE(was_cancelled());
ASSERT_EQ(1u, selected_paths().size());
EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase(
selected_paths()[0].value(), default_path.value()));
}
TEST_F(SelectFileDialogWinTest, SpecifyTitle) {
static constexpr char16_t kTitle[] = u"FooBar Title";
base::ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
std::string contents = "Hello test!";
ASSERT_TRUE(base::WriteFile(default_path, contents));
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, kTitle,
default_path, nullptr, 0, L"", native_window());
HWND window = WaitForDialogWindow(base::UTF16ToWide(kTitle));
SendCommand(window, IDCANCEL);
}
TEST_F(SelectFileDialogWinTest, TestSelectFile) {
base::ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
std::string contents = "Hello test!";
ASSERT_TRUE(base::WriteFile(default_path, contents));
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(),
default_path, nullptr, 0, L"", native_window());
HWND window = WaitForDialogWindow(kSelectFileDefaultTitle);
SendCommand(window, IDOK);
RunUntilIdle();
EXPECT_FALSE(was_cancelled());
ASSERT_EQ(1u, selected_paths().size());
EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase(
selected_paths()[0].value(), default_path.value()));
}
TEST_F(SelectFileDialogWinTest, TestSaveFile) {
base::ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo");
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.push_back({L"html"});
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
default_path, &file_type_info, 1, L"", native_window());
HWND window = WaitForDialogWindow(kSaveFileDefaultTitle);
SendCommand(window, IDOK);
RunUntilIdle();
EXPECT_FALSE(was_cancelled());
ASSERT_EQ(1u, selected_paths().size());
EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase(
selected_paths()[0].value(), default_path.AddExtension(L"html").value()));
}
TEST_F(SelectFileDialogWinTest, OnlyBasename) {
base::FilePath default_path(L"foobar.html");
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.push_back({L"html"});
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
default_path, &file_type_info, 1, L"", native_window());
HWND window = WaitForDialogWindow(kSaveFileDefaultTitle);
SendCommand(window, IDOK);
RunUntilIdle();
EXPECT_FALSE(was_cancelled());
ASSERT_EQ(1u, selected_paths().size());
EXPECT_EQ(selected_paths()[0].BaseName(), default_path);
}
TEST_F(SelectFileDialogWinTest, SaveAsDifferentExtension) {
base::ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.push_back({L"exe"});
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
default_path, &file_type_info, 1, L"html",
native_window());
HWND window = WaitForDialogWindow(kSaveFileDefaultTitle);
SendCommand(window, IDOK);
RunUntilIdle();
EXPECT_FALSE(was_cancelled());
EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase(
selected_paths()[0].value(), default_path.value()));
}
TEST_F(SelectFileDialogWinTest, OpenFileDifferentExtension) {
base::ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
std::string contents = "Hello test!";
ASSERT_TRUE(base::WriteFile(default_path, contents));
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.push_back({L"exe"});
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(),
default_path, &file_type_info, 1, L"html",
native_window());
HWND window = WaitForDialogWindow(kSelectFileDefaultTitle);
SendCommand(window, IDOK);
RunUntilIdle();
EXPECT_FALSE(was_cancelled());
EXPECT_TRUE(base::FilePath::CompareEqualIgnoreCase(
selected_paths()[0].value(), default_path.value()));
}
TEST_F(SelectFileDialogWinTest, SelectNonExistingFile) {
base::ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath default_path =
scoped_temp_dir.GetPath().Append(L"does-not-exist.html");
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(),
default_path, nullptr, 0, L"", native_window());
HWND window = WaitForDialogWindow(kSelectFileDefaultTitle);
SendCommand(window, IDOK);
HWND error_box = WaitForDialogPrompt(window);
SendCommand(error_box, IDOK);
SendCommand(window, IDCANCEL);
RunUntilIdle();
EXPECT_TRUE(was_cancelled());
EXPECT_TRUE(selected_paths().empty());
}
TEST_F(SelectFileDialogWinTest, SaveFileOverwritePrompt) {
base::ScopedTempDir scoped_temp_dir;
ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath default_path = scoped_temp_dir.GetPath().Append(L"foo.txt");
std::string contents = "Hello test!";
ASSERT_TRUE(base::WriteFile(default_path, contents));
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.push_back({L"txt"});
scoped_refptr<ui::SelectFileDialog> dialog =
ui::SelectFileDialog::Create(this, nullptr);
dialog->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE, std::u16string(),
default_path, &file_type_info, 1, L"", native_window());
HWND window = WaitForDialogWindow(kSaveFileDefaultTitle);
SendCommand(window, IDOK);
HWND error_box = WaitForDialogPrompt(window);
SendCommand(error_box, IDOK);
SendCommand(window, IDCANCEL);
RunUntilIdle();
EXPECT_TRUE(was_cancelled());
EXPECT_TRUE(selected_paths().empty());
}