Move renderer ExtensionHelper into //extensions
[chromium-blink-merge.git] / apps / launcher.cc
blob8d31a0115c46e671d56a953aa194942a20f388df
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 "apps/browser/api/app_runtime/app_runtime_api.h"
8 #include "apps/browser/file_handler_util.h"
9 #include "apps/common/api/app_runtime.h"
10 #include "base/command_line.h"
11 #include "base/file_util.h"
12 #include "base/files/file_path.h"
13 #include "base/logging.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/browser/extensions/api/file_handlers/app_file_handler_util.h"
18 #include "chrome/browser/extensions/api/file_system/file_system_api.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "content/public/browser/browser_thread.h"
21 #include "content/public/browser/render_process_host.h"
22 #include "content/public/browser/web_contents.h"
23 #include "extensions/browser/event_router.h"
24 #include "extensions/browser/extension_host.h"
25 #include "extensions/browser/extension_prefs.h"
26 #include "extensions/browser/extension_system.h"
27 #include "extensions/browser/lazy_background_task_queue.h"
28 #include "extensions/browser/process_manager.h"
29 #include "extensions/common/extension.h"
30 #include "extensions/common/extension_messages.h"
31 #include "extensions/common/manifest_handlers/kiosk_mode_info.h"
32 #include "net/base/filename_util.h"
33 #include "net/base/mime_sniffer.h"
34 #include "net/base/mime_util.h"
35 #include "net/base/net_util.h"
36 #include "url/gurl.h"
38 #if defined(OS_CHROMEOS)
39 #include "chrome/browser/chromeos/drive/file_errors.h"
40 #include "chrome/browser/chromeos/drive/file_system_interface.h"
41 #include "chrome/browser/chromeos/drive/file_system_util.h"
42 #include "chrome/browser/chromeos/login/user_manager.h"
43 #endif
45 namespace app_runtime = apps::api::app_runtime;
47 using apps::file_handler_util::GrantedFileEntry;
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::HasFileSystemWritePermission;
55 using extensions::EventRouter;
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.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 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 // If MIME type of the file can't be determined by its path,
188 // try to sniff it by its content.
189 std::vector<char> content(net::kMaxBytesToSniff);
190 int bytes_read = base::ReadFile(file_path_, &content[0], content.size());
191 if (bytes_read >= 0) {
192 net::SniffMimeType(&content[0],
193 bytes_read,
194 net::FilePathToFileURL(file_path_),
195 std::string(), // type_hint (passes no hint)
196 &mime_type);
198 if (mime_type.empty())
199 mime_type = kFallbackMimeType;
202 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
203 &PlatformAppPathLauncher::LaunchWithMimeType, this, mime_type));
206 #if defined(OS_CHROMEOS)
207 void GetMimeTypeAndLaunchForDriveFile() {
208 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
210 drive::FileSystemInterface* file_system =
211 drive::util::GetFileSystemByProfile(profile_);
212 if (!file_system) {
213 LaunchWithNoLaunchData();
214 return;
217 file_system->GetFile(
218 drive::util::ExtractDrivePath(file_path_),
219 base::Bind(&PlatformAppPathLauncher::OnGotDriveFile, this));
222 void OnGotDriveFile(drive::FileError error,
223 const base::FilePath& file_path,
224 scoped_ptr<drive::ResourceEntry> entry) {
225 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
227 if (error != drive::FILE_ERROR_OK ||
228 !entry || entry->file_specific_info().is_hosted_document()) {
229 LaunchWithNoLaunchData();
230 return;
233 const std::string& mime_type =
234 entry->file_specific_info().content_mime_type();
235 LaunchWithMimeType(mime_type.empty() ? kFallbackMimeType : mime_type);
237 #endif // defined(OS_CHROMEOS)
239 void LaunchWithNoLaunchData() {
240 // This method is required as an entry point on the UI thread.
241 LaunchPlatformAppWithNoData(profile_, extension_);
244 void LaunchWithMimeType(const std::string& mime_type) {
245 // Find file handler from the platform app for the file being opened.
246 const extensions::FileHandlerInfo* handler = NULL;
247 if (!handler_id_.empty())
248 handler = FileHandlerForId(*extension_, handler_id_);
249 else
250 handler = FirstFileHandlerForFile(*extension_, mime_type, file_path_);
251 if (handler && !FileHandlerCanHandleFile(*handler, mime_type, file_path_)) {
252 LOG(WARNING) << "Extension does not provide a valid file handler for "
253 << file_path_.value();
254 LaunchWithNoLaunchData();
255 return;
258 // If this app doesn't have a file handler that supports the file, launch
259 // with no launch data.
260 if (!handler) {
261 LOG(WARNING) << "Extension does not provide a valid file handler for "
262 << file_path_.value();
263 LaunchWithNoLaunchData();
264 return;
267 if (handler_id_.empty())
268 handler_id_ = handler->id;
270 // Access needs to be granted to the file for the process associated with
271 // the extension. To do this the ExtensionHost is needed. This might not be
272 // available, or it might be in the process of being unloaded, in which case
273 // the lazy background task queue is used to load the extension and then
274 // call back to us.
275 extensions::LazyBackgroundTaskQueue* queue =
276 ExtensionSystem::Get(profile_)->lazy_background_task_queue();
277 if (queue->ShouldEnqueueTask(profile_, extension_)) {
278 queue->AddPendingTask(profile_, extension_->id(), base::Bind(
279 &PlatformAppPathLauncher::GrantAccessToFileAndLaunch,
280 this, mime_type));
281 return;
284 extensions::ProcessManager* process_manager =
285 ExtensionSystem::Get(profile_)->process_manager();
286 ExtensionHost* host =
287 process_manager->GetBackgroundHostForExtension(extension_->id());
288 DCHECK(host);
289 GrantAccessToFileAndLaunch(mime_type, host);
292 void GrantAccessToFileAndLaunch(const std::string& mime_type,
293 ExtensionHost* host) {
294 // If there was an error loading the app page, |host| will be NULL.
295 if (!host) {
296 LOG(ERROR) << "Could not load app page for " << extension_->id();
297 return;
300 GrantedFileEntry file_entry =
301 CreateFileEntry(profile_,
302 extension_,
303 host->render_process_host()->GetID(),
304 file_path_,
305 false);
306 AppEventRouter::DispatchOnLaunchedEventWithFileEntry(
307 profile_, extension_, handler_id_, mime_type, file_entry);
310 // The profile the app should be run in.
311 Profile* profile_;
312 // The extension providing the app.
313 const Extension* extension_;
314 // The path to be passed through to the app.
315 const base::FilePath file_path_;
316 // The ID of the file handler used to launch the app.
317 std::string handler_id_;
319 DISALLOW_COPY_AND_ASSIGN(PlatformAppPathLauncher);
322 } // namespace
324 void LaunchPlatformAppWithCommandLine(Profile* profile,
325 const Extension* extension,
326 const CommandLine& command_line,
327 const base::FilePath& current_directory) {
328 // An app with "kiosk_only" should not be installed and launched
329 // outside of ChromeOS kiosk mode in the first place. This is a defensive
330 // check in case this scenario does occur.
331 if (extensions::KioskModeInfo::IsKioskOnly(extension)) {
332 bool in_kiosk_mode = false;
333 #if defined(OS_CHROMEOS)
334 chromeos::UserManager* user_manager = chromeos::UserManager::Get();
335 in_kiosk_mode = user_manager && user_manager->IsLoggedInAsKioskApp();
336 #endif
337 if (!in_kiosk_mode) {
338 LOG(ERROR) << "App with 'kiosk_only' attribute must be run in "
339 << " ChromeOS kiosk mode.";
340 NOTREACHED();
341 return;
345 base::FilePath path;
346 if (!GetAbsolutePathFromCommandLine(command_line, current_directory, &path)) {
347 LaunchPlatformAppWithNoData(profile, extension);
348 return;
351 // TODO(benwells): add a command-line argument to provide a handler ID.
352 LaunchPlatformAppWithPath(profile, extension, path);
355 void LaunchPlatformAppWithPath(Profile* profile,
356 const Extension* extension,
357 const base::FilePath& file_path) {
358 // launcher will be freed when nothing has a reference to it. The message
359 // queue will retain a reference for any outstanding task, so when the
360 // launcher has finished it will be freed.
361 scoped_refptr<PlatformAppPathLauncher> launcher =
362 new PlatformAppPathLauncher(profile, extension, file_path);
363 launcher->Launch();
366 void LaunchPlatformApp(Profile* profile, const Extension* extension) {
367 LaunchPlatformAppWithCommandLine(profile,
368 extension,
369 CommandLine(CommandLine::NO_PROGRAM),
370 base::FilePath());
373 void LaunchPlatformAppWithFileHandler(Profile* profile,
374 const Extension* extension,
375 const std::string& handler_id,
376 const base::FilePath& file_path) {
377 scoped_refptr<PlatformAppPathLauncher> launcher =
378 new PlatformAppPathLauncher(profile, extension, file_path);
379 launcher->LaunchWithHandler(handler_id);
382 void RestartPlatformApp(Profile* profile, const Extension* extension) {
383 EventRouter* event_router = EventRouter::Get(profile);
384 bool listening_to_restart = event_router->
385 ExtensionHasEventListener(extension->id(),
386 app_runtime::OnRestarted::kEventName);
388 if (listening_to_restart) {
389 AppEventRouter::DispatchOnRestartedEvent(profile, extension);
390 return;
393 extensions::ExtensionPrefs* extension_prefs =
394 extensions::ExtensionPrefs::Get(profile);
395 bool had_windows = extension_prefs->IsActive(extension->id());
396 extension_prefs->SetIsActive(extension->id(), false);
397 bool listening_to_launch = event_router->
398 ExtensionHasEventListener(extension->id(),
399 app_runtime::OnLaunched::kEventName);
401 if (listening_to_launch && had_windows)
402 LaunchPlatformAppWithNoData(profile, extension);
405 void LaunchPlatformAppWithUrl(Profile* profile,
406 const Extension* extension,
407 const std::string& handler_id,
408 const GURL& url,
409 const GURL& referrer_url) {
410 AppEventRouter::DispatchOnLaunchedEventWithUrl(
411 profile, extension, handler_id, url, referrer_url);
414 } // namespace apps