Add new certificateProvider extension API.
[chromium-blink-merge.git] / chrome / browser / ui / views / select_file_dialog_extension.cc
blob6a6a60efb93f1ab7751e179ee56fd4363abd610b
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/ui/views/select_file_dialog_extension.h"
7 #include "base/bind.h"
8 #include "base/callback.h"
9 #include "base/logging.h"
10 #include "base/memory/ref_counted.h"
11 #include "base/memory/singleton.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/prefs/pref_service.h"
14 #include "chrome/browser/app_mode/app_mode_utils.h"
15 #include "chrome/browser/apps/app_window_registry_util.h"
16 #include "chrome/browser/chromeos/file_manager/app_id.h"
17 #include "chrome/browser/chromeos/file_manager/fileapi_util.h"
18 #include "chrome/browser/chromeos/file_manager/select_file_dialog_util.h"
19 #include "chrome/browser/chromeos/file_manager/url_util.h"
20 #include "chrome/browser/chromeos/login/ui/login_web_dialog.h"
21 #include "chrome/browser/extensions/extension_service.h"
22 #include "chrome/browser/extensions/extension_view_host.h"
23 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/sessions/session_tab_helper.h"
25 #include "chrome/browser/ui/browser.h"
26 #include "chrome/browser/ui/browser_finder.h"
27 #include "chrome/browser/ui/browser_window.h"
28 #include "chrome/browser/ui/chrome_select_file_policy.h"
29 #include "chrome/browser/ui/host_desktop.h"
30 #include "chrome/browser/ui/tabs/tab_strip_model.h"
31 #include "chrome/browser/ui/views/extensions/extension_dialog.h"
32 #include "chrome/common/pref_names.h"
33 #include "content/public/browser/browser_thread.h"
34 #include "extensions/browser/app_window/app_window.h"
35 #include "extensions/browser/app_window/native_app_window.h"
36 #include "extensions/browser/extension_system.h"
37 #include "ui/base/base_window.h"
38 #include "ui/shell_dialogs/selected_file_info.h"
39 #include "ui/views/widget/widget.h"
41 using extensions::AppWindow;
42 using content::BrowserThread;
44 namespace {
46 const int kFileManagerWidth = 972; // pixels
47 const int kFileManagerHeight = 640; // pixels
48 const int kFileManagerMinimumWidth = 640; // pixels
49 const int kFileManagerMinimumHeight = 240; // pixels
51 // Holds references to file manager dialogs that have callbacks pending
52 // to their listeners.
53 class PendingDialog {
54 public:
55 static PendingDialog* GetInstance();
56 void Add(SelectFileDialogExtension::RoutingID id,
57 scoped_refptr<SelectFileDialogExtension> dialog);
58 void Remove(SelectFileDialogExtension::RoutingID id);
59 scoped_refptr<SelectFileDialogExtension> Find(
60 SelectFileDialogExtension::RoutingID id);
62 private:
63 friend struct DefaultSingletonTraits<PendingDialog>;
64 typedef std::map<SelectFileDialogExtension::RoutingID,
65 scoped_refptr<SelectFileDialogExtension> > Map;
66 Map map_;
69 // static
70 PendingDialog* PendingDialog::GetInstance() {
71 return Singleton<PendingDialog>::get();
74 void PendingDialog::Add(SelectFileDialogExtension::RoutingID id,
75 scoped_refptr<SelectFileDialogExtension> dialog) {
76 DCHECK(dialog.get());
77 if (map_.find(id) == map_.end())
78 map_.insert(std::make_pair(id, dialog));
79 else
80 DLOG(WARNING) << "Duplicate pending dialog " << id;
83 void PendingDialog::Remove(SelectFileDialogExtension::RoutingID id) {
84 map_.erase(id);
87 scoped_refptr<SelectFileDialogExtension> PendingDialog::Find(
88 SelectFileDialogExtension::RoutingID id) {
89 Map::const_iterator it = map_.find(id);
90 if (it == map_.end())
91 return NULL;
92 return it->second;
95 // Given |owner_window| finds corresponding |base_window|, it's associated
96 // |web_contents| and |profile|.
97 void FindRuntimeContext(gfx::NativeWindow owner_window,
98 ui::BaseWindow** base_window,
99 content::WebContents** web_contents) {
100 *base_window = NULL;
101 *web_contents = NULL;
102 // To get the base_window and web contents, either a Browser or AppWindow is
103 // needed.
104 Browser* owner_browser = NULL;
105 AppWindow* app_window = NULL;
107 // If owner_window is supplied, use that to find a browser or a app window.
108 if (owner_window) {
109 owner_browser = chrome::FindBrowserWithWindow(owner_window);
110 if (!owner_browser) {
111 // If an owner_window was supplied but we couldn't find a browser, this
112 // could be for a app window.
113 app_window =
114 AppWindowRegistryUtil::GetAppWindowForNativeWindowAnyProfile(
115 owner_window);
119 if (app_window) {
120 DCHECK(!app_window->window_type_is_panel());
121 *base_window = app_window->GetBaseWindow();
122 *web_contents = app_window->web_contents();
123 } else {
124 // If the owning window is still unknown, this could be a background page or
125 // and extension popup. Use the last active browser.
126 if (!owner_browser) {
127 owner_browser =
128 chrome::FindLastActiveWithHostDesktopType(chrome::GetActiveDesktop());
130 if (owner_browser) {
131 *base_window = owner_browser->window();
132 *web_contents = owner_browser->tab_strip_model()->GetActiveWebContents();
136 // In ChromeOS kiosk launch mode, we can still show file picker for
137 // certificate manager dialog. There are no browser or webapp window
138 // instances present in this case.
139 if (chrome::IsRunningInForcedAppMode() && !(*web_contents))
140 *web_contents = chromeos::LoginWebDialog::GetCurrentWebContents();
142 CHECK(web_contents);
145 } // namespace
147 /////////////////////////////////////////////////////////////////////////////
149 // static
150 SelectFileDialogExtension::RoutingID
151 SelectFileDialogExtension::GetRoutingIDFromWebContents(
152 const content::WebContents* web_contents) {
153 // Use the raw pointer value as the identifier. Previously we have used the
154 // tab ID for the purpose, but some web_contents, especially those of the
155 // packaged apps, don't have tab IDs assigned.
156 return web_contents;
159 // TODO(jamescook): Move this into a new file shell_dialogs_chromeos.cc
160 // static
161 SelectFileDialogExtension* SelectFileDialogExtension::Create(
162 Listener* listener,
163 ui::SelectFilePolicy* policy) {
164 return new SelectFileDialogExtension(listener, policy);
167 SelectFileDialogExtension::SelectFileDialogExtension(
168 Listener* listener,
169 ui::SelectFilePolicy* policy)
170 : SelectFileDialog(listener, policy),
171 has_multiple_file_type_choices_(false),
172 routing_id_(),
173 profile_(NULL),
174 owner_window_(NULL),
175 selection_type_(CANCEL),
176 selection_index_(0),
177 params_(NULL) {
180 SelectFileDialogExtension::~SelectFileDialogExtension() {
181 if (extension_dialog_.get())
182 extension_dialog_->ObserverDestroyed();
185 bool SelectFileDialogExtension::IsRunning(
186 gfx::NativeWindow owner_window) const {
187 return owner_window_ == owner_window;
190 void SelectFileDialogExtension::ListenerDestroyed() {
191 listener_ = NULL;
192 params_ = NULL;
193 PendingDialog::GetInstance()->Remove(routing_id_);
196 void SelectFileDialogExtension::ExtensionDialogClosing(
197 ExtensionDialog* /*dialog*/) {
198 profile_ = NULL;
199 owner_window_ = NULL;
200 // Release our reference to the underlying dialog to allow it to close.
201 extension_dialog_ = NULL;
202 PendingDialog::GetInstance()->Remove(routing_id_);
203 // Actually invoke the appropriate callback on our listener.
204 NotifyListener();
207 void SelectFileDialogExtension::ExtensionTerminated(
208 ExtensionDialog* dialog) {
209 // The extension would have been unloaded because of the termination,
210 // reload it.
211 std::string extension_id = dialog->host()->extension()->id();
212 // Reload the extension after a bit; the extension may not have been unloaded
213 // yet. We don't want to try to reload the extension only to have the Unload
214 // code execute after us and re-unload the extension.
216 // TODO(rkc): This is ugly. The ideal solution is that we shouldn't need to
217 // reload the extension at all - when we try to open the extension the next
218 // time, the extension subsystem would automatically reload it for us. At
219 // this time though this is broken because of some faulty wiring in
220 // extensions::ProcessManager::CreateViewHost. Once that is fixed, remove
221 // this.
222 if (profile_) {
223 base::MessageLoop::current()->PostTask(
224 FROM_HERE,
225 base::Bind(&ExtensionService::ReloadExtension,
226 base::Unretained(extensions::ExtensionSystem::Get(profile_)
227 ->extension_service()),
228 extension_id));
231 dialog->GetWidget()->Close();
234 // static
235 void SelectFileDialogExtension::OnFileSelected(
236 RoutingID routing_id,
237 const ui::SelectedFileInfo& file,
238 int index) {
239 scoped_refptr<SelectFileDialogExtension> dialog =
240 PendingDialog::GetInstance()->Find(routing_id);
241 if (!dialog.get())
242 return;
243 dialog->selection_type_ = SINGLE_FILE;
244 dialog->selection_files_.clear();
245 dialog->selection_files_.push_back(file);
246 dialog->selection_index_ = index;
249 // static
250 void SelectFileDialogExtension::OnMultiFilesSelected(
251 RoutingID routing_id,
252 const std::vector<ui::SelectedFileInfo>& files) {
253 scoped_refptr<SelectFileDialogExtension> dialog =
254 PendingDialog::GetInstance()->Find(routing_id);
255 if (!dialog.get())
256 return;
257 dialog->selection_type_ = MULTIPLE_FILES;
258 dialog->selection_files_ = files;
259 dialog->selection_index_ = 0;
262 // static
263 void SelectFileDialogExtension::OnFileSelectionCanceled(RoutingID routing_id) {
264 scoped_refptr<SelectFileDialogExtension> dialog =
265 PendingDialog::GetInstance()->Find(routing_id);
266 if (!dialog.get())
267 return;
268 dialog->selection_type_ = CANCEL;
269 dialog->selection_files_.clear();
270 dialog->selection_index_ = 0;
273 content::RenderViewHost* SelectFileDialogExtension::GetRenderViewHost() {
274 if (extension_dialog_.get())
275 return extension_dialog_->host()->render_view_host();
276 return NULL;
279 void SelectFileDialogExtension::NotifyListener() {
280 if (!listener_)
281 return;
282 switch (selection_type_) {
283 case CANCEL:
284 listener_->FileSelectionCanceled(params_);
285 break;
286 case SINGLE_FILE:
287 listener_->FileSelectedWithExtraInfo(selection_files_[0],
288 selection_index_,
289 params_);
290 break;
291 case MULTIPLE_FILES:
292 listener_->MultiFilesSelectedWithExtraInfo(selection_files_, params_);
293 break;
294 default:
295 NOTREACHED();
296 break;
300 void SelectFileDialogExtension::AddPending(RoutingID routing_id) {
301 PendingDialog::GetInstance()->Add(routing_id, this);
304 // static
305 bool SelectFileDialogExtension::PendingExists(RoutingID routing_id) {
306 return PendingDialog::GetInstance()->Find(routing_id).get() != NULL;
309 bool SelectFileDialogExtension::HasMultipleFileTypeChoicesImpl() {
310 return has_multiple_file_type_choices_;
313 void SelectFileDialogExtension::SelectFileImpl(
314 Type type,
315 const base::string16& title,
316 const base::FilePath& default_path,
317 const FileTypeInfo* file_types,
318 int file_type_index,
319 const base::FilePath::StringType& default_extension,
320 gfx::NativeWindow owner_window,
321 void* params) {
322 if (owner_window_) {
323 LOG(ERROR) << "File dialog already in use!";
324 return;
327 // The base window to associate the dialog with.
328 ui::BaseWindow* base_window = NULL;
330 // The web contents to associate the dialog with.
331 content::WebContents* web_contents = NULL;
332 FindRuntimeContext(owner_window, &base_window, &web_contents);
333 CHECK(web_contents);
334 profile_ = Profile::FromBrowserContext(web_contents->GetBrowserContext());
335 CHECK(profile_);
337 // Check if we have another dialog opened for the contents. It's unlikely, but
338 // possible. In such situation, discard this request.
339 RoutingID routing_id = GetRoutingIDFromWebContents(web_contents);
340 if (PendingExists(routing_id))
341 return;
343 const PrefService* pref_service = profile_->GetPrefs();
344 DCHECK(pref_service);
346 base::FilePath download_default_path(
347 pref_service->GetFilePath(prefs::kDownloadDefaultDirectory));
349 base::FilePath selection_path = default_path.IsAbsolute() ?
350 default_path : download_default_path.Append(default_path.BaseName());
352 base::FilePath fallback_path = profile_->last_selected_directory().empty() ?
353 download_default_path : profile_->last_selected_directory();
355 // Convert the above absolute paths to file system URLs.
356 GURL selection_url;
357 if (!file_manager::util::ConvertAbsoluteFilePathToFileSystemUrl(
358 profile_,
359 selection_path,
360 file_manager::kFileManagerAppId,
361 &selection_url)) {
362 // Due to the current design, an invalid temporal cache file path may passed
363 // as |default_path| (crbug.com/178013 #9-#11). In such a case, we use the
364 // last selected directory as a workaround. Real fix is tracked at
365 // crbug.com/110119.
366 if (!file_manager::util::ConvertAbsoluteFilePathToFileSystemUrl(
367 profile_,
368 fallback_path.Append(default_path.BaseName()),
369 file_manager::kFileManagerAppId,
370 &selection_url)) {
371 DVLOG(1) << "Unable to resolve the selection URL.";
375 GURL current_directory_url;
376 base::FilePath current_directory_path = selection_path.DirName();
377 if (!file_manager::util::ConvertAbsoluteFilePathToFileSystemUrl(
378 profile_,
379 current_directory_path,
380 file_manager::kFileManagerAppId,
381 &current_directory_url)) {
382 // Fallback if necessary, see the comment above.
383 if (!file_manager::util::ConvertAbsoluteFilePathToFileSystemUrl(
384 profile_,
385 fallback_path,
386 file_manager::kFileManagerAppId,
387 &current_directory_url)) {
388 DVLOG(1) << "Unable to resolve the current directory URL for: "
389 << fallback_path.value();
393 has_multiple_file_type_choices_ =
394 !file_types || (file_types->extensions.size() > 1);
396 GURL file_manager_url =
397 file_manager::util::GetFileManagerMainPageUrlWithParams(
398 type,
399 title,
400 current_directory_url,
401 selection_url,
402 default_path.BaseName().value(),
403 file_types,
404 file_type_index,
405 default_extension);
407 ExtensionDialog* dialog = ExtensionDialog::Show(
408 file_manager_url,
409 base_window ? base_window->GetNativeWindow() : owner_window,
410 profile_,
411 web_contents,
412 kFileManagerWidth,
413 kFileManagerHeight,
414 kFileManagerMinimumWidth,
415 kFileManagerMinimumHeight,
416 file_manager::util::GetSelectFileDialogTitle(type),
417 this /* ExtensionDialog::Observer */);
418 if (!dialog) {
419 LOG(ERROR) << "Unable to create extension dialog";
420 return;
423 // Connect our listener to FileDialogFunction's per-tab callbacks.
424 AddPending(routing_id);
426 extension_dialog_ = dialog;
427 params_ = params;
428 routing_id_ = routing_id;
429 owner_window_ = owner_window;