Change ImageLoadingHelper to be a RenderFrameObserver.
[chromium-blink-merge.git] / apps / launcher.cc
blob845b259a733a1f0dc9400903ad7cbf5759a2669b
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/apps_client.h"
8 #include "apps/browser/api/app_runtime/app_runtime_api.h"
9 #include "apps/browser/file_handler_util.h"
10 #include "apps/common/api/app_runtime.h"
11 #include "base/command_line.h"
12 #include "base/file_util.h"
13 #include "base/files/file_path.h"
14 #include "base/logging.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "chrome/browser/extensions/api/file_handlers/app_file_handler_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 "extensions/browser/event_router.h"
25 #include "extensions/browser/extension_host.h"
26 #include "extensions/browser/extension_prefs.h"
27 #include "extensions/browser/extension_system.h"
28 #include "extensions/browser/lazy_background_task_queue.h"
29 #include "extensions/browser/process_manager.h"
30 #include "extensions/common/extension.h"
31 #include "extensions/common/extension_messages.h"
32 #include "extensions/common/manifest_handlers/kiosk_mode_info.h"
33 #include "net/base/mime_util.h"
34 #include "net/base/net_util.h"
35 #include "url/gurl.h"
37 #if defined(OS_CHROMEOS)
38 #include "chrome/browser/chromeos/drive/file_errors.h"
39 #include "chrome/browser/chromeos/drive/file_system_interface.h"
40 #include "chrome/browser/chromeos/drive/file_system_util.h"
41 #include "chrome/browser/chromeos/login/user_manager.h"
42 #endif
44 #if defined(OS_WIN)
45 #include "win8/util/win8_util.h"
46 #endif
48 namespace app_runtime = apps::api::app_runtime;
50 using apps::file_handler_util::GrantedFileEntry;
51 using content::BrowserThread;
52 using extensions::app_file_handler_util::CheckWritableFiles;
53 using extensions::app_file_handler_util::FileHandlerForId;
54 using extensions::app_file_handler_util::FileHandlerCanHandleFile;
55 using extensions::app_file_handler_util::FirstFileHandlerForFile;
56 using extensions::app_file_handler_util::CreateFileEntry;
57 using extensions::app_file_handler_util::HasFileSystemWritePermission;
58 using extensions::EventRouter;
59 using extensions::Extension;
60 using extensions::ExtensionHost;
61 using extensions::ExtensionSystem;
63 namespace apps {
65 namespace {
67 const char kFallbackMimeType[] = "application/octet-stream";
69 bool MakePathAbsolute(const base::FilePath& current_directory,
70 base::FilePath* file_path) {
71 DCHECK(file_path);
72 if (file_path->IsAbsolute())
73 return true;
75 if (current_directory.empty()) {
76 *file_path = base::MakeAbsoluteFilePath(*file_path);
77 return !file_path->empty();
80 if (!current_directory.IsAbsolute())
81 return false;
83 *file_path = current_directory.Append(*file_path);
84 return true;
87 bool GetAbsolutePathFromCommandLine(const CommandLine& command_line,
88 const base::FilePath& current_directory,
89 base::FilePath* path) {
90 if (!command_line.GetArgs().size())
91 return false;
93 base::FilePath relative_path(command_line.GetArgs()[0]);
94 base::FilePath absolute_path(relative_path);
95 if (!MakePathAbsolute(current_directory, &absolute_path)) {
96 LOG(WARNING) << "Cannot make absolute path from " << relative_path.value();
97 return false;
99 *path = absolute_path;
100 return true;
103 // Helper method to launch the platform app |extension| with no data. This
104 // should be called in the fallback case, where it has been impossible to
105 // load or obtain file launch data.
106 void LaunchPlatformAppWithNoData(Profile* profile, const Extension* extension) {
107 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
108 AppEventRouter::DispatchOnLaunchedEvent(profile, extension);
111 // Class to handle launching of platform apps to open a specific path.
112 // An instance of this class is created for each launch. The lifetime of these
113 // instances is managed by reference counted pointers. As long as an instance
114 // has outstanding tasks on a message queue it will be retained; once all
115 // outstanding tasks are completed it will be deleted.
116 class PlatformAppPathLauncher
117 : public base::RefCountedThreadSafe<PlatformAppPathLauncher> {
118 public:
119 PlatformAppPathLauncher(Profile* profile,
120 const Extension* extension,
121 const base::FilePath& file_path)
122 : profile_(profile), extension_(extension), file_path_(file_path) {}
124 void Launch() {
125 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
126 if (file_path_.empty()) {
127 LaunchPlatformAppWithNoData(profile_, extension_);
128 return;
131 DCHECK(file_path_.IsAbsolute());
133 if (HasFileSystemWritePermission(extension_)) {
134 std::vector<base::FilePath> paths;
135 paths.push_back(file_path_);
136 CheckWritableFiles(
137 paths,
138 profile_,
139 false,
140 base::Bind(&PlatformAppPathLauncher::OnFileValid, this),
141 base::Bind(&PlatformAppPathLauncher::OnFileInvalid, this));
142 return;
145 OnFileValid();
148 void LaunchWithHandler(const std::string& handler_id) {
149 handler_id_ = handler_id;
150 Launch();
153 private:
154 friend class base::RefCountedThreadSafe<PlatformAppPathLauncher>;
156 virtual ~PlatformAppPathLauncher() {}
158 void OnFileValid() {
159 #if defined(OS_CHROMEOS)
160 if (drive::util::IsUnderDriveMountPoint(file_path_)) {
161 PlatformAppPathLauncher::GetMimeTypeAndLaunchForDriveFile();
162 return;
164 #endif
166 BrowserThread::PostTask(
167 BrowserThread::FILE,
168 FROM_HERE,
169 base::Bind(&PlatformAppPathLauncher::GetMimeTypeAndLaunch, this));
172 void OnFileInvalid(const base::FilePath& /* error_path */) {
173 LaunchWithNoLaunchData();
176 void GetMimeTypeAndLaunch() {
177 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
179 // If the file doesn't exist, or is a directory, launch with no launch data.
180 if (!base::PathExists(file_path_) ||
181 base::DirectoryExists(file_path_)) {
182 LOG(WARNING) << "No file exists with path " << file_path_.value();
183 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
184 &PlatformAppPathLauncher::LaunchWithNoLaunchData, this));
185 return;
188 std::string mime_type;
189 if (!net::GetMimeTypeFromFile(file_path_, &mime_type))
190 mime_type = kFallbackMimeType;
192 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
193 &PlatformAppPathLauncher::LaunchWithMimeType, this, mime_type));
196 #if defined(OS_CHROMEOS)
197 void GetMimeTypeAndLaunchForDriveFile() {
198 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
200 drive::FileSystemInterface* file_system =
201 drive::util::GetFileSystemByProfile(profile_);
202 if (!file_system) {
203 LaunchWithNoLaunchData();
204 return;
207 file_system->GetFile(
208 drive::util::ExtractDrivePath(file_path_),
209 base::Bind(&PlatformAppPathLauncher::OnGotDriveFile, this));
212 void OnGotDriveFile(drive::FileError error,
213 const base::FilePath& file_path,
214 scoped_ptr<drive::ResourceEntry> entry) {
215 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
217 if (error != drive::FILE_ERROR_OK ||
218 !entry || entry->file_specific_info().is_hosted_document()) {
219 LaunchWithNoLaunchData();
220 return;
223 const std::string& mime_type =
224 entry->file_specific_info().content_mime_type();
225 LaunchWithMimeType(mime_type.empty() ? kFallbackMimeType : mime_type);
227 #endif // defined(OS_CHROMEOS)
229 void LaunchWithNoLaunchData() {
230 // This method is required as an entry point on the UI thread.
231 LaunchPlatformAppWithNoData(profile_, extension_);
234 void LaunchWithMimeType(const std::string& mime_type) {
235 // Find file handler from the platform app for the file being opened.
236 const extensions::FileHandlerInfo* handler = NULL;
237 if (!handler_id_.empty())
238 handler = FileHandlerForId(*extension_, handler_id_);
239 else
240 handler = FirstFileHandlerForFile(*extension_, mime_type, file_path_);
241 if (handler && !FileHandlerCanHandleFile(*handler, mime_type, file_path_)) {
242 LOG(WARNING) << "Extension does not provide a valid file handler for "
243 << file_path_.value();
244 LaunchWithNoLaunchData();
245 return;
248 // If this app doesn't have a file handler that supports the file, launch
249 // with no launch data.
250 if (!handler) {
251 LOG(WARNING) << "Extension does not provide a valid file handler for "
252 << file_path_.value();
253 LaunchWithNoLaunchData();
254 return;
257 if (handler_id_.empty())
258 handler_id_ = handler->id;
260 // Access needs to be granted to the file for the process associated with
261 // the extension. To do this the ExtensionHost is needed. This might not be
262 // available, or it might be in the process of being unloaded, in which case
263 // the lazy background task queue is used to load the extension and then
264 // call back to us.
265 extensions::LazyBackgroundTaskQueue* queue =
266 ExtensionSystem::Get(profile_)->lazy_background_task_queue();
267 if (queue->ShouldEnqueueTask(profile_, extension_)) {
268 queue->AddPendingTask(profile_, extension_->id(), base::Bind(
269 &PlatformAppPathLauncher::GrantAccessToFileAndLaunch,
270 this, mime_type));
271 return;
274 extensions::ProcessManager* process_manager =
275 ExtensionSystem::Get(profile_)->process_manager();
276 ExtensionHost* host =
277 process_manager->GetBackgroundHostForExtension(extension_->id());
278 DCHECK(host);
279 GrantAccessToFileAndLaunch(mime_type, host);
282 void GrantAccessToFileAndLaunch(const std::string& mime_type,
283 ExtensionHost* host) {
284 // If there was an error loading the app page, |host| will be NULL.
285 if (!host) {
286 LOG(ERROR) << "Could not load app page for " << extension_->id();
287 return;
290 GrantedFileEntry file_entry =
291 CreateFileEntry(profile_,
292 extension_,
293 host->render_process_host()->GetID(),
294 file_path_,
295 false);
296 AppEventRouter::DispatchOnLaunchedEventWithFileEntry(
297 profile_, extension_, handler_id_, mime_type, file_entry);
300 // The profile the app should be run in.
301 Profile* profile_;
302 // The extension providing the app.
303 const Extension* extension_;
304 // The path to be passed through to the app.
305 const base::FilePath file_path_;
306 // The ID of the file handler used to launch the app.
307 std::string handler_id_;
309 DISALLOW_COPY_AND_ASSIGN(PlatformAppPathLauncher);
312 } // namespace
314 void LaunchPlatformAppWithCommandLine(Profile* profile,
315 const Extension* extension,
316 const CommandLine& command_line,
317 const base::FilePath& current_directory) {
318 if (!AppsClient::Get()->CheckAppLaunch(profile, extension))
319 return;
321 // An app with "kiosk_only" should not be installed and launched
322 // outside of ChromeOS kiosk mode in the first place. This is a defensive
323 // check in case this scenario does occur.
324 if (extensions::KioskModeInfo::IsKioskOnly(extension)) {
325 bool in_kiosk_mode = false;
326 #if defined(OS_CHROMEOS)
327 chromeos::UserManager* user_manager = chromeos::UserManager::Get();
328 in_kiosk_mode = user_manager && user_manager->IsLoggedInAsKioskApp();
329 #endif
330 if (!in_kiosk_mode) {
331 LOG(ERROR) << "App with 'kiosk_only' attribute must be run in "
332 << " ChromeOS kiosk mode.";
333 NOTREACHED();
334 return;
338 base::FilePath path;
339 if (!GetAbsolutePathFromCommandLine(command_line, current_directory, &path)) {
340 LaunchPlatformAppWithNoData(profile, extension);
341 return;
344 // TODO(benwells): add a command-line argument to provide a handler ID.
345 LaunchPlatformAppWithPath(profile, extension, path);
348 void LaunchPlatformAppWithPath(Profile* profile,
349 const Extension* extension,
350 const base::FilePath& file_path) {
351 // launcher will be freed when nothing has a reference to it. The message
352 // queue will retain a reference for any outstanding task, so when the
353 // launcher has finished it will be freed.
354 scoped_refptr<PlatformAppPathLauncher> launcher =
355 new PlatformAppPathLauncher(profile, extension, file_path);
356 launcher->Launch();
359 void LaunchPlatformApp(Profile* profile, const Extension* extension) {
360 LaunchPlatformAppWithCommandLine(profile,
361 extension,
362 CommandLine(CommandLine::NO_PROGRAM),
363 base::FilePath());
366 void LaunchPlatformAppWithFileHandler(Profile* profile,
367 const Extension* extension,
368 const std::string& handler_id,
369 const base::FilePath& file_path) {
370 scoped_refptr<PlatformAppPathLauncher> launcher =
371 new PlatformAppPathLauncher(profile, extension, file_path);
372 launcher->LaunchWithHandler(handler_id);
375 void RestartPlatformApp(Profile* profile, const Extension* extension) {
376 #if defined(OS_WIN)
377 // On Windows 8's single window Metro mode we can not launch platform apps.
378 // In restart we are just making sure launch doesn't slip through.
379 if (win8::IsSingleWindowMetroMode())
380 return;
381 #endif
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 AppEventRouter::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 LaunchPlatformAppWithNoData(profile, extension);
404 void LaunchPlatformAppWithUrl(Profile* profile,
405 const Extension* extension,
406 const std::string& handler_id,
407 const GURL& url,
408 const GURL& referrer_url) {
409 AppEventRouter::DispatchOnLaunchedEventWithUrl(
410 profile, extension, handler_id, url, referrer_url);
413 } // namespace apps