NaCl: Update revision in DEPS, r13580 -> r13592
[chromium-blink-merge.git] / apps / launcher.cc
blobca463de5f1e438ee43b6d03feacc731e6b5489ad
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 <utility>
8 #include <set>
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_handlers/mime_util.h"
19 #include "chrome/browser/extensions/api/file_system/file_system_api.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "content/public/browser/browser_thread.h"
22 #include "content/public/browser/render_process_host.h"
23 #include "content/public/browser/web_contents.h"
24 #include "content/public/common/content_switches.h"
25 #include "content/public/common/url_constants.h"
26 #include "extensions/browser/api/app_runtime/app_runtime_api.h"
27 #include "extensions/browser/event_router.h"
28 #include "extensions/browser/extension_host.h"
29 #include "extensions/browser/extension_prefs.h"
30 #include "extensions/browser/extension_system.h"
31 #include "extensions/browser/granted_file_entry.h"
32 #include "extensions/browser/lazy_background_task_queue.h"
33 #include "extensions/browser/process_manager.h"
34 #include "extensions/common/api/app_runtime.h"
35 #include "extensions/common/extension.h"
36 #include "extensions/common/extension_messages.h"
37 #include "extensions/common/manifest_handlers/kiosk_mode_info.h"
38 #include "net/base/filename_util.h"
39 #include "net/base/net_util.h"
40 #include "url/gurl.h"
42 #if defined(OS_CHROMEOS)
43 #include "chrome/browser/chromeos/login/users/user_manager.h"
44 #endif
46 namespace app_runtime = extensions::core_api::app_runtime;
48 using content::BrowserThread;
49 using extensions::AppRuntimeEventRouter;
50 using extensions::app_file_handler_util::CreateFileEntry;
51 using extensions::app_file_handler_util::FileHandlerCanHandleFile;
52 using extensions::app_file_handler_util::FileHandlerForId;
53 using extensions::app_file_handler_util::FirstFileHandlerForFile;
54 using extensions::app_file_handler_util::HasFileSystemWritePermission;
55 using extensions::app_file_handler_util::PrepareFilesForWritableApp;
56 using extensions::EventRouter;
57 using extensions::Extension;
58 using extensions::ExtensionHost;
59 using extensions::ExtensionSystem;
60 using extensions::GrantedFileEntry;
62 namespace apps {
64 namespace {
66 const char kFallbackMimeType[] = "application/octet-stream";
68 bool DoMakePathAbsolute(const base::FilePath& current_directory,
69 base::FilePath* file_path) {
70 DCHECK(file_path);
71 if (file_path->IsAbsolute())
72 return true;
74 if (current_directory.empty()) {
75 *file_path = base::MakeAbsoluteFilePath(*file_path);
76 return !file_path->empty();
79 if (!current_directory.IsAbsolute())
80 return false;
82 *file_path = current_directory.Append(*file_path);
83 return true;
86 // Helper method to launch the platform app |extension| with no data. This
87 // should be called in the fallback case, where it has been impossible to
88 // load or obtain file launch data.
89 void LaunchPlatformAppWithNoData(Profile* profile, const Extension* extension) {
90 DCHECK_CURRENTLY_ON(BrowserThread::UI);
91 AppRuntimeEventRouter::DispatchOnLaunchedEvent(profile, extension);
94 // Class to handle launching of platform apps to open specific paths.
95 // An instance of this class is created for each launch. The lifetime of these
96 // instances is managed by reference counted pointers. As long as an instance
97 // has outstanding tasks on a message queue it will be retained; once all
98 // outstanding tasks are completed it will be deleted.
99 class PlatformAppPathLauncher
100 : public base::RefCountedThreadSafe<PlatformAppPathLauncher> {
101 public:
102 PlatformAppPathLauncher(Profile* profile,
103 const Extension* extension,
104 const std::vector<base::FilePath>& file_paths)
105 : profile_(profile),
106 extension_(extension),
107 file_paths_(file_paths),
108 collector_(profile) {}
110 PlatformAppPathLauncher(Profile* profile,
111 const Extension* extension,
112 const base::FilePath& file_path)
113 : profile_(profile), extension_(extension), collector_(profile) {
114 if (!file_path.empty())
115 file_paths_.push_back(file_path);
118 void Launch() {
119 DCHECK_CURRENTLY_ON(BrowserThread::UI);
120 if (file_paths_.empty()) {
121 LaunchPlatformAppWithNoData(profile_, extension_);
122 return;
125 for (size_t i = 0; i < file_paths_.size(); ++i) {
126 DCHECK(file_paths_[i].IsAbsolute());
129 if (HasFileSystemWritePermission(extension_)) {
130 PrepareFilesForWritableApp(
131 file_paths_,
132 profile_,
133 false,
134 base::Bind(&PlatformAppPathLauncher::OnFilesValid, this),
135 base::Bind(&PlatformAppPathLauncher::OnFilesInvalid, this));
136 return;
139 OnFilesValid();
142 void LaunchWithHandler(const std::string& handler_id) {
143 handler_id_ = handler_id;
144 Launch();
147 void LaunchWithRelativePath(const base::FilePath& current_directory) {
148 BrowserThread::PostTask(
149 BrowserThread::FILE,
150 FROM_HERE,
151 base::Bind(&PlatformAppPathLauncher::MakePathAbsolute,
152 this,
153 current_directory));
156 private:
157 friend class base::RefCountedThreadSafe<PlatformAppPathLauncher>;
159 virtual ~PlatformAppPathLauncher() {}
161 void MakePathAbsolute(const base::FilePath& current_directory) {
162 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
164 for (std::vector<base::FilePath>::iterator it = file_paths_.begin();
165 it != file_paths_.end();
166 ++it) {
167 if (!DoMakePathAbsolute(current_directory, &*it)) {
168 LOG(WARNING) << "Cannot make absolute path from " << it->value();
169 BrowserThread::PostTask(
170 BrowserThread::UI,
171 FROM_HERE,
172 base::Bind(&PlatformAppPathLauncher::LaunchWithNoLaunchData, this));
173 return;
177 BrowserThread::PostTask(BrowserThread::UI,
178 FROM_HERE,
179 base::Bind(&PlatformAppPathLauncher::Launch, this));
182 void OnFilesValid() {
183 collector_.CollectForLocalPaths(
184 file_paths_,
185 base::Bind(&PlatformAppPathLauncher::OnMimeTypesCollected, this));
188 void OnFilesInvalid(const base::FilePath& /* error_path */) {
189 LaunchWithNoLaunchData();
192 void LaunchWithNoLaunchData() {
193 // This method is required as an entry point on the UI thread.
194 LaunchPlatformAppWithNoData(profile_, extension_);
197 void OnMimeTypesCollected(scoped_ptr<std::vector<std::string> > mime_types) {
198 DCHECK(file_paths_.size() == mime_types->size());
200 // If fetching a mime type failed, then use a fallback one.
201 for (size_t i = 0; i < mime_types->size(); ++i) {
202 const std::string mime_type =
203 !(*mime_types)[i].empty() ? (*mime_types)[i] : kFallbackMimeType;
204 mime_types_.push_back(mime_type);
207 // Find file handler from the platform app for the file being opened.
208 const extensions::FileHandlerInfo* handler = NULL;
209 if (!handler_id_.empty()) {
210 handler = FileHandlerForId(*extension_, handler_id_);
211 if (handler) {
212 for (size_t i = 0; i < file_paths_.size(); ++i) {
213 if (!FileHandlerCanHandleFile(
214 *handler, mime_types_[i], file_paths_[i])) {
215 LOG(WARNING)
216 << "Extension does not provide a valid file handler for "
217 << file_paths_[i].value();
218 handler = NULL;
219 break;
223 } else {
224 std::set<std::pair<base::FilePath, std::string> > path_and_file_type_set;
225 for (size_t i = 0; i < file_paths_.size(); ++i) {
226 path_and_file_type_set.insert(
227 std::make_pair(file_paths_[i], mime_types_[i]));
229 const std::vector<const extensions::FileHandlerInfo*>& handlers =
230 extensions::app_file_handler_util::FindFileHandlersForFiles(
231 *extension_, path_and_file_type_set);
232 if (!handlers.empty())
233 handler = handlers[0];
236 // If this app doesn't have a file handler that supports the file, launch
237 // with no launch data.
238 if (!handler) {
239 LOG(WARNING) << "Extension does not provide a valid file handler.";
240 LaunchWithNoLaunchData();
241 return;
244 if (handler_id_.empty())
245 handler_id_ = handler->id;
247 // Access needs to be granted to the file for the process associated with
248 // the extension. To do this the ExtensionHost is needed. This might not be
249 // available, or it might be in the process of being unloaded, in which case
250 // the lazy background task queue is used to load the extension and then
251 // call back to us.
252 extensions::LazyBackgroundTaskQueue* const queue =
253 ExtensionSystem::Get(profile_)->lazy_background_task_queue();
254 if (queue->ShouldEnqueueTask(profile_, extension_)) {
255 queue->AddPendingTask(
256 profile_,
257 extension_->id(),
258 base::Bind(&PlatformAppPathLauncher::GrantAccessToFilesAndLaunch,
259 this));
260 return;
263 extensions::ProcessManager* const process_manager =
264 ExtensionSystem::Get(profile_)->process_manager();
265 ExtensionHost* const host =
266 process_manager->GetBackgroundHostForExtension(extension_->id());
267 DCHECK(host);
268 GrantAccessToFilesAndLaunch(host);
271 void GrantAccessToFilesAndLaunch(ExtensionHost* host) {
272 // If there was an error loading the app page, |host| will be NULL.
273 if (!host) {
274 LOG(ERROR) << "Could not load app page for " << extension_->id();
275 return;
278 std::vector<GrantedFileEntry> file_entries;
279 for (size_t i = 0; i < file_paths_.size(); ++i) {
280 file_entries.push_back(
281 CreateFileEntry(profile_,
282 extension_,
283 host->render_process_host()->GetID(),
284 file_paths_[i],
285 false));
288 AppRuntimeEventRouter::DispatchOnLaunchedEventWithFileEntries(
289 profile_, extension_, handler_id_, mime_types_, file_entries);
292 // The profile the app should be run in.
293 Profile* profile_;
294 // The extension providing the app.
295 // TODO(benwells): Hold onto the extension ID instead of a pointer as it
296 // is possible the extension will be unloaded while we're doing our thing.
297 // See http://crbug.com/372270 for details.
298 const Extension* extension_;
299 // The path to be passed through to the app.
300 std::vector<base::FilePath> file_paths_;
301 std::vector<std::string> mime_types_;
302 // The ID of the file handler used to launch the app.
303 std::string handler_id_;
304 extensions::app_file_handler_util::MimeTypeCollector collector_;
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 // An app with "kiosk_only" should not be installed and launched
316 // outside of ChromeOS kiosk mode in the first place. This is a defensive
317 // check in case this scenario does occur.
318 if (extensions::KioskModeInfo::IsKioskOnly(extension)) {
319 bool in_kiosk_mode = false;
320 #if defined(OS_CHROMEOS)
321 chromeos::UserManager* user_manager = chromeos::UserManager::Get();
322 in_kiosk_mode = user_manager && user_manager->IsLoggedInAsKioskApp();
323 #endif
324 if (!in_kiosk_mode) {
325 LOG(ERROR) << "App with 'kiosk_only' attribute must be run in "
326 << " ChromeOS kiosk mode.";
327 NOTREACHED();
328 return;
332 #if defined(OS_WIN)
333 base::CommandLine::StringType about_blank_url(
334 base::ASCIIToWide(url::kAboutBlankURL));
335 #else
336 base::CommandLine::StringType about_blank_url(url::kAboutBlankURL);
337 #endif
338 CommandLine::StringVector args = command_line.GetArgs();
339 // Browser tests will add about:blank to the command line. This should
340 // never be interpreted as a file to open, as doing so with an app that
341 // has write access will result in a file 'about' being created, which
342 // causes problems on the bots.
343 if (args.empty() || (command_line.HasSwitch(switches::kTestType) &&
344 args[0] == about_blank_url)) {
345 LaunchPlatformAppWithNoData(profile, extension);
346 return;
349 base::FilePath file_path(command_line.GetArgs()[0]);
350 scoped_refptr<PlatformAppPathLauncher> launcher =
351 new PlatformAppPathLauncher(profile, extension, file_path);
352 launcher->LaunchWithRelativePath(current_directory);
355 void LaunchPlatformAppWithPath(Profile* profile,
356 const Extension* extension,
357 const base::FilePath& file_path) {
358 scoped_refptr<PlatformAppPathLauncher> launcher =
359 new PlatformAppPathLauncher(profile, extension, file_path);
360 launcher->Launch();
363 void LaunchPlatformApp(Profile* profile, const Extension* extension) {
364 LaunchPlatformAppWithCommandLine(profile,
365 extension,
366 CommandLine(CommandLine::NO_PROGRAM),
367 base::FilePath());
370 void LaunchPlatformAppWithFileHandler(
371 Profile* profile,
372 const Extension* extension,
373 const std::string& handler_id,
374 const std::vector<base::FilePath>& file_paths) {
375 scoped_refptr<PlatformAppPathLauncher> launcher =
376 new PlatformAppPathLauncher(profile, extension, file_paths);
377 launcher->LaunchWithHandler(handler_id);
380 void RestartPlatformApp(Profile* profile, const Extension* extension) {
381 EventRouter* event_router = EventRouter::Get(profile);
382 bool listening_to_restart = event_router->
383 ExtensionHasEventListener(extension->id(),
384 app_runtime::OnRestarted::kEventName);
386 if (listening_to_restart) {
387 AppRuntimeEventRouter::DispatchOnRestartedEvent(profile, extension);
388 return;
391 extensions::ExtensionPrefs* extension_prefs =
392 extensions::ExtensionPrefs::Get(profile);
393 bool had_windows = extension_prefs->IsActive(extension->id());
394 extension_prefs->SetIsActive(extension->id(), false);
395 bool listening_to_launch = event_router->
396 ExtensionHasEventListener(extension->id(),
397 app_runtime::OnLaunched::kEventName);
399 if (listening_to_launch && had_windows)
400 LaunchPlatformAppWithNoData(profile, extension);
403 void LaunchPlatformAppWithUrl(Profile* profile,
404 const Extension* extension,
405 const std::string& handler_id,
406 const GURL& url,
407 const GURL& referrer_url) {
408 AppRuntimeEventRouter::DispatchOnLaunchedEventWithUrl(
409 profile, extension, handler_id, url, referrer_url);
412 } // namespace apps