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/file_select_helper.h"
10 #include "base/bind.h"
11 #include "base/files/file_enumerator.h"
12 #include "base/files/file_util.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 "chrome/browser/browser_process.h"
17 #include "chrome/browser/platform_util.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/profiles/profile_manager.h"
20 #include "chrome/browser/ui/browser.h"
21 #include "chrome/browser/ui/browser_list.h"
22 #include "chrome/browser/ui/chrome_select_file_policy.h"
23 #include "chrome/grit/generated_resources.h"
24 #include "content/public/browser/browser_thread.h"
25 #include "content/public/browser/notification_details.h"
26 #include "content/public/browser/notification_source.h"
27 #include "content/public/browser/notification_types.h"
28 #include "content/public/browser/render_view_host.h"
29 #include "content/public/browser/render_widget_host_view.h"
30 #include "content/public/browser/web_contents.h"
31 #include "content/public/common/file_chooser_file_info.h"
32 #include "content/public/common/file_chooser_params.h"
33 #include "net/base/mime_util.h"
34 #include "ui/base/l10n/l10n_util.h"
35 #include "ui/shell_dialogs/selected_file_info.h"
37 #if defined(OS_CHROMEOS)
38 #include "chrome/browser/chromeos/file_manager/fileapi_util.h"
39 #include "content/public/browser/site_instance.h"
42 using content::BrowserThread
;
43 using content::FileChooserParams
;
44 using content::RenderViewHost
;
45 using content::RenderWidgetHost
;
46 using content::WebContents
;
50 // There is only one file-selection happening at any given time,
51 // so we allocate an enumeration ID for that purpose. All IDs from
52 // the renderer must start at 0 and increase.
53 const int kFileSelectEnumerationId
= -1;
55 // Converts a list of FilePaths to a list of ui::SelectedFileInfo.
56 std::vector
<ui::SelectedFileInfo
> FilePathListToSelectedFileInfoList(
57 const std::vector
<base::FilePath
>& paths
) {
58 std::vector
<ui::SelectedFileInfo
> selected_files
;
59 for (size_t i
= 0; i
< paths
.size(); ++i
) {
60 selected_files
.push_back(
61 ui::SelectedFileInfo(paths
[i
], paths
[i
]));
63 return selected_files
;
66 void DeleteFiles(const std::vector
<base::FilePath
>& paths
) {
67 for (auto& file_path
: paths
)
68 base::DeleteFile(file_path
, false);
71 bool IsValidProfile(Profile
* profile
) {
72 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
73 return g_browser_process
->profile_manager()->IsValidProfile(profile
);
78 struct FileSelectHelper::ActiveDirectoryEnumeration
{
79 ActiveDirectoryEnumeration() : rvh_(NULL
) {}
81 scoped_ptr
<DirectoryListerDispatchDelegate
> delegate_
;
82 scoped_ptr
<net::DirectoryLister
> lister_
;
84 std::vector
<base::FilePath
> results_
;
87 FileSelectHelper::FileSelectHelper(Profile
* profile
)
89 render_view_host_(NULL
),
91 select_file_dialog_(),
93 dialog_type_(ui::SelectFileDialog::SELECT_OPEN_FILE
),
94 dialog_mode_(FileChooserParams::Open
) {
97 FileSelectHelper::~FileSelectHelper() {
98 // There may be pending file dialogs, we need to tell them that we've gone
99 // away so they don't try and call back to us.
100 if (select_file_dialog_
.get())
101 select_file_dialog_
->ListenerDestroyed();
103 // Stop any pending directory enumeration, prevent a callback, and free
105 std::map
<int, ActiveDirectoryEnumeration
*>::iterator iter
;
106 for (iter
= directory_enumerations_
.begin();
107 iter
!= directory_enumerations_
.end();
109 iter
->second
->lister_
.reset();
114 void FileSelectHelper::DirectoryListerDispatchDelegate::OnListFile(
115 const net::DirectoryLister::DirectoryListerData
& data
) {
116 parent_
->OnListFile(id_
, data
);
119 void FileSelectHelper::DirectoryListerDispatchDelegate::OnListDone(int error
) {
120 parent_
->OnListDone(id_
, error
);
123 void FileSelectHelper::FileSelected(const base::FilePath
& path
,
124 int index
, void* params
) {
125 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path
, path
), index
, params
);
128 void FileSelectHelper::FileSelectedWithExtraInfo(
129 const ui::SelectedFileInfo
& file
,
132 if (IsValidProfile(profile_
))
133 profile_
->set_last_selected_directory(file
.file_path
.DirName());
135 if (!render_view_host_
) {
140 const base::FilePath
& path
= file
.local_path
;
141 if (dialog_type_
== ui::SelectFileDialog::SELECT_UPLOAD_FOLDER
) {
142 StartNewEnumeration(path
, kFileSelectEnumerationId
, render_view_host_
);
146 std::vector
<ui::SelectedFileInfo
> files
;
147 files
.push_back(file
);
149 #if defined(OS_MACOSX) && !defined(OS_IOS)
150 content::BrowserThread::PostTask(
151 content::BrowserThread::FILE_USER_BLOCKING
,
153 base::Bind(&FileSelectHelper::ProcessSelectedFilesMac
, this, files
));
155 NotifyRenderViewHostAndEnd(files
);
156 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
159 void FileSelectHelper::MultiFilesSelected(
160 const std::vector
<base::FilePath
>& files
,
162 std::vector
<ui::SelectedFileInfo
> selected_files
=
163 FilePathListToSelectedFileInfoList(files
);
165 MultiFilesSelectedWithExtraInfo(selected_files
, params
);
168 void FileSelectHelper::MultiFilesSelectedWithExtraInfo(
169 const std::vector
<ui::SelectedFileInfo
>& files
,
171 if (!files
.empty() && IsValidProfile(profile_
))
172 profile_
->set_last_selected_directory(files
[0].file_path
.DirName());
174 #if defined(OS_MACOSX) && !defined(OS_IOS)
175 content::BrowserThread::PostTask(
176 content::BrowserThread::FILE_USER_BLOCKING
,
178 base::Bind(&FileSelectHelper::ProcessSelectedFilesMac
, this, files
));
180 NotifyRenderViewHostAndEnd(files
);
181 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
184 void FileSelectHelper::FileSelectionCanceled(void* params
) {
185 NotifyRenderViewHostAndEnd(std::vector
<ui::SelectedFileInfo
>());
188 void FileSelectHelper::StartNewEnumeration(const base::FilePath
& path
,
190 RenderViewHost
* render_view_host
) {
191 scoped_ptr
<ActiveDirectoryEnumeration
> entry(new ActiveDirectoryEnumeration
);
192 entry
->rvh_
= render_view_host
;
193 entry
->delegate_
.reset(new DirectoryListerDispatchDelegate(this, request_id
));
194 entry
->lister_
.reset(new net::DirectoryLister(
195 path
, net::DirectoryLister::NO_SORT_RECURSIVE
, entry
->delegate_
.get()));
196 if (!entry
->lister_
->Start()) {
197 if (request_id
== kFileSelectEnumerationId
)
198 FileSelectionCanceled(NULL
);
200 render_view_host
->DirectoryEnumerationFinished(request_id
,
203 directory_enumerations_
[request_id
] = entry
.release();
207 void FileSelectHelper::OnListFile(
209 const net::DirectoryLister::DirectoryListerData
& data
) {
210 ActiveDirectoryEnumeration
* entry
= directory_enumerations_
[id
];
212 // Directory upload only cares about files.
213 if (data
.info
.IsDirectory())
216 entry
->results_
.push_back(data
.path
);
219 void FileSelectHelper::OnListDone(int id
, int error
) {
220 // This entry needs to be cleaned up when this function is done.
221 scoped_ptr
<ActiveDirectoryEnumeration
> entry(directory_enumerations_
[id
]);
222 directory_enumerations_
.erase(id
);
226 FileSelectionCanceled(NULL
);
230 std::vector
<ui::SelectedFileInfo
> selected_files
=
231 FilePathListToSelectedFileInfoList(entry
->results_
);
233 if (id
== kFileSelectEnumerationId
) {
234 NotifyRenderViewHostAndEnd(selected_files
);
236 entry
->rvh_
->DirectoryEnumerationFinished(id
, entry
->results_
);
237 EnumerateDirectoryEnd();
241 void FileSelectHelper::NotifyRenderViewHostAndEnd(
242 const std::vector
<ui::SelectedFileInfo
>& files
) {
243 if (!render_view_host_
) {
248 #if defined(OS_CHROMEOS)
249 if (!files
.empty()) {
250 if (!IsValidProfile(profile_
)) {
254 // Converts |files| into FileChooserFileInfo with handling of non-native
256 file_manager::util::ConvertSelectedFileInfoListToFileChooserFileInfoList(
257 file_manager::util::GetFileSystemContextForRenderViewHost(
258 profile_
, render_view_host_
),
259 web_contents_
->GetSiteInstance()->GetSiteURL(),
262 &FileSelectHelper::NotifyRenderViewHostAndEndAfterConversion
,
266 #endif // defined(OS_CHROMEOS)
268 std::vector
<content::FileChooserFileInfo
> chooser_files
;
269 for (const auto& file
: files
) {
270 content::FileChooserFileInfo chooser_file
;
271 chooser_file
.file_path
= file
.local_path
;
272 chooser_file
.display_name
= file
.display_name
;
273 chooser_files
.push_back(chooser_file
);
276 NotifyRenderViewHostAndEndAfterConversion(chooser_files
);
279 void FileSelectHelper::NotifyRenderViewHostAndEndAfterConversion(
280 const std::vector
<content::FileChooserFileInfo
>& list
) {
281 if (render_view_host_
)
282 render_view_host_
->FilesSelectedInChooser(list
, dialog_mode_
);
284 // No members should be accessed from here on.
288 void FileSelectHelper::DeleteTemporaryFiles() {
289 BrowserThread::PostTask(BrowserThread::FILE,
291 base::Bind(&DeleteFiles
, temporary_files_
));
292 temporary_files_
.clear();
295 void FileSelectHelper::CleanUpOnRenderViewHostChange() {
296 if (!temporary_files_
.empty()) {
297 DeleteTemporaryFiles();
299 // Now that the temporary files have been scheduled for deletion, there
300 // is no longer any reason to keep this instance around.
305 scoped_ptr
<ui::SelectFileDialog::FileTypeInfo
>
306 FileSelectHelper::GetFileTypesFromAcceptType(
307 const std::vector
<base::string16
>& accept_types
) {
308 scoped_ptr
<ui::SelectFileDialog::FileTypeInfo
> base_file_type(
309 new ui::SelectFileDialog::FileTypeInfo());
310 if (accept_types
.empty())
311 return base_file_type
.Pass();
313 // Create FileTypeInfo and pre-allocate for the first extension list.
314 scoped_ptr
<ui::SelectFileDialog::FileTypeInfo
> file_type(
315 new ui::SelectFileDialog::FileTypeInfo(*base_file_type
));
316 file_type
->include_all_files
= true;
317 file_type
->extensions
.resize(1);
318 std::vector
<base::FilePath::StringType
>* extensions
=
319 &file_type
->extensions
.back();
321 // Find the corresponding extensions.
322 int valid_type_count
= 0;
323 int description_id
= 0;
324 for (size_t i
= 0; i
< accept_types
.size(); ++i
) {
325 std::string ascii_type
= base::UTF16ToASCII(accept_types
[i
]);
326 if (!IsAcceptTypeValid(ascii_type
))
329 size_t old_extension_size
= extensions
->size();
330 if (ascii_type
[0] == '.') {
331 // If the type starts with a period it is assumed to be a file extension
332 // so we just have to add it to the list.
333 base::FilePath::StringType
ext(ascii_type
.begin(), ascii_type
.end());
334 extensions
->push_back(ext
.substr(1));
336 if (ascii_type
== "image/*")
337 description_id
= IDS_IMAGE_FILES
;
338 else if (ascii_type
== "audio/*")
339 description_id
= IDS_AUDIO_FILES
;
340 else if (ascii_type
== "video/*")
341 description_id
= IDS_VIDEO_FILES
;
343 net::GetExtensionsForMimeType(ascii_type
, extensions
);
346 if (extensions
->size() > old_extension_size
)
350 // If no valid extension is added, bail out.
351 if (valid_type_count
== 0)
352 return base_file_type
.Pass();
354 // Use a generic description "Custom Files" if either of the following is
356 // 1) There're multiple types specified, like "audio/*,video/*"
357 // 2) There're multiple extensions for a MIME type without parameter, like
358 // "ehtml,shtml,htm,html" for "text/html". On Windows, the select file
359 // dialog uses the first extension in the list to form the description,
360 // like "EHTML Files". This is not what we want.
361 if (valid_type_count
> 1 ||
362 (valid_type_count
== 1 && description_id
== 0 && extensions
->size() > 1))
363 description_id
= IDS_CUSTOM_FILES
;
365 if (description_id
) {
366 file_type
->extension_description_overrides
.push_back(
367 l10n_util::GetStringUTF16(description_id
));
370 return file_type
.Pass();
374 void FileSelectHelper::RunFileChooser(content::WebContents
* tab
,
375 const FileChooserParams
& params
) {
376 Profile
* profile
= Profile::FromBrowserContext(tab
->GetBrowserContext());
377 // FileSelectHelper will keep itself alive until it sends the result message.
378 scoped_refptr
<FileSelectHelper
> file_select_helper(
379 new FileSelectHelper(profile
));
380 file_select_helper
->RunFileChooser(tab
->GetRenderViewHost(), tab
, params
);
384 void FileSelectHelper::EnumerateDirectory(content::WebContents
* tab
,
386 const base::FilePath
& path
) {
387 Profile
* profile
= Profile::FromBrowserContext(tab
->GetBrowserContext());
388 // FileSelectHelper will keep itself alive until it sends the result message.
389 scoped_refptr
<FileSelectHelper
> file_select_helper(
390 new FileSelectHelper(profile
));
391 file_select_helper
->EnumerateDirectory(
392 request_id
, tab
->GetRenderViewHost(), path
);
395 void FileSelectHelper::RunFileChooser(RenderViewHost
* render_view_host
,
396 content::WebContents
* web_contents
,
397 const FileChooserParams
& params
) {
398 DCHECK(!render_view_host_
);
399 DCHECK(!web_contents_
);
400 render_view_host_
= render_view_host
;
401 web_contents_
= web_contents
;
402 notification_registrar_
.RemoveAll();
403 content::WebContentsObserver::Observe(web_contents_
);
404 notification_registrar_
.Add(
406 content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
407 content::Source
<RenderWidgetHost
>(render_view_host_
));
409 BrowserThread::PostTask(
410 BrowserThread::FILE, FROM_HERE
,
411 base::Bind(&FileSelectHelper::RunFileChooserOnFileThread
, this, params
));
413 // Because this class returns notifications to the RenderViewHost, it is
414 // difficult for callers to know how long to keep a reference to this
415 // instance. We AddRef() here to keep the instance alive after we return
416 // to the caller, until the last callback is received from the file dialog.
417 // At that point, we must call RunFileChooserEnd().
421 void FileSelectHelper::RunFileChooserOnFileThread(
422 const FileChooserParams
& params
) {
423 select_file_types_
= GetFileTypesFromAcceptType(params
.accept_types
);
424 select_file_types_
->support_drive
= !params
.need_local_path
;
426 BrowserThread::PostTask(
427 BrowserThread::UI
, FROM_HERE
,
428 base::Bind(&FileSelectHelper::RunFileChooserOnUIThread
, this, params
));
431 void FileSelectHelper::RunFileChooserOnUIThread(
432 const FileChooserParams
& params
) {
433 if (!render_view_host_
|| !web_contents_
|| !IsValidProfile(profile_
)) {
434 // If the renderer was destroyed before we started, just cancel the
440 select_file_dialog_
= ui::SelectFileDialog::Create(
441 this, new ChromeSelectFilePolicy(web_contents_
));
442 if (!select_file_dialog_
.get())
445 dialog_mode_
= params
.mode
;
446 switch (params
.mode
) {
447 case FileChooserParams::Open
:
448 dialog_type_
= ui::SelectFileDialog::SELECT_OPEN_FILE
;
450 case FileChooserParams::OpenMultiple
:
451 dialog_type_
= ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE
;
453 case FileChooserParams::UploadFolder
:
454 dialog_type_
= ui::SelectFileDialog::SELECT_UPLOAD_FOLDER
;
456 case FileChooserParams::Save
:
457 dialog_type_
= ui::SelectFileDialog::SELECT_SAVEAS_FILE
;
461 dialog_type_
= ui::SelectFileDialog::SELECT_OPEN_FILE
;
465 base::FilePath default_file_name
= params
.default_file_name
.IsAbsolute() ?
466 params
.default_file_name
:
467 profile_
->last_selected_directory().Append(params
.default_file_name
);
469 gfx::NativeWindow owning_window
=
470 platform_util::GetTopLevel(render_view_host_
->GetView()->GetNativeView());
472 #if defined(OS_ANDROID)
473 // Android needs the original MIME types and an additional capture value.
474 std::pair
<std::vector
<base::string16
>, bool> accept_types
=
475 std::make_pair(params
.accept_types
, params
.capture
);
478 select_file_dialog_
->SelectFile(
482 select_file_types_
.get(),
483 select_file_types_
.get() && !select_file_types_
->extensions
.empty()
485 : 0, // 1-based index of default extension to show.
486 base::FilePath::StringType(),
488 #if defined(OS_ANDROID)
494 select_file_types_
.reset();
497 // This method is called when we receive the last callback from the file
498 // chooser dialog. Perform any cleanup and release the reference we added
499 // in RunFileChooser().
500 void FileSelectHelper::RunFileChooserEnd() {
501 // If there are temporary files, then this instance needs to stick around
502 // until web_contents_ is destroyed, so that this instance can delete the
504 if (!temporary_files_
.empty())
507 render_view_host_
= NULL
;
508 web_contents_
= NULL
;
512 void FileSelectHelper::EnumerateDirectory(int request_id
,
513 RenderViewHost
* render_view_host
,
514 const base::FilePath
& path
) {
516 // Because this class returns notifications to the RenderViewHost, it is
517 // difficult for callers to know how long to keep a reference to this
518 // instance. We AddRef() here to keep the instance alive after we return
519 // to the caller, until the last callback is received from the enumeration
520 // code. At that point, we must call EnumerateDirectoryEnd().
522 StartNewEnumeration(path
, request_id
, render_view_host
);
525 // This method is called when we receive the last callback from the enumeration
526 // code. Perform any cleanup and release the reference we added in
527 // EnumerateDirectory().
528 void FileSelectHelper::EnumerateDirectoryEnd() {
532 void FileSelectHelper::Observe(int type
,
533 const content::NotificationSource
& source
,
534 const content::NotificationDetails
& details
) {
536 case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
537 DCHECK(content::Source
<RenderWidgetHost
>(source
).ptr() ==
539 render_view_host_
= NULL
;
547 void FileSelectHelper::RenderViewHostChanged(RenderViewHost
* old_host
,
548 RenderViewHost
* new_host
) {
549 CleanUpOnRenderViewHostChange();
552 void FileSelectHelper::WebContentsDestroyed() {
553 web_contents_
= nullptr;
554 CleanUpOnRenderViewHostChange();
558 bool FileSelectHelper::IsAcceptTypeValid(const std::string
& accept_type
) {
559 // TODO(raymes): This only does some basic checks, extend to test more cases.
560 // A 1 character accept type will always be invalid (either a "." in the case
561 // of an extension or a "/" in the case of a MIME type).
563 if (accept_type
.length() <= 1 ||
564 base::StringToLowerASCII(accept_type
) != accept_type
||
565 base::TrimWhitespaceASCII(accept_type
, base::TRIM_ALL
, &unused
) !=