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.
5 #include "chrome/browser/ui/views/select_file_dialog_extension.h"
7 #include "base/files/file_util.h"
8 #include "base/files/scoped_temp_dir.h"
9 #include "base/logging.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/path_service.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/threading/platform_thread.h"
15 #include "build/build_config.h"
16 #include "chrome/browser/chromeos/file_manager/volume_manager.h"
17 #include "chrome/browser/extensions/component_loader.h"
18 #include "chrome/browser/extensions/extension_browsertest.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "chrome/browser/ui/browser.h"
21 #include "chrome/browser/ui/browser_navigator.h"
22 #include "chrome/browser/ui/browser_window.h"
23 #include "chrome/common/chrome_paths.h"
24 #include "chrome/common/pref_names.h"
25 #include "content/public/browser/notification_service.h"
26 #include "content/public/browser/notification_types.h"
27 #include "content/public/browser/render_frame_host.h"
28 #include "content/public/browser/render_view_host.h"
29 #include "content/public/test/test_utils.h"
30 #include "extensions/test/extension_test_message_listener.h"
31 #include "ui/shell_dialogs/select_file_dialog.h"
32 #include "ui/shell_dialogs/selected_file_info.h"
34 using content::BrowserContext
;
36 // Mock listener used by test below.
37 class MockSelectFileDialogListener
: public ui::SelectFileDialog::Listener
{
39 MockSelectFileDialogListener()
40 : file_selected_(false),
45 bool file_selected() const { return file_selected_
; }
46 bool canceled() const { return canceled_
; }
47 base::FilePath
path() const { return path_
; }
48 void* params() const { return params_
; }
50 // ui::SelectFileDialog::Listener implementation.
51 void FileSelected(const base::FilePath
& path
,
53 void* params
) override
{
54 file_selected_
= true;
58 void FileSelectedWithExtraInfo(const ui::SelectedFileInfo
& selected_file_info
,
60 void* params
) override
{
61 FileSelected(selected_file_info
.local_path
, index
, params
);
63 void MultiFilesSelected(const std::vector
<base::FilePath
>& files
,
64 void* params
) override
{}
65 void FileSelectionCanceled(void* params
) override
{
76 DISALLOW_COPY_AND_ASSIGN(MockSelectFileDialogListener
);
79 class SelectFileDialogExtensionBrowserTest
: public ExtensionBrowserTest
{
81 enum DialogButtonType
{
86 void SetUp() override
{
87 extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();
89 // Create the dialog wrapper object, but don't show it yet.
90 listener_
.reset(new MockSelectFileDialogListener());
91 dialog_
= new SelectFileDialogExtension(listener_
.get(), NULL
);
93 // We have to provide at least one mount point.
94 // File manager looks for "Downloads" mount point, so use this name.
95 base::FilePath tmp_path
;
96 PathService::Get(base::DIR_TEMP
, &tmp_path
);
97 ASSERT_TRUE(tmp_dir_
.CreateUniqueTempDirUnderPath(tmp_path
));
98 downloads_dir_
= tmp_dir_
.path().Append("Downloads");
99 base::CreateDirectory(downloads_dir_
);
101 // Must run after our setup because it actually runs the test.
102 ExtensionBrowserTest::SetUp();
105 void TearDown() override
{
106 ExtensionBrowserTest::TearDown();
108 // Delete the dialog first, as it holds a pointer to the listener.
112 second_dialog_
= NULL
;
113 second_listener_
.reset();
116 // Creates a file system mount point for a directory.
117 void AddMountPoint(const base::FilePath
& path
) {
118 EXPECT_TRUE(file_manager::VolumeManager::Get(
119 browser()->profile())->RegisterDownloadsDirectoryForTesting(path
));
120 browser()->profile()->GetPrefs()->SetFilePath(
121 prefs::kDownloadDefaultDirectory
, downloads_dir_
);
124 void CheckJavascriptErrors() {
125 content::RenderFrameHost
* host
=
126 dialog_
->GetRenderViewHost()->GetMainFrame();
127 scoped_ptr
<base::Value
> value
=
128 content::ExecuteScriptAndGetValue(host
, "window.JSErrorCount");
129 int js_error_count
= 0;
130 ASSERT_TRUE(value
->GetAsInteger(&js_error_count
));
131 ASSERT_EQ(0, js_error_count
);
134 void OpenDialog(ui::SelectFileDialog::Type dialog_type
,
135 const base::FilePath
& file_path
,
136 const gfx::NativeWindow
& owning_window
,
137 const std::string
& additional_message
) {
138 // Spawn a dialog to open a file. The dialog will signal that it is ready
139 // via chrome.test.sendMessage() in the extension JavaScript.
140 ExtensionTestMessageListener
init_listener("ready", false /* will_reply */);
142 scoped_ptr
<ExtensionTestMessageListener
> additional_listener
;
143 if (!additional_message
.empty()) {
144 additional_listener
.reset(
145 new ExtensionTestMessageListener(additional_message
, false));
148 dialog_
->SelectFile(dialog_type
,
149 base::string16() /* title */,
151 NULL
/* file_types */,
152 0 /* file_type_index */,
153 FILE_PATH_LITERAL("") /* default_extension */,
157 LOG(INFO
) << "Waiting for JavaScript ready message.";
158 ASSERT_TRUE(init_listener
.WaitUntilSatisfied());
160 if (additional_listener
.get()) {
161 LOG(INFO
) << "Waiting for JavaScript " << additional_message
163 ASSERT_TRUE(additional_listener
->WaitUntilSatisfied());
166 // Dialog should be running now.
167 ASSERT_TRUE(dialog_
->IsRunning(owning_window
));
169 ASSERT_NO_FATAL_FAILURE(CheckJavascriptErrors());
172 void TryOpeningSecondDialog(const gfx::NativeWindow
& owning_window
) {
173 second_listener_
.reset(new MockSelectFileDialogListener());
174 second_dialog_
= new SelectFileDialogExtension(second_listener_
.get(),
177 // At the moment we don't really care about dialog type, but we have to put
179 second_dialog_
->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE
,
180 base::string16() /* title */,
181 base::FilePath() /* default_path */,
182 NULL
/* file_types */,
183 0 /* file_type_index */,
184 FILE_PATH_LITERAL("") /* default_extension */,
189 void CloseDialog(DialogButtonType button_type
,
190 const gfx::NativeWindow
& owning_window
) {
191 // Inject JavaScript to click the cancel button and wait for notification
192 // that the window has closed.
193 content::WindowedNotificationObserver
host_destroyed(
194 content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
195 content::NotificationService::AllSources());
196 content::RenderViewHost
* host
= dialog_
->GetRenderViewHost();
197 std::string button_class
=
198 (button_type
== DIALOG_BTN_OK
) ? ".button-panel .ok" :
199 ".button-panel .cancel";
200 base::string16 script
= base::ASCIIToUTF16(
201 "console.log(\'Test JavaScript injected.\');"
202 "document.querySelector(\'" + button_class
+ "\').click();");
203 // The file selection handler closes the dialog and does not return control
204 // to JavaScript, so do not wait for return values.
205 host
->GetMainFrame()->ExecuteJavaScript(script
);
206 LOG(INFO
) << "Waiting for window close notification.";
207 host_destroyed
.Wait();
209 // Dialog no longer believes it is running.
210 ASSERT_FALSE(dialog_
->IsRunning(owning_window
));
213 scoped_ptr
<MockSelectFileDialogListener
> listener_
;
214 scoped_refptr
<SelectFileDialogExtension
> dialog_
;
216 scoped_ptr
<MockSelectFileDialogListener
> second_listener_
;
217 scoped_refptr
<SelectFileDialogExtension
> second_dialog_
;
219 base::ScopedTempDir tmp_dir_
;
220 base::FilePath downloads_dir_
;
223 IN_PROC_BROWSER_TEST_F(SelectFileDialogExtensionBrowserTest
, CreateAndDestroy
) {
224 // Browser window must be up for us to test dialog window parent.
225 gfx::NativeWindow native_window
= browser()->window()->GetNativeWindow();
226 ASSERT_TRUE(native_window
!= NULL
);
228 // Before we call SelectFile, dialog is not running/visible.
229 ASSERT_FALSE(dialog_
->IsRunning(native_window
));
232 IN_PROC_BROWSER_TEST_F(SelectFileDialogExtensionBrowserTest
, DestroyListener
) {
233 // Some users of SelectFileDialog destroy their listener before cleaning
234 // up the dialog. Make sure we don't crash.
235 dialog_
->ListenerDestroyed();
239 // TODO(jamescook): Add a test for selecting a file for an <input type='file'/>
240 // page element, as that uses different memory management pathways.
243 IN_PROC_BROWSER_TEST_F(SelectFileDialogExtensionBrowserTest
,
244 SelectFileAndCancel
) {
245 AddMountPoint(downloads_dir_
);
247 gfx::NativeWindow owning_window
= browser()->window()->GetNativeWindow();
249 // base::FilePath() for default path.
250 ASSERT_NO_FATAL_FAILURE(OpenDialog(ui::SelectFileDialog::SELECT_OPEN_FILE
,
251 base::FilePath(), owning_window
, ""));
253 // Press cancel button.
254 CloseDialog(DIALOG_BTN_CANCEL
, owning_window
);
256 // Listener should have been informed of the cancellation.
257 ASSERT_FALSE(listener_
->file_selected());
258 ASSERT_TRUE(listener_
->canceled());
259 ASSERT_EQ(this, listener_
->params());
262 IN_PROC_BROWSER_TEST_F(SelectFileDialogExtensionBrowserTest
,
264 AddMountPoint(downloads_dir_
);
266 base::FilePath test_file
=
267 downloads_dir_
.AppendASCII("file_manager_test.html");
269 // Create an empty file to give us something to select.
270 FILE* fp
= base::OpenFile(test_file
, "w");
271 ASSERT_TRUE(fp
!= NULL
);
272 ASSERT_TRUE(base::CloseFile(fp
));
274 gfx::NativeWindow owning_window
= browser()->window()->GetNativeWindow();
276 // Spawn a dialog to open a file. Provide the path to the file so the dialog
277 // will automatically select it. Ensure that the OK button is enabled by
278 // waiting for chrome.test.sendMessage('selection-change-complete').
279 ASSERT_NO_FATAL_FAILURE(OpenDialog(ui::SelectFileDialog::SELECT_OPEN_FILE
,
280 test_file
, owning_window
,
283 // Click open button.
284 CloseDialog(DIALOG_BTN_OK
, owning_window
);
286 // Listener should have been informed that the file was opened.
287 ASSERT_TRUE(listener_
->file_selected());
288 ASSERT_FALSE(listener_
->canceled());
289 ASSERT_EQ(test_file
, listener_
->path());
290 ASSERT_EQ(this, listener_
->params());
293 IN_PROC_BROWSER_TEST_F(SelectFileDialogExtensionBrowserTest
,
295 AddMountPoint(downloads_dir_
);
297 base::FilePath test_file
=
298 downloads_dir_
.AppendASCII("file_manager_test.html");
300 gfx::NativeWindow owning_window
= browser()->window()->GetNativeWindow();
302 // Spawn a dialog to save a file, providing a suggested path.
303 // Ensure "Save" button is enabled by waiting for notification from
304 // chrome.test.sendMessage().
305 ASSERT_NO_FATAL_FAILURE(OpenDialog(ui::SelectFileDialog::SELECT_SAVEAS_FILE
,
306 test_file
, owning_window
,
309 // Click save button.
310 CloseDialog(DIALOG_BTN_OK
, owning_window
);
312 // Listener should have been informed that the file was selected.
313 ASSERT_TRUE(listener_
->file_selected());
314 ASSERT_FALSE(listener_
->canceled());
315 ASSERT_EQ(test_file
, listener_
->path());
316 ASSERT_EQ(this, listener_
->params());
319 IN_PROC_BROWSER_TEST_F(SelectFileDialogExtensionBrowserTest
,
320 OpenSingletonTabAndCancel
) {
321 AddMountPoint(downloads_dir_
);
323 gfx::NativeWindow owning_window
= browser()->window()->GetNativeWindow();
325 ASSERT_NO_FATAL_FAILURE(OpenDialog(ui::SelectFileDialog::SELECT_OPEN_FILE
,
326 base::FilePath(), owning_window
, ""));
328 // Open a singleton tab in background.
329 chrome::NavigateParams
p(browser(), GURL("http://www.google.com"),
330 ui::PAGE_TRANSITION_LINK
);
331 p
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
332 p
.disposition
= SINGLETON_TAB
;
333 chrome::Navigate(&p
);
335 // Press cancel button.
336 CloseDialog(DIALOG_BTN_CANCEL
, owning_window
);
338 // Listener should have been informed of the cancellation.
339 ASSERT_FALSE(listener_
->file_selected());
340 ASSERT_TRUE(listener_
->canceled());
341 ASSERT_EQ(this, listener_
->params());
344 IN_PROC_BROWSER_TEST_F(SelectFileDialogExtensionBrowserTest
,
346 AddMountPoint(downloads_dir_
);
348 gfx::NativeWindow owning_window
= browser()->window()->GetNativeWindow();
350 ASSERT_NO_FATAL_FAILURE(OpenDialog(ui::SelectFileDialog::SELECT_OPEN_FILE
,
351 base::FilePath(), owning_window
, ""));
353 TryOpeningSecondDialog(owning_window
);
355 // Second dialog should not be running.
356 ASSERT_FALSE(second_dialog_
->IsRunning(owning_window
));
358 // Click cancel button.
359 CloseDialog(DIALOG_BTN_CANCEL
, owning_window
);
361 // Listener should have been informed of the cancellation.
362 ASSERT_FALSE(listener_
->file_selected());
363 ASSERT_TRUE(listener_
->canceled());
364 ASSERT_EQ(this, listener_
->params());