Files.app: Override overflow specifying to use the original scroll bar.
[chromium-blink-merge.git] / apps / launcher.cc
blob0880c6d1923e07402275f2359d07efe45e1c69cf
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 "base/command_line.h"
8 #include "base/file_util.h"
9 #include "base/files/file_path.h"
10 #include "base/logging.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/extensions/api/file_handlers/app_file_handler_util.h"
15 #include "chrome/browser/extensions/api/file_handlers/mime_util.h"
16 #include "chrome/browser/extensions/api/file_system/file_system_api.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "content/public/browser/browser_thread.h"
19 #include "content/public/browser/render_process_host.h"
20 #include "content/public/browser/web_contents.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/url_constants.h"
23 #include "extensions/browser/api/app_runtime/app_runtime_api.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/granted_file_entry.h"
29 #include "extensions/browser/lazy_background_task_queue.h"
30 #include "extensions/browser/process_manager.h"
31 #include "extensions/common/api/app_runtime.h"
32 #include "extensions/common/extension.h"
33 #include "extensions/common/extension_messages.h"
34 #include "extensions/common/manifest_handlers/kiosk_mode_info.h"
35 #include "net/base/filename_util.h"
36 #include "net/base/net_util.h"
37 #include "url/gurl.h"
39 #if defined(OS_CHROMEOS)
40 #include "chrome/browser/chromeos/login/users/user_manager.h"
41 #endif
43 namespace app_runtime = extensions::core_api::app_runtime;
45 using content::BrowserThread;
46 using extensions::AppRuntimeEventRouter;
47 using extensions::app_file_handler_util::CreateFileEntry;
48 using extensions::app_file_handler_util::FileHandlerCanHandleFile;
49 using extensions::app_file_handler_util::FileHandlerForId;
50 using extensions::app_file_handler_util::FirstFileHandlerForFile;
51 using extensions::app_file_handler_util::HasFileSystemWritePermission;
52 using extensions::app_file_handler_util::PrepareFilesForWritableApp;
53 using extensions::EventRouter;
54 using extensions::Extension;
55 using extensions::ExtensionHost;
56 using extensions::ExtensionSystem;
57 using extensions::GrantedFileEntry;
59 namespace apps {
61 namespace {
63 const char kFallbackMimeType[] = "application/octet-stream";
65 bool DoMakePathAbsolute(const base::FilePath& current_directory,
66 base::FilePath* file_path) {
67 DCHECK(file_path);
68 if (file_path->IsAbsolute())
69 return true;
71 if (current_directory.empty()) {
72 *file_path = base::MakeAbsoluteFilePath(*file_path);
73 return !file_path->empty();
76 if (!current_directory.IsAbsolute())
77 return false;
79 *file_path = current_directory.Append(*file_path);
80 return true;
83 // Helper method to launch the platform app |extension| with no data. This
84 // should be called in the fallback case, where it has been impossible to
85 // load or obtain file launch data.
86 void LaunchPlatformAppWithNoData(Profile* profile, const Extension* extension) {
87 DCHECK_CURRENTLY_ON(BrowserThread::UI);
88 AppRuntimeEventRouter::DispatchOnLaunchedEvent(profile, extension);
91 // Class to handle launching of platform apps to open specific paths.
92 // An instance of this class is created for each launch. The lifetime of these
93 // instances is managed by reference counted pointers. As long as an instance
94 // has outstanding tasks on a message queue it will be retained; once all
95 // outstanding tasks are completed it will be deleted.
96 class PlatformAppPathLauncher
97 : public base::RefCountedThreadSafe<PlatformAppPathLauncher> {
98 public:
99 PlatformAppPathLauncher(Profile* profile,
100 const Extension* extension,
101 const std::vector<base::FilePath>& file_paths)
102 : profile_(profile),
103 extension_(extension),
104 file_paths_(file_paths),
105 collector_(profile) {}
107 PlatformAppPathLauncher(Profile* profile,
108 const Extension* extension,
109 const base::FilePath& file_path)
110 : profile_(profile), extension_(extension), collector_(profile) {
111 if (!file_path.empty())
112 file_paths_.push_back(file_path);
115 void Launch() {
116 DCHECK_CURRENTLY_ON(BrowserThread::UI);
117 if (file_paths_.empty()) {
118 LaunchPlatformAppWithNoData(profile_, extension_);
119 return;
122 for (size_t i = 0; i < file_paths_.size(); ++i) {
123 DCHECK(file_paths_[i].IsAbsolute());
126 if (HasFileSystemWritePermission(extension_)) {
127 PrepareFilesForWritableApp(
128 file_paths_,
129 profile_,
130 false,
131 base::Bind(&PlatformAppPathLauncher::OnFilesValid, this),
132 base::Bind(&PlatformAppPathLauncher::OnFilesInvalid, this));
133 return;
136 OnFilesValid();
139 void LaunchWithHandler(const std::string& handler_id) {
140 handler_id_ = handler_id;
141 Launch();
144 void LaunchWithRelativePath(const base::FilePath& current_directory) {
145 BrowserThread::PostTask(
146 BrowserThread::FILE,
147 FROM_HERE,
148 base::Bind(&PlatformAppPathLauncher::MakePathAbsolute,
149 this,
150 current_directory));
153 private:
154 friend class base::RefCountedThreadSafe<PlatformAppPathLauncher>;
156 virtual ~PlatformAppPathLauncher() {}
158 void MakePathAbsolute(const base::FilePath& current_directory) {
159 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
161 for (std::vector<base::FilePath>::iterator it = file_paths_.begin();
162 it != file_paths_.end();
163 ++it) {
164 if (!DoMakePathAbsolute(current_directory, &*it)) {
165 LOG(WARNING) << "Cannot make absolute path from " << it->value();
166 BrowserThread::PostTask(
167 BrowserThread::UI,
168 FROM_HERE,
169 base::Bind(&PlatformAppPathLauncher::LaunchWithNoLaunchData, this));
170 return;
174 BrowserThread::PostTask(BrowserThread::UI,
175 FROM_HERE,
176 base::Bind(&PlatformAppPathLauncher::Launch, this));
179 void OnFilesValid() {
180 collector_.CollectForLocalPaths(
181 file_paths_,
182 base::Bind(&PlatformAppPathLauncher::OnMimeTypesCollected, this));
185 void OnFilesInvalid(const base::FilePath& /* error_path */) {
186 LaunchWithNoLaunchData();
189 void LaunchWithNoLaunchData() {
190 // This method is required as an entry point on the UI thread.
191 LaunchPlatformAppWithNoData(profile_, extension_);
194 void OnMimeTypesCollected(scoped_ptr<std::vector<std::string> > mime_types) {
195 DCHECK(file_paths_.size() == mime_types->size());
197 // If fetching a mime type failed, then use a fallback one.
198 for (size_t i = 0; i < mime_types->size(); ++i) {
199 const std::string mime_type =
200 !(*mime_types)[i].empty() ? (*mime_types)[i] : kFallbackMimeType;
201 mime_types_.push_back(mime_type);
204 // Find file handler from the platform app for the file being opened.
205 const extensions::FileHandlerInfo* handler = NULL;
206 if (!handler_id_.empty()) {
207 handler = FileHandlerForId(*extension_, handler_id_);
208 if (handler) {
209 for (size_t i = 0; i < file_paths_.size(); ++i) {
210 if (!FileHandlerCanHandleFile(
211 *handler, mime_types_[i], file_paths_[i])) {
212 LOG(WARNING)
213 << "Extension does not provide a valid file handler for "
214 << file_paths_[i].value();
215 handler = NULL;
216 break;
220 } else {
221 std::set<std::pair<base::FilePath, std::string> > path_and_file_type_set;
222 for (size_t i = 0; i < file_paths_.size(); ++i) {
223 path_and_file_type_set.insert(
224 std::make_pair(file_paths_[i], mime_types_[i]));
226 const std::vector<const extensions::FileHandlerInfo*>& handlers =
227 extensions::app_file_handler_util::FindFileHandlersForFiles(
228 *extension_, path_and_file_type_set);
229 if (!handlers.empty())
230 handler = handlers[0];
233 // If this app doesn't have a file handler that supports the file, launch
234 // with no launch data.
235 if (!handler) {
236 LOG(WARNING) << "Extension does not provide a valid file handler.";
237 LaunchWithNoLaunchData();
238 return;
241 if (handler_id_.empty())
242 handler_id_ = handler->id;
244 // Access needs to be granted to the file for the process associated with
245 // the extension. To do this the ExtensionHost is needed. This might not be
246 // available, or it might be in the process of being unloaded, in which case
247 // the lazy background task queue is used to load the extension and then
248 // call back to us.
249 extensions::LazyBackgroundTaskQueue* const queue =
250 ExtensionSystem::Get(profile_)->lazy_background_task_queue();
251 if (queue->ShouldEnqueueTask(profile_, extension_)) {
252 queue->AddPendingTask(
253 profile_,
254 extension_->id(),
255 base::Bind(&PlatformAppPathLauncher::GrantAccessToFilesAndLaunch,
256 this));
257 return;
260 extensions::ProcessManager* const process_manager =
261 ExtensionSystem::Get(profile_)->process_manager();
262 ExtensionHost* const host =
263 process_manager->GetBackgroundHostForExtension(extension_->id());
264 DCHECK(host);
265 GrantAccessToFilesAndLaunch(host);
268 void GrantAccessToFilesAndLaunch(ExtensionHost* host) {
269 // If there was an error loading the app page, |host| will be NULL.
270 if (!host) {
271 LOG(ERROR) << "Could not load app page for " << extension_->id();
272 return;
275 std::vector<GrantedFileEntry> file_entries;
276 for (size_t i = 0; i < file_paths_.size(); ++i) {
277 file_entries.push_back(
278 CreateFileEntry(profile_,
279 extension_,
280 host->render_process_host()->GetID(),
281 file_paths_[i],
282 false));
285 AppRuntimeEventRouter::DispatchOnLaunchedEventWithFileEntries(
286 profile_, extension_, handler_id_, mime_types_, file_entries);
289 // The profile the app should be run in.
290 Profile* profile_;
291 // The extension providing the app.
292 // TODO(benwells): Hold onto the extension ID instead of a pointer as it
293 // is possible the extension will be unloaded while we're doing our thing.
294 // See http://crbug.com/372270 for details.
295 const Extension* extension_;
296 // The path to be passed through to the app.
297 std::vector<base::FilePath> file_paths_;
298 std::vector<std::string> mime_types_;
299 // The ID of the file handler used to launch the app.
300 std::string handler_id_;
301 extensions::app_file_handler_util::MimeTypeCollector collector_;
303 DISALLOW_COPY_AND_ASSIGN(PlatformAppPathLauncher);
306 } // namespace
308 void LaunchPlatformAppWithCommandLine(Profile* profile,
309 const Extension* extension,
310 const CommandLine& command_line,
311 const base::FilePath& current_directory) {
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 chromeos::UserManager* user_manager = chromeos::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::ASCIIToWide(url::kAboutBlankURL));
332 #else
333 base::CommandLine::StringType about_blank_url(url::kAboutBlankURL);
334 #endif
335 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 LaunchPlatformAppWithNoData(profile, extension);
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, const Extension* extension) {
361 LaunchPlatformAppWithCommandLine(profile,
362 extension,
363 CommandLine(CommandLine::NO_PROGRAM),
364 base::FilePath());
367 void LaunchPlatformAppWithFileHandler(
368 Profile* profile,
369 const Extension* extension,
370 const std::string& handler_id,
371 const std::vector<base::FilePath>& file_paths) {
372 scoped_refptr<PlatformAppPathLauncher> launcher =
373 new PlatformAppPathLauncher(profile, extension, file_paths);
374 launcher->LaunchWithHandler(handler_id);
377 void RestartPlatformApp(Profile* profile, const Extension* extension) {
378 EventRouter* event_router = EventRouter::Get(profile);
379 bool listening_to_restart = event_router->
380 ExtensionHasEventListener(extension->id(),
381 app_runtime::OnRestarted::kEventName);
383 if (listening_to_restart) {
384 AppRuntimeEventRouter::DispatchOnRestartedEvent(profile, extension);
385 return;
388 extensions::ExtensionPrefs* extension_prefs =
389 extensions::ExtensionPrefs::Get(profile);
390 bool had_windows = extension_prefs->IsActive(extension->id());
391 extension_prefs->SetIsActive(extension->id(), false);
392 bool listening_to_launch = event_router->
393 ExtensionHasEventListener(extension->id(),
394 app_runtime::OnLaunched::kEventName);
396 if (listening_to_launch && had_windows)
397 LaunchPlatformAppWithNoData(profile, extension);
400 void LaunchPlatformAppWithUrl(Profile* profile,
401 const Extension* extension,
402 const std::string& handler_id,
403 const GURL& url,
404 const GURL& referrer_url) {
405 AppRuntimeEventRouter::DispatchOnLaunchedEventWithUrl(
406 profile, extension, handler_id, url, referrer_url);
409 } // namespace apps