Added 4 bytes to font file name constant to align on 8 byte boundary and statisfy...
[chromium-blink-merge.git] / apps / launcher.cc
blob25c3a5f2bd14e4de31ab50dfba264101792a4054
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_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/manifest_handlers/kiosk_mode_info.h"
37 #include "net/base/filename_util.h"
38 #include "net/base/net_util.h"
39 #include "url/gurl.h"
41 #if defined(OS_CHROMEOS)
42 #include "components/user_manager/user_manager.h"
43 #endif
45 namespace app_runtime = extensions::core_api::app_runtime;
47 using content::BrowserThread;
48 using extensions::AppRuntimeEventRouter;
49 using extensions::app_file_handler_util::CreateFileEntry;
50 using extensions::app_file_handler_util::FileHandlerCanHandleFile;
51 using extensions::app_file_handler_util::FileHandlerForId;
52 using extensions::app_file_handler_util::FirstFileHandlerForFile;
53 using extensions::app_file_handler_util::HasFileSystemWritePermission;
54 using extensions::app_file_handler_util::PrepareFilesForWritableApp;
55 using extensions::EventRouter;
56 using extensions::Extension;
57 using extensions::ExtensionHost;
58 using extensions::ExtensionSystem;
59 using extensions::GrantedFileEntry;
61 namespace apps {
63 namespace {
65 const char kFallbackMimeType[] = "application/octet-stream";
67 bool DoMakePathAbsolute(const base::FilePath& current_directory,
68 base::FilePath* file_path) {
69 DCHECK(file_path);
70 if (file_path->IsAbsolute())
71 return true;
73 if (current_directory.empty()) {
74 base::FilePath absolute_path = base::MakeAbsoluteFilePath(*file_path);
75 if (absolute_path.empty())
76 return false;
77 *file_path = absolute_path;
78 return true;
81 if (!current_directory.IsAbsolute())
82 return false;
84 *file_path = current_directory.Append(*file_path);
85 return true;
88 // Class to handle launching of platform apps to open specific paths.
89 // An instance of this class is created for each launch. The lifetime of these
90 // instances is managed by reference counted pointers. As long as an instance
91 // has outstanding tasks on a message queue it will be retained; once all
92 // outstanding tasks are completed it will be deleted.
93 class PlatformAppPathLauncher
94 : public base::RefCountedThreadSafe<PlatformAppPathLauncher> {
95 public:
96 PlatformAppPathLauncher(Profile* profile,
97 const Extension* extension,
98 const std::vector<base::FilePath>& file_paths)
99 : profile_(profile),
100 extension_(extension),
101 file_paths_(file_paths),
102 collector_(profile) {}
104 PlatformAppPathLauncher(Profile* profile,
105 const Extension* extension,
106 const base::FilePath& file_path)
107 : profile_(profile), extension_(extension), collector_(profile) {
108 if (!file_path.empty())
109 file_paths_.push_back(file_path);
112 void Launch() {
113 DCHECK_CURRENTLY_ON(BrowserThread::UI);
114 if (file_paths_.empty()) {
115 LaunchWithNoLaunchData();
116 return;
119 for (size_t i = 0; i < file_paths_.size(); ++i) {
120 DCHECK(file_paths_[i].IsAbsolute());
123 if (HasFileSystemWritePermission(extension_)) {
124 PrepareFilesForWritableApp(
125 file_paths_,
126 profile_,
127 false,
128 base::Bind(&PlatformAppPathLauncher::OnFilesValid, this),
129 base::Bind(&PlatformAppPathLauncher::OnFilesInvalid, this));
130 return;
133 OnFilesValid();
136 void LaunchWithHandler(const std::string& handler_id) {
137 handler_id_ = handler_id;
138 Launch();
141 void LaunchWithRelativePath(const base::FilePath& current_directory) {
142 BrowserThread::PostTask(
143 BrowserThread::FILE,
144 FROM_HERE,
145 base::Bind(&PlatformAppPathLauncher::MakePathAbsolute,
146 this,
147 current_directory));
150 private:
151 friend class base::RefCountedThreadSafe<PlatformAppPathLauncher>;
153 virtual ~PlatformAppPathLauncher() {}
155 void MakePathAbsolute(const base::FilePath& current_directory) {
156 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
158 for (std::vector<base::FilePath>::iterator it = file_paths_.begin();
159 it != file_paths_.end();
160 ++it) {
161 if (!DoMakePathAbsolute(current_directory, &*it)) {
162 LOG(WARNING) << "Cannot make absolute path from " << it->value();
163 BrowserThread::PostTask(
164 BrowserThread::UI,
165 FROM_HERE,
166 base::Bind(&PlatformAppPathLauncher::LaunchWithNoLaunchData, this));
167 return;
171 BrowserThread::PostTask(BrowserThread::UI,
172 FROM_HERE,
173 base::Bind(&PlatformAppPathLauncher::Launch, this));
176 void OnFilesValid() {
177 collector_.CollectForLocalPaths(
178 file_paths_,
179 base::Bind(&PlatformAppPathLauncher::OnMimeTypesCollected, this));
182 void OnFilesInvalid(const base::FilePath& /* error_path */) {
183 LaunchWithNoLaunchData();
186 void LaunchWithNoLaunchData() {
187 // This method is required as an entry point on the UI thread.
188 DCHECK_CURRENTLY_ON(BrowserThread::UI);
189 AppRuntimeEventRouter::DispatchOnLaunchedEvent(
190 profile_, extension_, extensions::SOURCE_FILE_HANDLER);
193 void OnMimeTypesCollected(scoped_ptr<std::vector<std::string> > mime_types) {
194 DCHECK(file_paths_.size() == mime_types->size());
196 // If fetching a mime type failed, then use a fallback one.
197 for (size_t i = 0; i < mime_types->size(); ++i) {
198 const std::string mime_type =
199 !(*mime_types)[i].empty() ? (*mime_types)[i] : kFallbackMimeType;
200 mime_types_.push_back(mime_type);
203 // Find file handler from the platform app for the file being opened.
204 const extensions::FileHandlerInfo* handler = NULL;
205 if (!handler_id_.empty()) {
206 handler = FileHandlerForId(*extension_, handler_id_);
207 if (handler) {
208 for (size_t i = 0; i < file_paths_.size(); ++i) {
209 if (!FileHandlerCanHandleFile(
210 *handler, mime_types_[i], file_paths_[i])) {
211 LOG(WARNING)
212 << "Extension does not provide a valid file handler for "
213 << file_paths_[i].value();
214 handler = NULL;
215 break;
219 } else {
220 std::set<std::pair<base::FilePath, std::string> > path_and_file_type_set;
221 for (size_t i = 0; i < file_paths_.size(); ++i) {
222 path_and_file_type_set.insert(
223 std::make_pair(file_paths_[i], mime_types_[i]));
225 const std::vector<const extensions::FileHandlerInfo*>& handlers =
226 extensions::app_file_handler_util::FindFileHandlersForFiles(
227 *extension_, path_and_file_type_set);
228 if (!handlers.empty())
229 handler = handlers[0];
232 // If this app doesn't have a file handler that supports the file, launch
233 // with no launch data.
234 if (!handler) {
235 LOG(WARNING) << "Extension does not provide a valid file handler.";
236 LaunchWithNoLaunchData();
237 return;
240 if (handler_id_.empty())
241 handler_id_ = handler->id;
243 // Access needs to be granted to the file for the process associated with
244 // the extension. To do this the ExtensionHost is needed. This might not be
245 // available, or it might be in the process of being unloaded, in which case
246 // the lazy background task queue is used to load the extension and then
247 // call back to us.
248 extensions::LazyBackgroundTaskQueue* const queue =
249 ExtensionSystem::Get(profile_)->lazy_background_task_queue();
250 if (queue->ShouldEnqueueTask(profile_, extension_)) {
251 queue->AddPendingTask(
252 profile_,
253 extension_->id(),
254 base::Bind(&PlatformAppPathLauncher::GrantAccessToFilesAndLaunch,
255 this));
256 return;
259 extensions::ProcessManager* const process_manager =
260 extensions::ProcessManager::Get(profile_);
261 ExtensionHost* const host =
262 process_manager->GetBackgroundHostForExtension(extension_->id());
263 DCHECK(host);
264 GrantAccessToFilesAndLaunch(host);
267 void GrantAccessToFilesAndLaunch(ExtensionHost* host) {
268 // If there was an error loading the app page, |host| will be NULL.
269 if (!host) {
270 LOG(ERROR) << "Could not load app page for " << extension_->id();
271 return;
274 std::vector<GrantedFileEntry> file_entries;
275 for (size_t i = 0; i < file_paths_.size(); ++i) {
276 file_entries.push_back(
277 CreateFileEntry(profile_,
278 extension_,
279 host->render_process_host()->GetID(),
280 file_paths_[i],
281 false));
284 AppRuntimeEventRouter::DispatchOnLaunchedEventWithFileEntries(
285 profile_, extension_, handler_id_, mime_types_, file_entries);
288 // The profile the app should be run in.
289 Profile* profile_;
290 // The extension providing the app.
291 // TODO(benwells): Hold onto the extension ID instead of a pointer as it
292 // is possible the extension will be unloaded while we're doing our thing.
293 // See http://crbug.com/372270 for details.
294 const Extension* extension_;
295 // The path to be passed through to the app.
296 std::vector<base::FilePath> file_paths_;
297 std::vector<std::string> mime_types_;
298 // The ID of the file handler used to launch the app.
299 std::string handler_id_;
300 extensions::app_file_handler_util::MimeTypeCollector collector_;
302 DISALLOW_COPY_AND_ASSIGN(PlatformAppPathLauncher);
305 } // namespace
307 void LaunchPlatformAppWithCommandLine(Profile* profile,
308 const Extension* extension,
309 const base::CommandLine& command_line,
310 const base::FilePath& current_directory,
311 extensions::AppLaunchSource source) {
312 // An app with "kiosk_only" should not be installed and launched
313 // outside of ChromeOS kiosk mode in the first place. This is a defensive
314 // check in case this scenario does occur.
315 if (extensions::KioskModeInfo::IsKioskOnly(extension)) {
316 bool in_kiosk_mode = false;
317 #if defined(OS_CHROMEOS)
318 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
319 in_kiosk_mode = user_manager && user_manager->IsLoggedInAsKioskApp();
320 #endif
321 if (!in_kiosk_mode) {
322 LOG(ERROR) << "App with 'kiosk_only' attribute must be run in "
323 << " ChromeOS kiosk mode.";
324 NOTREACHED();
325 return;
329 #if defined(OS_WIN)
330 base::CommandLine::StringType about_blank_url(
331 base::ASCIIToUTF16(url::kAboutBlankURL));
332 #else
333 base::CommandLine::StringType about_blank_url(url::kAboutBlankURL);
334 #endif
335 base::CommandLine::StringVector args = command_line.GetArgs();
336 // Browser tests will add about:blank to the command line. This should
337 // never be interpreted as a file to open, as doing so with an app that
338 // has write access will result in a file 'about' being created, which
339 // causes problems on the bots.
340 if (args.empty() || (command_line.HasSwitch(switches::kTestType) &&
341 args[0] == about_blank_url)) {
342 AppRuntimeEventRouter::DispatchOnLaunchedEvent(profile, extension, source);
343 return;
346 base::FilePath file_path(command_line.GetArgs()[0]);
347 scoped_refptr<PlatformAppPathLauncher> launcher =
348 new PlatformAppPathLauncher(profile, extension, file_path);
349 launcher->LaunchWithRelativePath(current_directory);
352 void LaunchPlatformAppWithPath(Profile* profile,
353 const Extension* extension,
354 const base::FilePath& file_path) {
355 scoped_refptr<PlatformAppPathLauncher> launcher =
356 new PlatformAppPathLauncher(profile, extension, file_path);
357 launcher->Launch();
360 void LaunchPlatformApp(Profile* profile,
361 const Extension* extension,
362 extensions::AppLaunchSource source) {
363 LaunchPlatformAppWithCommandLine(
364 profile,
365 extension,
366 base::CommandLine(base::CommandLine::NO_PROGRAM),
367 base::FilePath(),
368 source);
371 void LaunchPlatformAppWithFileHandler(
372 Profile* profile,
373 const Extension* extension,
374 const std::string& handler_id,
375 const std::vector<base::FilePath>& file_paths) {
376 scoped_refptr<PlatformAppPathLauncher> launcher =
377 new PlatformAppPathLauncher(profile, extension, file_paths);
378 launcher->LaunchWithHandler(handler_id);
381 void RestartPlatformApp(Profile* profile, const Extension* extension) {
382 EventRouter* event_router = EventRouter::Get(profile);
383 bool listening_to_restart = event_router->
384 ExtensionHasEventListener(extension->id(),
385 app_runtime::OnRestarted::kEventName);
387 if (listening_to_restart) {
388 AppRuntimeEventRouter::DispatchOnRestartedEvent(profile, extension);
389 return;
392 extensions::ExtensionPrefs* extension_prefs =
393 extensions::ExtensionPrefs::Get(profile);
394 bool had_windows = extension_prefs->IsActive(extension->id());
395 extension_prefs->SetIsActive(extension->id(), false);
396 bool listening_to_launch = event_router->
397 ExtensionHasEventListener(extension->id(),
398 app_runtime::OnLaunched::kEventName);
400 if (listening_to_launch && had_windows) {
401 AppRuntimeEventRouter::DispatchOnLaunchedEvent(
402 profile, extension, extensions::SOURCE_RESTART);
406 void LaunchPlatformAppWithUrl(Profile* profile,
407 const Extension* extension,
408 const std::string& handler_id,
409 const GURL& url,
410 const GURL& referrer_url) {
411 AppRuntimeEventRouter::DispatchOnLaunchedEventWithUrl(
412 profile, extension, handler_id, url, referrer_url);
415 } // namespace apps