Componentize HistoryURLProvider/ScoredHistoryMatch.
[chromium-blink-merge.git] / chrome / browser / file_select_helper.cc
blob6d88afbf6de08641435885314e7c1e1ac3353126
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"
7 #include <string>
8 #include <utility>
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/storage_partition.h"
31 #include "content/public/browser/web_contents.h"
32 #include "content/public/common/file_chooser_file_info.h"
33 #include "content/public/common/file_chooser_params.h"
34 #include "net/base/mime_util.h"
35 #include "ui/base/l10n/l10n_util.h"
36 #include "ui/shell_dialogs/selected_file_info.h"
38 #if defined(OS_CHROMEOS)
39 #include "chrome/browser/chromeos/file_manager/fileapi_util.h"
40 #include "content/public/browser/site_instance.h"
41 #endif
43 using content::BrowserThread;
44 using content::FileChooserParams;
45 using content::RenderViewHost;
46 using content::RenderWidgetHost;
47 using content::WebContents;
49 namespace {
51 // There is only one file-selection happening at any given time,
52 // so we allocate an enumeration ID for that purpose. All IDs from
53 // the renderer must start at 0 and increase.
54 const int kFileSelectEnumerationId = -1;
56 // Converts a list of FilePaths to a list of ui::SelectedFileInfo.
57 std::vector<ui::SelectedFileInfo> FilePathListToSelectedFileInfoList(
58 const std::vector<base::FilePath>& paths) {
59 std::vector<ui::SelectedFileInfo> selected_files;
60 for (size_t i = 0; i < paths.size(); ++i) {
61 selected_files.push_back(
62 ui::SelectedFileInfo(paths[i], paths[i]));
64 return selected_files;
67 void DeleteFiles(const std::vector<base::FilePath>& paths) {
68 for (auto& file_path : paths)
69 base::DeleteFile(file_path, false);
72 bool IsValidProfile(Profile* profile) {
73 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
74 return g_browser_process->profile_manager()->IsValidProfile(profile);
77 } // namespace
79 struct FileSelectHelper::ActiveDirectoryEnumeration {
80 ActiveDirectoryEnumeration() : rvh_(NULL) {}
82 scoped_ptr<DirectoryListerDispatchDelegate> delegate_;
83 scoped_ptr<net::DirectoryLister> lister_;
84 RenderViewHost* rvh_;
85 std::vector<base::FilePath> results_;
88 FileSelectHelper::FileSelectHelper(Profile* profile)
89 : profile_(profile),
90 render_view_host_(NULL),
91 web_contents_(NULL),
92 select_file_dialog_(),
93 select_file_types_(),
94 dialog_type_(ui::SelectFileDialog::SELECT_OPEN_FILE),
95 dialog_mode_(FileChooserParams::Open) {
98 FileSelectHelper::~FileSelectHelper() {
99 // There may be pending file dialogs, we need to tell them that we've gone
100 // away so they don't try and call back to us.
101 if (select_file_dialog_.get())
102 select_file_dialog_->ListenerDestroyed();
104 // Stop any pending directory enumeration, prevent a callback, and free
105 // allocated memory.
106 std::map<int, ActiveDirectoryEnumeration*>::iterator iter;
107 for (iter = directory_enumerations_.begin();
108 iter != directory_enumerations_.end();
109 ++iter) {
110 iter->second->lister_.reset();
111 delete iter->second;
115 void FileSelectHelper::DirectoryListerDispatchDelegate::OnListFile(
116 const net::DirectoryLister::DirectoryListerData& data) {
117 parent_->OnListFile(id_, data);
120 void FileSelectHelper::DirectoryListerDispatchDelegate::OnListDone(int error) {
121 parent_->OnListDone(id_, error);
124 void FileSelectHelper::FileSelected(const base::FilePath& path,
125 int index, void* params) {
126 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
129 void FileSelectHelper::FileSelectedWithExtraInfo(
130 const ui::SelectedFileInfo& file,
131 int index,
132 void* params) {
133 if (IsValidProfile(profile_))
134 profile_->set_last_selected_directory(file.file_path.DirName());
136 if (!render_view_host_) {
137 RunFileChooserEnd();
138 return;
141 const base::FilePath& path = file.local_path;
142 if (dialog_type_ == ui::SelectFileDialog::SELECT_UPLOAD_FOLDER) {
143 StartNewEnumeration(path, kFileSelectEnumerationId, render_view_host_);
144 return;
147 std::vector<ui::SelectedFileInfo> files;
148 files.push_back(file);
150 #if defined(OS_MACOSX) && !defined(OS_IOS)
151 content::BrowserThread::PostTask(
152 content::BrowserThread::FILE_USER_BLOCKING,
153 FROM_HERE,
154 base::Bind(&FileSelectHelper::ProcessSelectedFilesMac, this, files));
155 #else
156 NotifyRenderViewHostAndEnd(files);
157 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
160 void FileSelectHelper::MultiFilesSelected(
161 const std::vector<base::FilePath>& files,
162 void* params) {
163 std::vector<ui::SelectedFileInfo> selected_files =
164 FilePathListToSelectedFileInfoList(files);
166 MultiFilesSelectedWithExtraInfo(selected_files, params);
169 void FileSelectHelper::MultiFilesSelectedWithExtraInfo(
170 const std::vector<ui::SelectedFileInfo>& files,
171 void* params) {
172 if (!files.empty() && IsValidProfile(profile_))
173 profile_->set_last_selected_directory(files[0].file_path.DirName());
175 #if defined(OS_MACOSX) && !defined(OS_IOS)
176 content::BrowserThread::PostTask(
177 content::BrowserThread::FILE_USER_BLOCKING,
178 FROM_HERE,
179 base::Bind(&FileSelectHelper::ProcessSelectedFilesMac, this, files));
180 #else
181 NotifyRenderViewHostAndEnd(files);
182 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
185 void FileSelectHelper::FileSelectionCanceled(void* params) {
186 NotifyRenderViewHostAndEnd(std::vector<ui::SelectedFileInfo>());
189 void FileSelectHelper::StartNewEnumeration(const base::FilePath& path,
190 int request_id,
191 RenderViewHost* render_view_host) {
192 scoped_ptr<ActiveDirectoryEnumeration> entry(new ActiveDirectoryEnumeration);
193 entry->rvh_ = render_view_host;
194 entry->delegate_.reset(new DirectoryListerDispatchDelegate(this, request_id));
195 entry->lister_.reset(new net::DirectoryLister(
196 path, net::DirectoryLister::NO_SORT_RECURSIVE, entry->delegate_.get()));
197 if (!entry->lister_->Start()) {
198 if (request_id == kFileSelectEnumerationId)
199 FileSelectionCanceled(NULL);
200 else
201 render_view_host->DirectoryEnumerationFinished(request_id,
202 entry->results_);
203 } else {
204 directory_enumerations_[request_id] = entry.release();
208 void FileSelectHelper::OnListFile(
209 int id,
210 const net::DirectoryLister::DirectoryListerData& data) {
211 ActiveDirectoryEnumeration* entry = directory_enumerations_[id];
213 // Directory upload only cares about files.
214 if (data.info.IsDirectory())
215 return;
217 entry->results_.push_back(data.path);
220 void FileSelectHelper::OnListDone(int id, int error) {
221 // This entry needs to be cleaned up when this function is done.
222 scoped_ptr<ActiveDirectoryEnumeration> entry(directory_enumerations_[id]);
223 directory_enumerations_.erase(id);
224 if (!entry->rvh_)
225 return;
226 if (error) {
227 FileSelectionCanceled(NULL);
228 return;
231 std::vector<ui::SelectedFileInfo> selected_files =
232 FilePathListToSelectedFileInfoList(entry->results_);
234 if (id == kFileSelectEnumerationId) {
235 NotifyRenderViewHostAndEnd(selected_files);
236 } else {
237 entry->rvh_->DirectoryEnumerationFinished(id, entry->results_);
238 EnumerateDirectoryEnd();
242 void FileSelectHelper::NotifyRenderViewHostAndEnd(
243 const std::vector<ui::SelectedFileInfo>& files) {
244 if (!render_view_host_) {
245 RunFileChooserEnd();
246 return;
249 #if defined(OS_CHROMEOS)
250 if (!files.empty()) {
251 if (!IsValidProfile(profile_)) {
252 RunFileChooserEnd();
253 return;
255 // Converts |files| into FileChooserFileInfo with handling of non-native
256 // files.
257 storage::FileSystemContext* file_system_context =
258 content::BrowserContext::GetStoragePartition(
259 profile_, render_view_host_->GetSiteInstance())->
260 GetFileSystemContext();
261 file_manager::util::ConvertSelectedFileInfoListToFileChooserFileInfoList(
262 file_system_context,
263 web_contents_->GetSiteInstance()->GetSiteURL(),
264 files,
265 base::Bind(
266 &FileSelectHelper::NotifyRenderViewHostAndEndAfterConversion,
267 this));
268 return;
270 #endif // defined(OS_CHROMEOS)
272 std::vector<content::FileChooserFileInfo> chooser_files;
273 for (const auto& file : files) {
274 content::FileChooserFileInfo chooser_file;
275 chooser_file.file_path = file.local_path;
276 chooser_file.display_name = file.display_name;
277 chooser_files.push_back(chooser_file);
280 NotifyRenderViewHostAndEndAfterConversion(chooser_files);
283 void FileSelectHelper::NotifyRenderViewHostAndEndAfterConversion(
284 const std::vector<content::FileChooserFileInfo>& list) {
285 if (render_view_host_)
286 render_view_host_->FilesSelectedInChooser(list, dialog_mode_);
288 // No members should be accessed from here on.
289 RunFileChooserEnd();
292 void FileSelectHelper::DeleteTemporaryFiles() {
293 BrowserThread::PostTask(BrowserThread::FILE,
294 FROM_HERE,
295 base::Bind(&DeleteFiles, temporary_files_));
296 temporary_files_.clear();
299 void FileSelectHelper::CleanUpOnRenderViewHostChange() {
300 if (!temporary_files_.empty()) {
301 DeleteTemporaryFiles();
303 // Now that the temporary files have been scheduled for deletion, there
304 // is no longer any reason to keep this instance around.
305 Release();
309 scoped_ptr<ui::SelectFileDialog::FileTypeInfo>
310 FileSelectHelper::GetFileTypesFromAcceptType(
311 const std::vector<base::string16>& accept_types) {
312 scoped_ptr<ui::SelectFileDialog::FileTypeInfo> base_file_type(
313 new ui::SelectFileDialog::FileTypeInfo());
314 if (accept_types.empty())
315 return base_file_type.Pass();
317 // Create FileTypeInfo and pre-allocate for the first extension list.
318 scoped_ptr<ui::SelectFileDialog::FileTypeInfo> file_type(
319 new ui::SelectFileDialog::FileTypeInfo(*base_file_type));
320 file_type->include_all_files = true;
321 file_type->extensions.resize(1);
322 std::vector<base::FilePath::StringType>* extensions =
323 &file_type->extensions.back();
325 // Find the corresponding extensions.
326 int valid_type_count = 0;
327 int description_id = 0;
328 for (size_t i = 0; i < accept_types.size(); ++i) {
329 std::string ascii_type = base::UTF16ToASCII(accept_types[i]);
330 if (!IsAcceptTypeValid(ascii_type))
331 continue;
333 size_t old_extension_size = extensions->size();
334 if (ascii_type[0] == '.') {
335 // If the type starts with a period it is assumed to be a file extension
336 // so we just have to add it to the list.
337 base::FilePath::StringType ext(ascii_type.begin(), ascii_type.end());
338 extensions->push_back(ext.substr(1));
339 } else {
340 if (ascii_type == "image/*")
341 description_id = IDS_IMAGE_FILES;
342 else if (ascii_type == "audio/*")
343 description_id = IDS_AUDIO_FILES;
344 else if (ascii_type == "video/*")
345 description_id = IDS_VIDEO_FILES;
347 net::GetExtensionsForMimeType(ascii_type, extensions);
350 if (extensions->size() > old_extension_size)
351 valid_type_count++;
354 // If no valid extension is added, bail out.
355 if (valid_type_count == 0)
356 return base_file_type.Pass();
358 // Use a generic description "Custom Files" if either of the following is
359 // true:
360 // 1) There're multiple types specified, like "audio/*,video/*"
361 // 2) There're multiple extensions for a MIME type without parameter, like
362 // "ehtml,shtml,htm,html" for "text/html". On Windows, the select file
363 // dialog uses the first extension in the list to form the description,
364 // like "EHTML Files". This is not what we want.
365 if (valid_type_count > 1 ||
366 (valid_type_count == 1 && description_id == 0 && extensions->size() > 1))
367 description_id = IDS_CUSTOM_FILES;
369 if (description_id) {
370 file_type->extension_description_overrides.push_back(
371 l10n_util::GetStringUTF16(description_id));
374 return file_type.Pass();
377 // static
378 void FileSelectHelper::RunFileChooser(content::WebContents* tab,
379 const FileChooserParams& params) {
380 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
381 // FileSelectHelper will keep itself alive until it sends the result message.
382 scoped_refptr<FileSelectHelper> file_select_helper(
383 new FileSelectHelper(profile));
384 file_select_helper->RunFileChooser(tab->GetRenderViewHost(), tab, params);
387 // static
388 void FileSelectHelper::EnumerateDirectory(content::WebContents* tab,
389 int request_id,
390 const base::FilePath& path) {
391 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
392 // FileSelectHelper will keep itself alive until it sends the result message.
393 scoped_refptr<FileSelectHelper> file_select_helper(
394 new FileSelectHelper(profile));
395 file_select_helper->EnumerateDirectory(
396 request_id, tab->GetRenderViewHost(), path);
399 void FileSelectHelper::RunFileChooser(RenderViewHost* render_view_host,
400 content::WebContents* web_contents,
401 const FileChooserParams& params) {
402 DCHECK(!render_view_host_);
403 DCHECK(!web_contents_);
404 render_view_host_ = render_view_host;
405 web_contents_ = web_contents;
406 notification_registrar_.RemoveAll();
407 content::WebContentsObserver::Observe(web_contents_);
408 notification_registrar_.Add(
409 this,
410 content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
411 content::Source<RenderWidgetHost>(render_view_host_));
413 BrowserThread::PostTask(
414 BrowserThread::FILE, FROM_HERE,
415 base::Bind(&FileSelectHelper::RunFileChooserOnFileThread, this, params));
417 // Because this class returns notifications to the RenderViewHost, it is
418 // difficult for callers to know how long to keep a reference to this
419 // instance. We AddRef() here to keep the instance alive after we return
420 // to the caller, until the last callback is received from the file dialog.
421 // At that point, we must call RunFileChooserEnd().
422 AddRef();
425 void FileSelectHelper::RunFileChooserOnFileThread(
426 const FileChooserParams& params) {
427 select_file_types_ = GetFileTypesFromAcceptType(params.accept_types);
428 select_file_types_->support_drive = !params.need_local_path;
430 BrowserThread::PostTask(
431 BrowserThread::UI, FROM_HERE,
432 base::Bind(&FileSelectHelper::RunFileChooserOnUIThread, this, params));
435 void FileSelectHelper::RunFileChooserOnUIThread(
436 const FileChooserParams& params) {
437 if (!render_view_host_ || !web_contents_ || !IsValidProfile(profile_)) {
438 // If the renderer was destroyed before we started, just cancel the
439 // operation.
440 RunFileChooserEnd();
441 return;
444 select_file_dialog_ = ui::SelectFileDialog::Create(
445 this, new ChromeSelectFilePolicy(web_contents_));
446 if (!select_file_dialog_.get())
447 return;
449 dialog_mode_ = params.mode;
450 switch (params.mode) {
451 case FileChooserParams::Open:
452 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_FILE;
453 break;
454 case FileChooserParams::OpenMultiple:
455 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE;
456 break;
457 case FileChooserParams::UploadFolder:
458 dialog_type_ = ui::SelectFileDialog::SELECT_UPLOAD_FOLDER;
459 break;
460 case FileChooserParams::Save:
461 dialog_type_ = ui::SelectFileDialog::SELECT_SAVEAS_FILE;
462 break;
463 default:
464 // Prevent warning.
465 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_FILE;
466 NOTREACHED();
469 base::FilePath default_file_name = params.default_file_name.IsAbsolute() ?
470 params.default_file_name :
471 profile_->last_selected_directory().Append(params.default_file_name);
473 gfx::NativeWindow owning_window =
474 platform_util::GetTopLevel(render_view_host_->GetView()->GetNativeView());
476 #if defined(OS_ANDROID)
477 // Android needs the original MIME types and an additional capture value.
478 std::pair<std::vector<base::string16>, bool> accept_types =
479 std::make_pair(params.accept_types, params.capture);
480 #endif
482 select_file_dialog_->SelectFile(
483 dialog_type_,
484 params.title,
485 default_file_name,
486 select_file_types_.get(),
487 select_file_types_.get() && !select_file_types_->extensions.empty()
489 : 0, // 1-based index of default extension to show.
490 base::FilePath::StringType(),
491 owning_window,
492 #if defined(OS_ANDROID)
493 &accept_types);
494 #else
495 NULL);
496 #endif
498 select_file_types_.reset();
501 // This method is called when we receive the last callback from the file
502 // chooser dialog. Perform any cleanup and release the reference we added
503 // in RunFileChooser().
504 void FileSelectHelper::RunFileChooserEnd() {
505 // If there are temporary files, then this instance needs to stick around
506 // until web_contents_ is destroyed, so that this instance can delete the
507 // temporary files.
508 if (!temporary_files_.empty())
509 return;
511 render_view_host_ = NULL;
512 web_contents_ = NULL;
513 Release();
516 void FileSelectHelper::EnumerateDirectory(int request_id,
517 RenderViewHost* render_view_host,
518 const base::FilePath& path) {
520 // Because this class returns notifications to the RenderViewHost, it is
521 // difficult for callers to know how long to keep a reference to this
522 // instance. We AddRef() here to keep the instance alive after we return
523 // to the caller, until the last callback is received from the enumeration
524 // code. At that point, we must call EnumerateDirectoryEnd().
525 AddRef();
526 StartNewEnumeration(path, request_id, render_view_host);
529 // This method is called when we receive the last callback from the enumeration
530 // code. Perform any cleanup and release the reference we added in
531 // EnumerateDirectory().
532 void FileSelectHelper::EnumerateDirectoryEnd() {
533 Release();
536 void FileSelectHelper::Observe(int type,
537 const content::NotificationSource& source,
538 const content::NotificationDetails& details) {
539 switch (type) {
540 case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
541 DCHECK(content::Source<RenderWidgetHost>(source).ptr() ==
542 render_view_host_);
543 render_view_host_ = NULL;
544 break;
546 default:
547 NOTREACHED();
551 void FileSelectHelper::RenderViewHostChanged(RenderViewHost* old_host,
552 RenderViewHost* new_host) {
553 CleanUpOnRenderViewHostChange();
556 void FileSelectHelper::WebContentsDestroyed() {
557 web_contents_ = nullptr;
558 CleanUpOnRenderViewHostChange();
561 // static
562 bool FileSelectHelper::IsAcceptTypeValid(const std::string& accept_type) {
563 // TODO(raymes): This only does some basic checks, extend to test more cases.
564 // A 1 character accept type will always be invalid (either a "." in the case
565 // of an extension or a "/" in the case of a MIME type).
566 std::string unused;
567 if (accept_type.length() <= 1 ||
568 base::StringToLowerASCII(accept_type) != accept_type ||
569 base::TrimWhitespaceASCII(accept_type, base::TRIM_ALL, &unused) !=
570 base::TRIM_NONE) {
571 return false;
573 return true;