Use app list item shadow for app list folders.
[chromium-blink-merge.git] / chrome / browser / file_select_helper.cc
blob92f3b96796bb70658df62f0bb047db15a7a5e464
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/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"
40 #endif
42 using content::BrowserThread;
43 using content::FileChooserParams;
44 using content::RenderViewHost;
45 using content::RenderWidgetHost;
46 using content::WebContents;
48 namespace {
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);
76 } // namespace
78 struct FileSelectHelper::ActiveDirectoryEnumeration {
79 ActiveDirectoryEnumeration() : rvh_(NULL) {}
81 scoped_ptr<DirectoryListerDispatchDelegate> delegate_;
82 scoped_ptr<net::DirectoryLister> lister_;
83 RenderViewHost* rvh_;
84 std::vector<base::FilePath> results_;
87 FileSelectHelper::FileSelectHelper(Profile* profile)
88 : profile_(profile),
89 render_view_host_(NULL),
90 web_contents_(NULL),
91 select_file_dialog_(),
92 select_file_types_(),
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
104 // allocated memory.
105 std::map<int, ActiveDirectoryEnumeration*>::iterator iter;
106 for (iter = directory_enumerations_.begin();
107 iter != directory_enumerations_.end();
108 ++iter) {
109 iter->second->lister_.reset();
110 delete iter->second;
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,
130 int index,
131 void* params) {
132 if (IsValidProfile(profile_))
133 profile_->set_last_selected_directory(file.file_path.DirName());
135 if (!render_view_host_) {
136 RunFileChooserEnd();
137 return;
140 const base::FilePath& path = file.local_path;
141 if (dialog_type_ == ui::SelectFileDialog::SELECT_UPLOAD_FOLDER) {
142 StartNewEnumeration(path, kFileSelectEnumerationId, render_view_host_);
143 return;
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,
152 FROM_HERE,
153 base::Bind(&FileSelectHelper::ProcessSelectedFilesMac, this, files));
154 #else
155 NotifyRenderViewHostAndEnd(files);
156 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
159 void FileSelectHelper::MultiFilesSelected(
160 const std::vector<base::FilePath>& files,
161 void* params) {
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,
170 void* params) {
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,
177 FROM_HERE,
178 base::Bind(&FileSelectHelper::ProcessSelectedFilesMac, this, files));
179 #else
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,
189 int request_id,
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);
199 else
200 render_view_host->DirectoryEnumerationFinished(request_id,
201 entry->results_);
202 } else {
203 directory_enumerations_[request_id] = entry.release();
207 void FileSelectHelper::OnListFile(
208 int id,
209 const net::DirectoryLister::DirectoryListerData& data) {
210 ActiveDirectoryEnumeration* entry = directory_enumerations_[id];
212 // Directory upload only cares about files.
213 if (data.info.IsDirectory())
214 return;
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);
223 if (!entry->rvh_)
224 return;
225 if (error) {
226 FileSelectionCanceled(NULL);
227 return;
230 std::vector<ui::SelectedFileInfo> selected_files =
231 FilePathListToSelectedFileInfoList(entry->results_);
233 if (id == kFileSelectEnumerationId) {
234 NotifyRenderViewHostAndEnd(selected_files);
235 } else {
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_) {
244 RunFileChooserEnd();
245 return;
248 #if defined(OS_CHROMEOS)
249 if (!files.empty()) {
250 if (!IsValidProfile(profile_)) {
251 RunFileChooserEnd();
252 return;
254 // Converts |files| into FileChooserFileInfo with handling of non-native
255 // files.
256 file_manager::util::ConvertSelectedFileInfoListToFileChooserFileInfoList(
257 file_manager::util::GetFileSystemContextForRenderViewHost(
258 profile_, render_view_host_),
259 web_contents_->GetSiteInstance()->GetSiteURL(),
260 files,
261 base::Bind(
262 &FileSelectHelper::NotifyRenderViewHostAndEndAfterConversion,
263 this));
264 return;
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.
285 RunFileChooserEnd();
288 void FileSelectHelper::DeleteTemporaryFiles() {
289 BrowserThread::PostTask(BrowserThread::FILE,
290 FROM_HERE,
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.
301 Release();
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))
327 continue;
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));
335 } else {
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)
347 valid_type_count++;
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
355 // true:
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();
373 // static
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);
383 // static
384 void FileSelectHelper::EnumerateDirectory(content::WebContents* tab,
385 int request_id,
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(
405 this,
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().
418 AddRef();
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
435 // operation.
436 RunFileChooserEnd();
437 return;
440 select_file_dialog_ = ui::SelectFileDialog::Create(
441 this, new ChromeSelectFilePolicy(web_contents_));
442 if (!select_file_dialog_.get())
443 return;
445 dialog_mode_ = params.mode;
446 switch (params.mode) {
447 case FileChooserParams::Open:
448 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_FILE;
449 break;
450 case FileChooserParams::OpenMultiple:
451 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE;
452 break;
453 case FileChooserParams::UploadFolder:
454 dialog_type_ = ui::SelectFileDialog::SELECT_UPLOAD_FOLDER;
455 break;
456 case FileChooserParams::Save:
457 dialog_type_ = ui::SelectFileDialog::SELECT_SAVEAS_FILE;
458 break;
459 default:
460 // Prevent warning.
461 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_FILE;
462 NOTREACHED();
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);
476 #endif
478 select_file_dialog_->SelectFile(
479 dialog_type_,
480 params.title,
481 default_file_name,
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(),
487 owning_window,
488 #if defined(OS_ANDROID)
489 &accept_types);
490 #else
491 NULL);
492 #endif
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
503 // temporary files.
504 if (!temporary_files_.empty())
505 return;
507 render_view_host_ = NULL;
508 web_contents_ = NULL;
509 Release();
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().
521 AddRef();
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() {
529 Release();
532 void FileSelectHelper::Observe(int type,
533 const content::NotificationSource& source,
534 const content::NotificationDetails& details) {
535 switch (type) {
536 case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
537 DCHECK(content::Source<RenderWidgetHost>(source).ptr() ==
538 render_view_host_);
539 render_view_host_ = NULL;
540 break;
542 default:
543 NOTREACHED();
547 void FileSelectHelper::RenderViewHostChanged(RenderViewHost* old_host,
548 RenderViewHost* new_host) {
549 CleanUpOnRenderViewHostChange();
552 void FileSelectHelper::WebContentsDestroyed() {
553 web_contents_ = nullptr;
554 CleanUpOnRenderViewHostChange();
557 // static
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).
562 std::string unused;
563 if (accept_type.length() <= 1 ||
564 base::StringToLowerASCII(accept_type) != accept_type ||
565 base::TrimWhitespaceASCII(accept_type, base::TRIM_ALL, &unused) !=
566 base::TRIM_NONE) {
567 return false;
569 return true;