Update names for Content Shell and Chrome Shell
[chromium-blink-merge.git] / apps / launcher.cc
blobaae298f10454c08e4ac94887267d58411facefbe
1 // Copyright 2013 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 "apps/launcher.h"
7 #include "base/command_line.h"
8 #include "base/file_util.h"
9 #include "base/files/file_path.h"
10 #include "base/logging.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/extensions/api/app_runtime/app_runtime_api.h"
15 #include "chrome/browser/extensions/api/file_handlers/app_file_handler_util.h"
16 #include "chrome/browser/extensions/api/file_system/file_system_api.h"
17 #include "chrome/browser/extensions/event_router.h"
18 #include "chrome/browser/extensions/extension_host.h"
19 #include "chrome/browser/extensions/extension_prefs.h"
20 #include "chrome/browser/extensions/extension_process_manager.h"
21 #include "chrome/browser/extensions/extension_service.h"
22 #include "chrome/browser/extensions/extension_system.h"
23 #include "chrome/browser/extensions/lazy_background_task_queue.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/ui/apps/app_metro_infobar_delegate_win.h"
26 #include "chrome/common/extensions/api/app_runtime.h"
27 #include "chrome/common/extensions/extension.h"
28 #include "chrome/common/extensions/extension_messages.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "content/public/browser/render_process_host.h"
31 #include "content/public/browser/web_contents.h"
32 #include "net/base/mime_util.h"
33 #include "net/base/net_util.h"
34 #include "url/gurl.h"
36 #if defined(OS_CHROMEOS)
37 #include "chrome/browser/chromeos/drive/file_errors.h"
38 #include "chrome/browser/chromeos/drive/file_system_interface.h"
39 #include "chrome/browser/chromeos/drive/file_system_util.h"
40 #endif
42 #if defined(OS_WIN)
43 #include "win8/util/win8_util.h"
44 #endif
46 namespace app_runtime = extensions::api::app_runtime;
48 using content::BrowserThread;
49 using extensions::app_file_handler_util::CheckWritableFiles;
50 using extensions::app_file_handler_util::FileHandlerForId;
51 using extensions::app_file_handler_util::FileHandlerCanHandleFile;
52 using extensions::app_file_handler_util::FirstFileHandlerForFile;
53 using extensions::app_file_handler_util::CreateFileEntry;
54 using extensions::app_file_handler_util::GrantedFileEntry;
55 using extensions::app_file_handler_util::HasFileSystemWritePermission;
56 using extensions::Extension;
57 using extensions::ExtensionHost;
58 using extensions::ExtensionSystem;
60 namespace apps {
62 namespace {
64 const char kFallbackMimeType[] = "application/octet-stream";
66 bool MakePathAbsolute(const base::FilePath& current_directory,
67 base::FilePath* file_path) {
68 DCHECK(file_path);
69 if (file_path->IsAbsolute())
70 return true;
72 if (current_directory.empty()) {
73 *file_path = base::MakeAbsoluteFilePath(*file_path);
74 return !file_path->empty();
77 if (!current_directory.IsAbsolute())
78 return false;
80 *file_path = current_directory.Append(*file_path);
81 return true;
84 bool GetAbsolutePathFromCommandLine(const CommandLine* command_line,
85 const base::FilePath& current_directory,
86 base::FilePath* path) {
87 if (!command_line || !command_line->GetArgs().size())
88 return false;
90 base::FilePath relative_path(command_line->GetArgs()[0]);
91 base::FilePath absolute_path(relative_path);
92 if (!MakePathAbsolute(current_directory, &absolute_path)) {
93 LOG(WARNING) << "Cannot make absolute path from " << relative_path.value();
94 return false;
96 *path = absolute_path;
97 return true;
100 // Helper method to launch the platform app |extension| with no data. This
101 // should be called in the fallback case, where it has been impossible to
102 // load or obtain file launch data.
103 void LaunchPlatformAppWithNoData(Profile* profile, const Extension* extension) {
104 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
105 extensions::AppEventRouter::DispatchOnLaunchedEvent(profile, extension);
108 // Class to handle launching of platform apps to open a specific path.
109 // An instance of this class is created for each launch. The lifetime of these
110 // instances is managed by reference counted pointers. As long as an instance
111 // has outstanding tasks on a message queue it will be retained; once all
112 // outstanding tasks are completed it will be deleted.
113 class PlatformAppPathLauncher
114 : public base::RefCountedThreadSafe<PlatformAppPathLauncher> {
115 public:
116 PlatformAppPathLauncher(Profile* profile,
117 const Extension* extension,
118 const base::FilePath& file_path)
119 : profile_(profile), extension_(extension), file_path_(file_path) {}
121 void Launch() {
122 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
123 if (file_path_.empty()) {
124 LaunchPlatformAppWithNoData(profile_, extension_);
125 return;
128 DCHECK(file_path_.IsAbsolute());
130 if (HasFileSystemWritePermission(extension_)) {
131 std::vector<base::FilePath> paths;
132 paths.push_back(file_path_);
133 CheckWritableFiles(
134 paths,
135 profile_,
136 false,
137 base::Bind(&PlatformAppPathLauncher::OnFileValid, this),
138 base::Bind(&PlatformAppPathLauncher::OnFileInvalid, this));
139 return;
142 OnFileValid();
145 void LaunchWithHandler(const std::string& handler_id) {
146 handler_id_ = handler_id;
147 Launch();
150 private:
151 friend class base::RefCountedThreadSafe<PlatformAppPathLauncher>;
153 virtual ~PlatformAppPathLauncher() {}
155 void OnFileValid() {
156 #if defined(OS_CHROMEOS)
157 if (drive::util::IsUnderDriveMountPoint(file_path_)) {
158 PlatformAppPathLauncher::GetMimeTypeAndLaunchForDriveFile();
159 return;
161 #endif
163 BrowserThread::PostTask(
164 BrowserThread::FILE,
165 FROM_HERE,
166 base::Bind(&PlatformAppPathLauncher::GetMimeTypeAndLaunch, this));
169 void OnFileInvalid(const base::FilePath& /* error_path */) {
170 LaunchWithNoLaunchData();
173 void GetMimeTypeAndLaunch() {
174 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
176 // If the file doesn't exist, or is a directory, launch with no launch data.
177 if (!base::PathExists(file_path_) ||
178 base::DirectoryExists(file_path_)) {
179 LOG(WARNING) << "No file exists with path " << file_path_.value();
180 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
181 &PlatformAppPathLauncher::LaunchWithNoLaunchData, this));
182 return;
185 std::string mime_type;
186 if (!net::GetMimeTypeFromFile(file_path_, &mime_type))
187 mime_type = kFallbackMimeType;
189 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
190 &PlatformAppPathLauncher::LaunchWithMimeType, this, mime_type));
193 #if defined(OS_CHROMEOS)
194 void GetMimeTypeAndLaunchForDriveFile() {
195 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
197 drive::FileSystemInterface* file_system =
198 drive::util::GetFileSystemByProfile(profile_);
199 if (!file_system) {
200 LaunchWithNoLaunchData();
201 return;
204 file_system->GetFileByPath(
205 drive::util::ExtractDrivePath(file_path_),
206 base::Bind(&PlatformAppPathLauncher::OnGotDriveFile, this));
209 void OnGotDriveFile(drive::FileError error,
210 const base::FilePath& file_path,
211 scoped_ptr<drive::ResourceEntry> entry) {
212 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
214 if (error != drive::FILE_ERROR_OK ||
215 !entry || entry->file_specific_info().is_hosted_document()) {
216 LaunchWithNoLaunchData();
217 return;
220 const std::string& mime_type =
221 entry->file_specific_info().content_mime_type();
222 LaunchWithMimeType(mime_type.empty() ? kFallbackMimeType : mime_type);
224 #endif // defined(OS_CHROMEOS)
226 void LaunchWithNoLaunchData() {
227 // This method is required as an entry point on the UI thread.
228 LaunchPlatformAppWithNoData(profile_, extension_);
231 void LaunchWithMimeType(const std::string& mime_type) {
232 // Find file handler from the platform app for the file being opened.
233 const extensions::FileHandlerInfo* handler = NULL;
234 if (!handler_id_.empty())
235 handler = FileHandlerForId(*extension_, handler_id_);
236 else
237 handler = FirstFileHandlerForFile(*extension_, mime_type, file_path_);
238 if (handler && !FileHandlerCanHandleFile(*handler, mime_type, file_path_)) {
239 LOG(WARNING) << "Extension does not provide a valid file handler for "
240 << file_path_.value();
241 LaunchWithNoLaunchData();
242 return;
245 // If this app doesn't have a file handler that supports the file, launch
246 // with no launch data.
247 if (!handler) {
248 LOG(WARNING) << "Extension does not provide a valid file handler for "
249 << file_path_.value();
250 LaunchWithNoLaunchData();
251 return;
254 if (handler_id_.empty())
255 handler_id_ = handler->id;
257 // Access needs to be granted to the file for the process associated with
258 // the extension. To do this the ExtensionHost is needed. This might not be
259 // available, or it might be in the process of being unloaded, in which case
260 // the lazy background task queue is used to load the extension and then
261 // call back to us.
262 extensions::LazyBackgroundTaskQueue* queue =
263 ExtensionSystem::Get(profile_)->lazy_background_task_queue();
264 if (queue->ShouldEnqueueTask(profile_, extension_)) {
265 queue->AddPendingTask(profile_, extension_->id(), base::Bind(
266 &PlatformAppPathLauncher::GrantAccessToFileAndLaunch,
267 this, mime_type));
268 return;
271 ExtensionProcessManager* process_manager =
272 ExtensionSystem::Get(profile_)->process_manager();
273 ExtensionHost* host =
274 process_manager->GetBackgroundHostForExtension(extension_->id());
275 DCHECK(host);
276 GrantAccessToFileAndLaunch(mime_type, host);
279 void GrantAccessToFileAndLaunch(const std::string& mime_type,
280 ExtensionHost* host) {
281 // If there was an error loading the app page, |host| will be NULL.
282 if (!host) {
283 LOG(ERROR) << "Could not load app page for " << extension_->id();
284 return;
287 GrantedFileEntry file_entry =
288 CreateFileEntry(profile_,
289 extension_,
290 host->render_process_host()->GetID(),
291 file_path_,
292 false);
293 extensions::AppEventRouter::DispatchOnLaunchedEventWithFileEntry(
294 profile_, extension_, handler_id_, mime_type, file_entry);
297 // The profile the app should be run in.
298 Profile* profile_;
299 // The extension providing the app.
300 const Extension* extension_;
301 // The path to be passed through to the app.
302 const base::FilePath file_path_;
303 // The ID of the file handler used to launch the app.
304 std::string handler_id_;
306 DISALLOW_COPY_AND_ASSIGN(PlatformAppPathLauncher);
309 } // namespace
311 void LaunchPlatformAppWithCommandLine(Profile* profile,
312 const Extension* extension,
313 const CommandLine* command_line,
314 const base::FilePath& current_directory) {
315 #if defined(OS_WIN)
316 // On Windows 8's single window Metro mode we can not launch platform apps.
317 // Offer to switch Chrome to desktop mode.
318 if (win8::IsSingleWindowMetroMode()) {
319 AppMetroInfoBarDelegateWin::Create(
320 profile, AppMetroInfoBarDelegateWin::LAUNCH_PACKAGED_APP,
321 extension->id());
322 return;
324 #endif
326 base::FilePath path;
327 if (!GetAbsolutePathFromCommandLine(command_line, current_directory, &path)) {
328 LaunchPlatformAppWithNoData(profile, extension);
329 return;
332 // TODO(benwells): add a command-line argument to provide a handler ID.
333 LaunchPlatformAppWithPath(profile, extension, path);
336 void LaunchPlatformAppWithPath(Profile* profile,
337 const Extension* extension,
338 const base::FilePath& file_path) {
339 // launcher will be freed when nothing has a reference to it. The message
340 // queue will retain a reference for any outstanding task, so when the
341 // launcher has finished it will be freed.
342 scoped_refptr<PlatformAppPathLauncher> launcher =
343 new PlatformAppPathLauncher(profile, extension, file_path);
344 launcher->Launch();
347 void LaunchPlatformApp(Profile* profile, const Extension* extension) {
348 LaunchPlatformAppWithCommandLine(profile, extension, NULL, base::FilePath());
351 void LaunchPlatformAppWithFileHandler(Profile* profile,
352 const Extension* extension,
353 const std::string& handler_id,
354 const base::FilePath& file_path) {
355 scoped_refptr<PlatformAppPathLauncher> launcher =
356 new PlatformAppPathLauncher(profile, extension, file_path);
357 launcher->LaunchWithHandler(handler_id);
360 void RestartPlatformApp(Profile* profile, const Extension* extension) {
361 #if defined(OS_WIN)
362 // On Windows 8's single window Metro mode we can not launch platform apps.
363 // In restart we are just making sure launch doesn't slip through.
364 if (win8::IsSingleWindowMetroMode())
365 return;
366 #endif
367 extensions::EventRouter* event_router =
368 ExtensionSystem::Get(profile)->event_router();
369 bool listening_to_restart = event_router->
370 ExtensionHasEventListener(extension->id(),
371 app_runtime::OnRestarted::kEventName);
373 if (listening_to_restart) {
374 extensions::AppEventRouter::DispatchOnRestartedEvent(profile, extension);
375 return;
378 extensions::ExtensionPrefs* extension_prefs = ExtensionSystem::Get(profile)->
379 extension_service()->extension_prefs();
380 bool had_windows = extension_prefs->IsActive(extension->id());
381 extension_prefs->SetIsActive(extension->id(), false);
382 bool listening_to_launch = event_router->
383 ExtensionHasEventListener(extension->id(),
384 app_runtime::OnLaunched::kEventName);
386 if (listening_to_launch && had_windows)
387 LaunchPlatformAppWithNoData(profile, extension);
390 void LaunchPlatformAppWithUrl(Profile* profile,
391 const Extension* extension,
392 const std::string& handler_id,
393 const GURL& url,
394 const GURL& referrer_url) {
395 extensions::AppEventRouter::DispatchOnLaunchedEventWithUrl(
396 profile, extension, handler_id, url, referrer_url);
399 } // namespace apps