[Android] Rename [Chromium -> Chrome]NativeTestInstrumentationTestRunner.
[chromium-blink-merge.git] / apps / launcher.cc
blobcda74ac144969d99de88c801dd690c761403e488
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 <set>
8 #include <utility>
10 #include "base/command_line.h"
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.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_registry.h"
31 #include "extensions/browser/extension_system.h"
32 #include "extensions/browser/granted_file_entry.h"
33 #include "extensions/browser/lazy_background_task_queue.h"
34 #include "extensions/browser/process_manager.h"
35 #include "extensions/common/api/app_runtime.h"
36 #include "extensions/common/extension.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 "components/user_manager/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 base::FilePath absolute_path = base::MakeAbsoluteFilePath(*file_path);
76 if (absolute_path.empty())
77 return false;
78 *file_path = absolute_path;
79 return true;
82 if (!current_directory.IsAbsolute())
83 return false;
85 *file_path = current_directory.Append(*file_path);
86 return true;
89 // Class to handle launching of platform apps to open specific paths.
90 // An instance of this class is created for each launch. The lifetime of these
91 // instances is managed by reference counted pointers. As long as an instance
92 // has outstanding tasks on a message queue it will be retained; once all
93 // outstanding tasks are completed it will be deleted.
94 class PlatformAppPathLauncher
95 : public base::RefCountedThreadSafe<PlatformAppPathLauncher> {
96 public:
97 PlatformAppPathLauncher(Profile* profile,
98 const Extension* extension,
99 const std::vector<base::FilePath>& file_paths)
100 : profile_(profile),
101 extension_id(extension->id()),
102 file_paths_(file_paths),
103 collector_(profile) {}
105 PlatformAppPathLauncher(Profile* profile,
106 const Extension* extension,
107 const base::FilePath& file_path)
108 : profile_(profile), extension_id(extension->id()), collector_(profile) {
109 if (!file_path.empty())
110 file_paths_.push_back(file_path);
113 void Launch() {
114 DCHECK_CURRENTLY_ON(BrowserThread::UI);
116 const Extension* extension = GetExtension();
117 if (!extension)
118 return;
120 if (file_paths_.empty()) {
121 LaunchWithNoLaunchData();
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 DCHECK_CURRENTLY_ON(BrowserThread::UI);
196 const Extension* extension = GetExtension();
197 if (!extension)
198 return;
200 AppRuntimeEventRouter::DispatchOnLaunchedEvent(
201 profile_, extension, extensions::SOURCE_FILE_HANDLER);
204 void OnMimeTypesCollected(scoped_ptr<std::vector<std::string> > mime_types) {
205 DCHECK(file_paths_.size() == mime_types->size());
207 const Extension* extension = GetExtension();
208 if (!extension)
209 return;
211 // If fetching a mime type failed, then use a fallback one.
212 for (size_t i = 0; i < mime_types->size(); ++i) {
213 const std::string mime_type =
214 !(*mime_types)[i].empty() ? (*mime_types)[i] : kFallbackMimeType;
215 mime_types_.push_back(mime_type);
218 // Find file handler from the platform app for the file being opened.
219 const extensions::FileHandlerInfo* handler = NULL;
220 if (!handler_id_.empty()) {
221 handler = FileHandlerForId(*extension, handler_id_);
222 if (handler) {
223 for (size_t i = 0; i < file_paths_.size(); ++i) {
224 if (!FileHandlerCanHandleFile(
225 *handler, mime_types_[i], file_paths_[i])) {
226 LOG(WARNING)
227 << "Extension does not provide a valid file handler for "
228 << file_paths_[i].value();
229 handler = NULL;
230 break;
234 } else {
235 std::set<std::pair<base::FilePath, std::string> > path_and_file_type_set;
236 for (size_t i = 0; i < file_paths_.size(); ++i) {
237 path_and_file_type_set.insert(
238 std::make_pair(file_paths_[i], mime_types_[i]));
240 const std::vector<const extensions::FileHandlerInfo*>& handlers =
241 extensions::app_file_handler_util::FindFileHandlersForFiles(
242 *extension, path_and_file_type_set);
243 if (!handlers.empty())
244 handler = handlers[0];
247 // If this app doesn't have a file handler that supports the file, launch
248 // with no launch data.
249 if (!handler) {
250 LOG(WARNING) << "Extension does not provide a valid file handler.";
251 LaunchWithNoLaunchData();
252 return;
255 if (handler_id_.empty())
256 handler_id_ = handler->id;
258 // Access needs to be granted to the file for the process associated with
259 // the extension. To do this the ExtensionHost is needed. This might not be
260 // available, or it might be in the process of being unloaded, in which case
261 // the lazy background task queue is used to load the extension and then
262 // call back to us.
263 extensions::LazyBackgroundTaskQueue* const queue =
264 ExtensionSystem::Get(profile_)->lazy_background_task_queue();
265 if (queue->ShouldEnqueueTask(profile_, extension)) {
266 queue->AddPendingTask(
267 profile_, extension_id,
268 base::Bind(&PlatformAppPathLauncher::GrantAccessToFilesAndLaunch,
269 this));
270 return;
273 extensions::ProcessManager* const process_manager =
274 extensions::ProcessManager::Get(profile_);
275 ExtensionHost* const host =
276 process_manager->GetBackgroundHostForExtension(extension_id);
277 DCHECK(host);
278 GrantAccessToFilesAndLaunch(host);
281 void GrantAccessToFilesAndLaunch(ExtensionHost* host) {
282 const Extension* extension = GetExtension();
283 if (!extension)
284 return;
286 // If there was an error loading the app page, |host| will be NULL.
287 if (!host) {
288 LOG(ERROR) << "Could not load app page for " << extension_id;
289 return;
292 std::vector<GrantedFileEntry> file_entries;
293 for (size_t i = 0; i < file_paths_.size(); ++i) {
294 file_entries.push_back(CreateFileEntry(
295 profile_, extension, host->render_process_host()->GetID(),
296 file_paths_[i], false));
299 AppRuntimeEventRouter::DispatchOnLaunchedEventWithFileEntries(
300 profile_, extension, handler_id_, mime_types_, file_entries);
303 const Extension* GetExtension() const {
304 return extensions::ExtensionRegistry::Get(profile_)->GetExtensionById(
305 extension_id, extensions::ExtensionRegistry::EVERYTHING);
308 // The profile the app should be run in.
309 Profile* profile_;
310 // The id of the extension providing the app. A pointer to the extension is
311 // not kept as the extension may be unloaded and deleted during the course of
312 // the launch.
313 const std::string extension_id;
314 // The path to be passed through to the app.
315 std::vector<base::FilePath> file_paths_;
316 std::vector<std::string> mime_types_;
317 // The ID of the file handler used to launch the app.
318 std::string handler_id_;
319 extensions::app_file_handler_util::MimeTypeCollector collector_;
321 DISALLOW_COPY_AND_ASSIGN(PlatformAppPathLauncher);
324 } // namespace
326 void LaunchPlatformAppWithCommandLine(Profile* profile,
327 const Extension* extension,
328 const base::CommandLine& command_line,
329 const base::FilePath& current_directory,
330 extensions::AppLaunchSource source) {
331 // An app with "kiosk_only" should not be installed and launched
332 // outside of ChromeOS kiosk mode in the first place. This is a defensive
333 // check in case this scenario does occur.
334 if (extensions::KioskModeInfo::IsKioskOnly(extension)) {
335 bool in_kiosk_mode = false;
336 #if defined(OS_CHROMEOS)
337 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
338 in_kiosk_mode = user_manager && user_manager->IsLoggedInAsKioskApp();
339 #endif
340 if (!in_kiosk_mode) {
341 LOG(ERROR) << "App with 'kiosk_only' attribute must be run in "
342 << " ChromeOS kiosk mode.";
343 NOTREACHED();
344 return;
348 #if defined(OS_WIN)
349 base::CommandLine::StringType about_blank_url(
350 base::ASCIIToUTF16(url::kAboutBlankURL));
351 #else
352 base::CommandLine::StringType about_blank_url(url::kAboutBlankURL);
353 #endif
354 base::CommandLine::StringVector args = command_line.GetArgs();
355 // Browser tests will add about:blank to the command line. This should
356 // never be interpreted as a file to open, as doing so with an app that
357 // has write access will result in a file 'about' being created, which
358 // causes problems on the bots.
359 if (args.empty() || (command_line.HasSwitch(switches::kTestType) &&
360 args[0] == about_blank_url)) {
361 AppRuntimeEventRouter::DispatchOnLaunchedEvent(profile, extension, source);
362 return;
365 base::FilePath file_path(command_line.GetArgs()[0]);
366 scoped_refptr<PlatformAppPathLauncher> launcher =
367 new PlatformAppPathLauncher(profile, extension, file_path);
368 launcher->LaunchWithRelativePath(current_directory);
371 void LaunchPlatformAppWithPath(Profile* profile,
372 const Extension* extension,
373 const base::FilePath& file_path) {
374 scoped_refptr<PlatformAppPathLauncher> launcher =
375 new PlatformAppPathLauncher(profile, extension, file_path);
376 launcher->Launch();
379 void LaunchPlatformApp(Profile* profile,
380 const Extension* extension,
381 extensions::AppLaunchSource source) {
382 LaunchPlatformAppWithCommandLine(
383 profile,
384 extension,
385 base::CommandLine(base::CommandLine::NO_PROGRAM),
386 base::FilePath(),
387 source);
390 void LaunchPlatformAppWithFileHandler(
391 Profile* profile,
392 const Extension* extension,
393 const std::string& handler_id,
394 const std::vector<base::FilePath>& file_paths) {
395 scoped_refptr<PlatformAppPathLauncher> launcher =
396 new PlatformAppPathLauncher(profile, extension, file_paths);
397 launcher->LaunchWithHandler(handler_id);
400 void RestartPlatformApp(Profile* profile, const Extension* extension) {
401 EventRouter* event_router = EventRouter::Get(profile);
402 bool listening_to_restart = event_router->
403 ExtensionHasEventListener(extension->id(),
404 app_runtime::OnRestarted::kEventName);
406 if (listening_to_restart) {
407 AppRuntimeEventRouter::DispatchOnRestartedEvent(profile, extension);
408 return;
411 extensions::ExtensionPrefs* extension_prefs =
412 extensions::ExtensionPrefs::Get(profile);
413 bool had_windows = extension_prefs->IsActive(extension->id());
414 extension_prefs->SetIsActive(extension->id(), false);
415 bool listening_to_launch = event_router->
416 ExtensionHasEventListener(extension->id(),
417 app_runtime::OnLaunched::kEventName);
419 if (listening_to_launch && had_windows) {
420 AppRuntimeEventRouter::DispatchOnLaunchedEvent(
421 profile, extension, extensions::SOURCE_RESTART);
425 void LaunchPlatformAppWithUrl(Profile* profile,
426 const Extension* extension,
427 const std::string& handler_id,
428 const GURL& url,
429 const GURL& referrer_url) {
430 AppRuntimeEventRouter::DispatchOnLaunchedEventWithUrl(
431 profile, extension, handler_id, url, referrer_url);
434 } // namespace apps