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(path
,
196 net::DirectoryLister::NO_SORT
,
197 entry
->delegate_
.get()));
198 if (!entry
->lister_
->Start()) {
199 if (request_id
== kFileSelectEnumerationId
)
200 FileSelectionCanceled(NULL
);
202 render_view_host
->DirectoryEnumerationFinished(request_id
,
205 directory_enumerations_
[request_id
] = entry
.release();
209 void FileSelectHelper::OnListFile(
211 const net::DirectoryLister::DirectoryListerData
& data
) {
212 ActiveDirectoryEnumeration
* entry
= directory_enumerations_
[id
];
214 // Directory upload only cares about files.
215 if (data
.info
.IsDirectory())
218 entry
->results_
.push_back(data
.path
);
221 void FileSelectHelper::OnListDone(int id
, int error
) {
222 // This entry needs to be cleaned up when this function is done.
223 scoped_ptr
<ActiveDirectoryEnumeration
> entry(directory_enumerations_
[id
]);
224 directory_enumerations_
.erase(id
);
228 FileSelectionCanceled(NULL
);
232 std::vector
<ui::SelectedFileInfo
> selected_files
=
233 FilePathListToSelectedFileInfoList(entry
->results_
);
235 if (id
== kFileSelectEnumerationId
) {
236 NotifyRenderViewHostAndEnd(selected_files
);
238 entry
->rvh_
->DirectoryEnumerationFinished(id
, entry
->results_
);
239 EnumerateDirectoryEnd();
243 void FileSelectHelper::NotifyRenderViewHostAndEnd(
244 const std::vector
<ui::SelectedFileInfo
>& files
) {
245 if (!render_view_host_
) {
250 #if defined(OS_CHROMEOS)
251 if (!files
.empty()) {
252 if (!IsValidProfile(profile_
)) {
256 // Converts |files| into FileChooserFileInfo with handling of non-native
258 file_manager::util::ConvertSelectedFileInfoListToFileChooserFileInfoList(
259 file_manager::util::GetFileSystemContextForRenderViewHost(
260 profile_
, render_view_host_
),
261 web_contents_
->GetSiteInstance()->GetSiteURL(),
264 &FileSelectHelper::NotifyRenderViewHostAndEndAfterConversion
,
268 #endif // defined(OS_CHROMEOS)
270 std::vector
<content::FileChooserFileInfo
> chooser_files
;
271 for (const auto& file
: files
) {
272 content::FileChooserFileInfo chooser_file
;
273 chooser_file
.file_path
= file
.local_path
;
274 chooser_file
.display_name
= file
.display_name
;
275 chooser_files
.push_back(chooser_file
);
278 NotifyRenderViewHostAndEndAfterConversion(chooser_files
);
281 void FileSelectHelper::NotifyRenderViewHostAndEndAfterConversion(
282 const std::vector
<content::FileChooserFileInfo
>& list
) {
283 if (render_view_host_
)
284 render_view_host_
->FilesSelectedInChooser(list
, dialog_mode_
);
286 // No members should be accessed from here on.
290 void FileSelectHelper::DeleteTemporaryFiles() {
291 BrowserThread::PostTask(BrowserThread::FILE,
293 base::Bind(&DeleteFiles
, temporary_files_
));
294 temporary_files_
.clear();
297 scoped_ptr
<ui::SelectFileDialog::FileTypeInfo
>
298 FileSelectHelper::GetFileTypesFromAcceptType(
299 const std::vector
<base::string16
>& accept_types
) {
300 scoped_ptr
<ui::SelectFileDialog::FileTypeInfo
> base_file_type(
301 new ui::SelectFileDialog::FileTypeInfo());
302 if (accept_types
.empty())
303 return base_file_type
.Pass();
305 // Create FileTypeInfo and pre-allocate for the first extension list.
306 scoped_ptr
<ui::SelectFileDialog::FileTypeInfo
> file_type(
307 new ui::SelectFileDialog::FileTypeInfo(*base_file_type
));
308 file_type
->include_all_files
= true;
309 file_type
->extensions
.resize(1);
310 std::vector
<base::FilePath::StringType
>* extensions
=
311 &file_type
->extensions
.back();
313 // Find the corresponding extensions.
314 int valid_type_count
= 0;
315 int description_id
= 0;
316 for (size_t i
= 0; i
< accept_types
.size(); ++i
) {
317 std::string ascii_type
= base::UTF16ToASCII(accept_types
[i
]);
318 if (!IsAcceptTypeValid(ascii_type
))
321 size_t old_extension_size
= extensions
->size();
322 if (ascii_type
[0] == '.') {
323 // If the type starts with a period it is assumed to be a file extension
324 // so we just have to add it to the list.
325 base::FilePath::StringType
ext(ascii_type
.begin(), ascii_type
.end());
326 extensions
->push_back(ext
.substr(1));
328 if (ascii_type
== "image/*")
329 description_id
= IDS_IMAGE_FILES
;
330 else if (ascii_type
== "audio/*")
331 description_id
= IDS_AUDIO_FILES
;
332 else if (ascii_type
== "video/*")
333 description_id
= IDS_VIDEO_FILES
;
335 net::GetExtensionsForMimeType(ascii_type
, extensions
);
338 if (extensions
->size() > old_extension_size
)
342 // If no valid extension is added, bail out.
343 if (valid_type_count
== 0)
344 return base_file_type
.Pass();
346 // Use a generic description "Custom Files" if either of the following is
348 // 1) There're multiple types specified, like "audio/*,video/*"
349 // 2) There're multiple extensions for a MIME type without parameter, like
350 // "ehtml,shtml,htm,html" for "text/html". On Windows, the select file
351 // dialog uses the first extension in the list to form the description,
352 // like "EHTML Files". This is not what we want.
353 if (valid_type_count
> 1 ||
354 (valid_type_count
== 1 && description_id
== 0 && extensions
->size() > 1))
355 description_id
= IDS_CUSTOM_FILES
;
357 if (description_id
) {
358 file_type
->extension_description_overrides
.push_back(
359 l10n_util::GetStringUTF16(description_id
));
362 return file_type
.Pass();
366 void FileSelectHelper::RunFileChooser(content::WebContents
* tab
,
367 const FileChooserParams
& params
) {
368 Profile
* profile
= Profile::FromBrowserContext(tab
->GetBrowserContext());
369 // FileSelectHelper will keep itself alive until it sends the result message.
370 scoped_refptr
<FileSelectHelper
> file_select_helper(
371 new FileSelectHelper(profile
));
372 file_select_helper
->RunFileChooser(tab
->GetRenderViewHost(), tab
, params
);
376 void FileSelectHelper::EnumerateDirectory(content::WebContents
* tab
,
378 const base::FilePath
& path
) {
379 Profile
* profile
= Profile::FromBrowserContext(tab
->GetBrowserContext());
380 // FileSelectHelper will keep itself alive until it sends the result message.
381 scoped_refptr
<FileSelectHelper
> file_select_helper(
382 new FileSelectHelper(profile
));
383 file_select_helper
->EnumerateDirectory(
384 request_id
, tab
->GetRenderViewHost(), path
);
387 void FileSelectHelper::RunFileChooser(RenderViewHost
* render_view_host
,
388 content::WebContents
* web_contents
,
389 const FileChooserParams
& params
) {
390 DCHECK(!render_view_host_
);
391 DCHECK(!web_contents_
);
392 render_view_host_
= render_view_host
;
393 web_contents_
= web_contents
;
394 notification_registrar_
.RemoveAll();
395 notification_registrar_
.Add(this,
396 content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED
,
397 content::Source
<WebContents
>(web_contents_
));
398 notification_registrar_
.Add(
400 content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
401 content::Source
<RenderWidgetHost
>(render_view_host_
));
402 notification_registrar_
.Add(
403 this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
404 content::Source
<WebContents
>(web_contents_
));
406 BrowserThread::PostTask(
407 BrowserThread::FILE, FROM_HERE
,
408 base::Bind(&FileSelectHelper::RunFileChooserOnFileThread
, this, params
));
410 // Because this class returns notifications to the RenderViewHost, it is
411 // difficult for callers to know how long to keep a reference to this
412 // instance. We AddRef() here to keep the instance alive after we return
413 // to the caller, until the last callback is received from the file dialog.
414 // At that point, we must call RunFileChooserEnd().
418 void FileSelectHelper::RunFileChooserOnFileThread(
419 const FileChooserParams
& params
) {
420 select_file_types_
= GetFileTypesFromAcceptType(params
.accept_types
);
421 select_file_types_
->support_drive
= !params
.need_local_path
;
423 BrowserThread::PostTask(
424 BrowserThread::UI
, FROM_HERE
,
425 base::Bind(&FileSelectHelper::RunFileChooserOnUIThread
, this, params
));
428 void FileSelectHelper::RunFileChooserOnUIThread(
429 const FileChooserParams
& params
) {
430 if (!render_view_host_
|| !web_contents_
|| !IsValidProfile(profile_
)) {
431 // If the renderer was destroyed before we started, just cancel the
437 select_file_dialog_
= ui::SelectFileDialog::Create(
438 this, new ChromeSelectFilePolicy(web_contents_
));
439 if (!select_file_dialog_
.get())
442 dialog_mode_
= params
.mode
;
443 switch (params
.mode
) {
444 case FileChooserParams::Open
:
445 dialog_type_
= ui::SelectFileDialog::SELECT_OPEN_FILE
;
447 case FileChooserParams::OpenMultiple
:
448 dialog_type_
= ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE
;
450 case FileChooserParams::UploadFolder
:
451 dialog_type_
= ui::SelectFileDialog::SELECT_UPLOAD_FOLDER
;
453 case FileChooserParams::Save
:
454 dialog_type_
= ui::SelectFileDialog::SELECT_SAVEAS_FILE
;
458 dialog_type_
= ui::SelectFileDialog::SELECT_OPEN_FILE
;
462 base::FilePath default_file_name
= params
.default_file_name
.IsAbsolute() ?
463 params
.default_file_name
:
464 profile_
->last_selected_directory().Append(params
.default_file_name
);
466 gfx::NativeWindow owning_window
=
467 platform_util::GetTopLevel(render_view_host_
->GetView()->GetNativeView());
469 #if defined(OS_ANDROID)
470 // Android needs the original MIME types and an additional capture value.
471 std::pair
<std::vector
<base::string16
>, bool> accept_types
=
472 std::make_pair(params
.accept_types
, params
.capture
);
475 select_file_dialog_
->SelectFile(
479 select_file_types_
.get(),
480 select_file_types_
.get() && !select_file_types_
->extensions
.empty()
482 : 0, // 1-based index of default extension to show.
483 base::FilePath::StringType(),
485 #if defined(OS_ANDROID)
491 select_file_types_
.reset();
494 // This method is called when we receive the last callback from the file
495 // chooser dialog. Perform any cleanup and release the reference we added
496 // in RunFileChooser().
497 void FileSelectHelper::RunFileChooserEnd() {
498 // If there are temporary files, then this instance needs to stick around
499 // until web_contents_ is destroyed, so that this instance can delete the
501 if (!temporary_files_
.empty())
504 render_view_host_
= NULL
;
505 web_contents_
= NULL
;
509 void FileSelectHelper::EnumerateDirectory(int request_id
,
510 RenderViewHost
* render_view_host
,
511 const base::FilePath
& path
) {
513 // Because this class returns notifications to the RenderViewHost, it is
514 // difficult for callers to know how long to keep a reference to this
515 // instance. We AddRef() here to keep the instance alive after we return
516 // to the caller, until the last callback is received from the enumeration
517 // code. At that point, we must call EnumerateDirectoryEnd().
519 StartNewEnumeration(path
, request_id
, render_view_host
);
522 // This method is called when we receive the last callback from the enumeration
523 // code. Perform any cleanup and release the reference we added in
524 // EnumerateDirectory().
525 void FileSelectHelper::EnumerateDirectoryEnd() {
529 void FileSelectHelper::Observe(int type
,
530 const content::NotificationSource
& source
,
531 const content::NotificationDetails
& details
) {
533 case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
534 DCHECK(content::Source
<RenderWidgetHost
>(source
).ptr() ==
536 render_view_host_
= NULL
;
540 case content::NOTIFICATION_WEB_CONTENTS_DESTROYED
: {
541 DCHECK(content::Source
<WebContents
>(source
).ptr() == web_contents_
);
542 web_contents_
= NULL
;
545 // Intentional fall through.
546 case content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED
:
547 if (!temporary_files_
.empty()) {
548 DeleteTemporaryFiles();
550 // Now that the temporary files have been scheduled for deletion, there
551 // is no longer any reason to keep this instance around.
563 bool FileSelectHelper::IsAcceptTypeValid(const std::string
& accept_type
) {
564 // TODO(raymes): This only does some basic checks, extend to test more cases.
565 // A 1 character accept type will always be invalid (either a "." in the case
566 // of an extension or a "/" in the case of a MIME type).
568 if (accept_type
.length() <= 1 ||
569 base::StringToLowerASCII(accept_type
) != accept_type
||
570 base::TrimWhitespaceASCII(accept_type
, base::TRIM_ALL
, &unused
) !=