Use WeakNSProtocol/WeakNSObject for WebControllerObserverBridge ivars.
[chromium-blink-merge.git] / chrome / browser / file_select_helper.cc
blob22a8fb4a866605ad216f8e3ba34418afeaa4f3cf
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 scoped_ptr<ui::SelectFileDialog::FileTypeInfo>
296 FileSelectHelper::GetFileTypesFromAcceptType(
297 const std::vector<base::string16>& accept_types) {
298 scoped_ptr<ui::SelectFileDialog::FileTypeInfo> base_file_type(
299 new ui::SelectFileDialog::FileTypeInfo());
300 if (accept_types.empty())
301 return base_file_type.Pass();
303 // Create FileTypeInfo and pre-allocate for the first extension list.
304 scoped_ptr<ui::SelectFileDialog::FileTypeInfo> file_type(
305 new ui::SelectFileDialog::FileTypeInfo(*base_file_type));
306 file_type->include_all_files = true;
307 file_type->extensions.resize(1);
308 std::vector<base::FilePath::StringType>* extensions =
309 &file_type->extensions.back();
311 // Find the corresponding extensions.
312 int valid_type_count = 0;
313 int description_id = 0;
314 for (size_t i = 0; i < accept_types.size(); ++i) {
315 std::string ascii_type = base::UTF16ToASCII(accept_types[i]);
316 if (!IsAcceptTypeValid(ascii_type))
317 continue;
319 size_t old_extension_size = extensions->size();
320 if (ascii_type[0] == '.') {
321 // If the type starts with a period it is assumed to be a file extension
322 // so we just have to add it to the list.
323 base::FilePath::StringType ext(ascii_type.begin(), ascii_type.end());
324 extensions->push_back(ext.substr(1));
325 } else {
326 if (ascii_type == "image/*")
327 description_id = IDS_IMAGE_FILES;
328 else if (ascii_type == "audio/*")
329 description_id = IDS_AUDIO_FILES;
330 else if (ascii_type == "video/*")
331 description_id = IDS_VIDEO_FILES;
333 net::GetExtensionsForMimeType(ascii_type, extensions);
336 if (extensions->size() > old_extension_size)
337 valid_type_count++;
340 // If no valid extension is added, bail out.
341 if (valid_type_count == 0)
342 return base_file_type.Pass();
344 // Use a generic description "Custom Files" if either of the following is
345 // true:
346 // 1) There're multiple types specified, like "audio/*,video/*"
347 // 2) There're multiple extensions for a MIME type without parameter, like
348 // "ehtml,shtml,htm,html" for "text/html". On Windows, the select file
349 // dialog uses the first extension in the list to form the description,
350 // like "EHTML Files". This is not what we want.
351 if (valid_type_count > 1 ||
352 (valid_type_count == 1 && description_id == 0 && extensions->size() > 1))
353 description_id = IDS_CUSTOM_FILES;
355 if (description_id) {
356 file_type->extension_description_overrides.push_back(
357 l10n_util::GetStringUTF16(description_id));
360 return file_type.Pass();
363 // static
364 void FileSelectHelper::RunFileChooser(content::WebContents* tab,
365 const FileChooserParams& params) {
366 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
367 // FileSelectHelper will keep itself alive until it sends the result message.
368 scoped_refptr<FileSelectHelper> file_select_helper(
369 new FileSelectHelper(profile));
370 file_select_helper->RunFileChooser(tab->GetRenderViewHost(), tab, params);
373 // static
374 void FileSelectHelper::EnumerateDirectory(content::WebContents* tab,
375 int request_id,
376 const base::FilePath& path) {
377 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
378 // FileSelectHelper will keep itself alive until it sends the result message.
379 scoped_refptr<FileSelectHelper> file_select_helper(
380 new FileSelectHelper(profile));
381 file_select_helper->EnumerateDirectory(
382 request_id, tab->GetRenderViewHost(), path);
385 void FileSelectHelper::RunFileChooser(RenderViewHost* render_view_host,
386 content::WebContents* web_contents,
387 const FileChooserParams& params) {
388 DCHECK(!render_view_host_);
389 DCHECK(!web_contents_);
390 render_view_host_ = render_view_host;
391 web_contents_ = web_contents;
392 notification_registrar_.RemoveAll();
393 notification_registrar_.Add(this,
394 content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
395 content::Source<WebContents>(web_contents_));
396 notification_registrar_.Add(
397 this,
398 content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
399 content::Source<RenderWidgetHost>(render_view_host_));
400 notification_registrar_.Add(
401 this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
402 content::Source<WebContents>(web_contents_));
404 BrowserThread::PostTask(
405 BrowserThread::FILE, FROM_HERE,
406 base::Bind(&FileSelectHelper::RunFileChooserOnFileThread, this, params));
408 // Because this class returns notifications to the RenderViewHost, it is
409 // difficult for callers to know how long to keep a reference to this
410 // instance. We AddRef() here to keep the instance alive after we return
411 // to the caller, until the last callback is received from the file dialog.
412 // At that point, we must call RunFileChooserEnd().
413 AddRef();
416 void FileSelectHelper::RunFileChooserOnFileThread(
417 const FileChooserParams& params) {
418 select_file_types_ = GetFileTypesFromAcceptType(params.accept_types);
419 select_file_types_->support_drive = !params.need_local_path;
421 BrowserThread::PostTask(
422 BrowserThread::UI, FROM_HERE,
423 base::Bind(&FileSelectHelper::RunFileChooserOnUIThread, this, params));
426 void FileSelectHelper::RunFileChooserOnUIThread(
427 const FileChooserParams& params) {
428 if (!render_view_host_ || !web_contents_ || !IsValidProfile(profile_)) {
429 // If the renderer was destroyed before we started, just cancel the
430 // operation.
431 RunFileChooserEnd();
432 return;
435 select_file_dialog_ = ui::SelectFileDialog::Create(
436 this, new ChromeSelectFilePolicy(web_contents_));
437 if (!select_file_dialog_.get())
438 return;
440 dialog_mode_ = params.mode;
441 switch (params.mode) {
442 case FileChooserParams::Open:
443 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_FILE;
444 break;
445 case FileChooserParams::OpenMultiple:
446 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE;
447 break;
448 case FileChooserParams::UploadFolder:
449 dialog_type_ = ui::SelectFileDialog::SELECT_UPLOAD_FOLDER;
450 break;
451 case FileChooserParams::Save:
452 dialog_type_ = ui::SelectFileDialog::SELECT_SAVEAS_FILE;
453 break;
454 default:
455 // Prevent warning.
456 dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_FILE;
457 NOTREACHED();
460 base::FilePath default_file_name = params.default_file_name.IsAbsolute() ?
461 params.default_file_name :
462 profile_->last_selected_directory().Append(params.default_file_name);
464 gfx::NativeWindow owning_window =
465 platform_util::GetTopLevel(render_view_host_->GetView()->GetNativeView());
467 #if defined(OS_ANDROID)
468 // Android needs the original MIME types and an additional capture value.
469 std::pair<std::vector<base::string16>, bool> accept_types =
470 std::make_pair(params.accept_types, params.capture);
471 #endif
473 select_file_dialog_->SelectFile(
474 dialog_type_,
475 params.title,
476 default_file_name,
477 select_file_types_.get(),
478 select_file_types_.get() && !select_file_types_->extensions.empty()
480 : 0, // 1-based index of default extension to show.
481 base::FilePath::StringType(),
482 owning_window,
483 #if defined(OS_ANDROID)
484 &accept_types);
485 #else
486 NULL);
487 #endif
489 select_file_types_.reset();
492 // This method is called when we receive the last callback from the file
493 // chooser dialog. Perform any cleanup and release the reference we added
494 // in RunFileChooser().
495 void FileSelectHelper::RunFileChooserEnd() {
496 // If there are temporary files, then this instance needs to stick around
497 // until web_contents_ is destroyed, so that this instance can delete the
498 // temporary files.
499 if (!temporary_files_.empty())
500 return;
502 render_view_host_ = NULL;
503 web_contents_ = NULL;
504 Release();
507 void FileSelectHelper::EnumerateDirectory(int request_id,
508 RenderViewHost* render_view_host,
509 const base::FilePath& path) {
511 // Because this class returns notifications to the RenderViewHost, it is
512 // difficult for callers to know how long to keep a reference to this
513 // instance. We AddRef() here to keep the instance alive after we return
514 // to the caller, until the last callback is received from the enumeration
515 // code. At that point, we must call EnumerateDirectoryEnd().
516 AddRef();
517 StartNewEnumeration(path, request_id, render_view_host);
520 // This method is called when we receive the last callback from the enumeration
521 // code. Perform any cleanup and release the reference we added in
522 // EnumerateDirectory().
523 void FileSelectHelper::EnumerateDirectoryEnd() {
524 Release();
527 void FileSelectHelper::Observe(int type,
528 const content::NotificationSource& source,
529 const content::NotificationDetails& details) {
530 switch (type) {
531 case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
532 DCHECK(content::Source<RenderWidgetHost>(source).ptr() ==
533 render_view_host_);
534 render_view_host_ = NULL;
535 break;
538 case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: {
539 DCHECK(content::Source<WebContents>(source).ptr() == web_contents_);
540 web_contents_ = NULL;
543 // Intentional fall through.
544 case content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED:
545 if (!temporary_files_.empty()) {
546 DeleteTemporaryFiles();
548 // Now that the temporary files have been scheduled for deletion, there
549 // is no longer any reason to keep this instance around.
550 Release();
553 break;
555 default:
556 NOTREACHED();
560 // static
561 bool FileSelectHelper::IsAcceptTypeValid(const std::string& accept_type) {
562 // TODO(raymes): This only does some basic checks, extend to test more cases.
563 // A 1 character accept type will always be invalid (either a "." in the case
564 // of an extension or a "/" in the case of a MIME type).
565 std::string unused;
566 if (accept_type.length() <= 1 ||
567 base::StringToLowerASCII(accept_type) != accept_type ||
568 base::TrimWhitespaceASCII(accept_type, base::TRIM_ALL, &unused) !=
569 base::TRIM_NONE) {
570 return false;
572 return true;