1 // Copyright (c) 2012 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 #import "chrome/browser/web_applications/web_app_mac.h"
7 #import <Carbon/Carbon.h>
8 #import <Cocoa/Cocoa.h>
10 #include "base/command_line.h"
11 #include "base/files/file_enumerator.h"
12 #include "base/files/file_util.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/mac/foundation_util.h"
15 #include "base/mac/launch_services_util.h"
16 #include "base/mac/mac_util.h"
17 #include "base/mac/scoped_cftyperef.h"
18 #include "base/mac/scoped_nsobject.h"
19 #include "base/metrics/sparse_histogram.h"
20 #include "base/path_service.h"
21 #include "base/process/process_handle.h"
22 #include "base/strings/string16.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_split.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/sys_string_conversions.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/version.h"
29 #include "chrome/browser/browser_process.h"
30 #import "chrome/browser/mac/dock.h"
31 #include "chrome/browser/profiles/profile.h"
32 #include "chrome/browser/profiles/profile_manager.h"
33 #include "chrome/browser/shell_integration.h"
34 #include "chrome/browser/ui/app_list/app_list_service.h"
35 #include "chrome/browser/ui/cocoa/key_equivalent_constants.h"
36 #include "chrome/common/chrome_constants.h"
37 #include "chrome/common/chrome_paths.h"
38 #include "chrome/common/chrome_switches.h"
39 #include "chrome/common/chrome_version_info.h"
40 #import "chrome/common/mac/app_mode_common.h"
41 #include "chrome/grit/generated_resources.h"
42 #include "components/crx_file/id_util.h"
43 #include "content/public/browser/browser_thread.h"
44 #include "extensions/browser/extension_registry.h"
45 #include "extensions/common/extension.h"
46 #include "grit/chrome_unscaled_resources.h"
47 #import "skia/ext/skia_utils_mac.h"
48 #include "third_party/skia/include/core/SkBitmap.h"
49 #include "third_party/skia/include/core/SkColor.h"
50 #include "ui/base/l10n/l10n_util.h"
51 #import "ui/base/l10n/l10n_util_mac.h"
52 #include "ui/base/resource/resource_bundle.h"
53 #include "ui/gfx/image/image_family.h"
55 bool g_app_shims_allow_update_and_launch_in_tests = false;
59 // Launch Services Key to run as an agent app, which doesn't launch in the dock.
60 NSString* const kLSUIElement = @"LSUIElement";
62 class ScopedCarbonHandle {
64 ScopedCarbonHandle(size_t initial_size) : handle_(NewHandle(initial_size)) {
66 DCHECK_EQ(noErr, MemError());
68 ~ScopedCarbonHandle() { DisposeHandle(handle_); }
70 Handle Get() { return handle_; }
71 char* Data() { return *handle_; }
72 size_t HandleSize() const { return GetHandleSize(handle_); }
74 IconFamilyHandle GetAsIconFamilyHandle() {
75 return reinterpret_cast<IconFamilyHandle>(handle_);
78 bool WriteDataToFile(const base::FilePath& path) {
79 NSData* data = [NSData dataWithBytes:Data()
81 return [data writeToFile:base::mac::FilePathToNSString(path)
89 void ConvertSkiaToARGB(const SkBitmap& bitmap, ScopedCarbonHandle* handle) {
90 CHECK_EQ(4u * bitmap.width() * bitmap.height(), handle->HandleSize());
92 char* argb = handle->Data();
93 SkAutoLockPixels lock(bitmap);
94 for (int y = 0; y < bitmap.height(); ++y) {
95 for (int x = 0; x < bitmap.width(); ++x) {
96 SkColor pixel = bitmap.getColor(x, y);
97 argb[0] = SkColorGetA(pixel);
98 argb[1] = SkColorGetR(pixel);
99 argb[2] = SkColorGetG(pixel);
100 argb[3] = SkColorGetB(pixel);
106 // Adds |image| to |icon_family|. Returns true on success, false on failure.
107 bool AddGfxImageToIconFamily(IconFamilyHandle icon_family,
108 const gfx::Image& image) {
109 // When called via ShowCreateChromeAppShortcutsDialog the ImageFamily will
110 // have all the representations desired here for mac, from the kDesiredSizes
111 // array in web_app.cc.
112 SkBitmap bitmap = image.AsBitmap();
113 if (bitmap.colorType() != kN32_SkColorType ||
114 bitmap.width() != bitmap.height()) {
119 switch (bitmap.width()) {
121 icon_type = kIconServices512PixelDataARGB;
124 icon_type = kIconServices256PixelDataARGB;
127 icon_type = kIconServices128PixelDataARGB;
130 icon_type = kIconServices48PixelDataARGB;
133 icon_type = kIconServices32PixelDataARGB;
136 icon_type = kIconServices16PixelDataARGB;
142 ScopedCarbonHandle raw_data(bitmap.getSize());
143 ConvertSkiaToARGB(bitmap, &raw_data);
144 OSErr result = SetIconFamilyData(icon_family, icon_type, raw_data.Get());
145 DCHECK_EQ(noErr, result);
146 return result == noErr;
149 bool AppShimsDisabledForTest() {
150 // Disable app shims in tests because shims created in ~/Applications will not
152 return base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType);
155 base::FilePath GetWritableApplicationsDirectory() {
157 if (base::mac::GetUserDirectory(NSApplicationDirectory, &path)) {
158 if (!base::DirectoryExists(path)) {
159 if (!base::CreateDirectory(path))
160 return base::FilePath();
162 // Create a zero-byte ".localized" file to inherit localizations from OSX
163 // for folders that have special meaning.
164 base::WriteFile(path.Append(".localized"), NULL, 0);
166 return base::PathIsWritable(path) ? path : base::FilePath();
168 return base::FilePath();
171 // Given the path to an app bundle, return the resources directory.
172 base::FilePath GetResourcesPath(const base::FilePath& app_path) {
173 return app_path.Append("Contents").Append("Resources");
176 bool HasExistingExtensionShim(const base::FilePath& destination_directory,
177 const std::string& extension_id,
178 const base::FilePath& own_basename) {
179 // Check if there any any other shims for the same extension.
180 base::FileEnumerator enumerator(destination_directory,
181 false /* recursive */,
182 base::FileEnumerator::DIRECTORIES);
183 for (base::FilePath shim_path = enumerator.Next();
184 !shim_path.empty(); shim_path = enumerator.Next()) {
185 if (shim_path.BaseName() != own_basename &&
186 EndsWith(shim_path.RemoveExtension().value(),
188 true /* case_sensitive */)) {
196 // Given the path to an app bundle, return the path to the Info.plist file.
197 NSString* GetPlistPath(const base::FilePath& bundle_path) {
198 return base::mac::FilePathToNSString(
199 bundle_path.Append("Contents").Append("Info.plist"));
202 NSMutableDictionary* ReadPlist(NSString* plist_path) {
203 return [NSMutableDictionary dictionaryWithContentsOfFile:plist_path];
206 // Takes the path to an app bundle and checks that the CrAppModeUserDataDir in
207 // the Info.plist starts with the current user_data_dir. This uses starts with
208 // instead of equals because the CrAppModeUserDataDir could be the user_data_dir
209 // or the |app_data_dir_|.
210 bool HasSameUserDataDir(const base::FilePath& bundle_path) {
211 NSDictionary* plist = ReadPlist(GetPlistPath(bundle_path));
212 base::FilePath user_data_dir;
213 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
214 DCHECK(!user_data_dir.empty());
215 return StartsWithASCII(
216 base::SysNSStringToUTF8(
217 [plist valueForKey:app_mode::kCrAppModeUserDataDirKey]),
218 user_data_dir.value(),
219 true /* case_sensitive */);
222 void LaunchShimOnFileThread(const web_app::ShortcutInfo& shortcut_info,
223 bool launched_after_rebuild) {
224 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
225 base::FilePath shim_path = web_app::GetAppInstallPath(shortcut_info);
227 if (shim_path.empty() ||
228 !base::PathExists(shim_path) ||
229 !HasSameUserDataDir(shim_path)) {
230 // The user may have deleted the copy in the Applications folder, use the
231 // one in the web app's |app_data_dir_|.
232 base::FilePath app_data_dir = web_app::GetWebAppDataDirectory(
233 shortcut_info.profile_path, shortcut_info.extension_id, GURL());
234 shim_path = app_data_dir.Append(shim_path.BaseName());
237 if (!base::PathExists(shim_path))
240 base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
241 command_line.AppendSwitchASCII(
242 app_mode::kLaunchedByChromeProcessId,
243 base::IntToString(base::GetCurrentProcId()));
244 if (launched_after_rebuild)
245 command_line.AppendSwitch(app_mode::kLaunchedAfterRebuild);
246 // Launch without activating (kLSLaunchDontSwitch).
247 base::mac::OpenApplicationWithPath(
248 shim_path, command_line, kLSLaunchDefaults | kLSLaunchDontSwitch, NULL);
251 base::FilePath GetAppLoaderPath() {
252 return base::mac::PathForFrameworkBundleResource(
253 base::mac::NSToCFCast(@"app_mode_loader.app"));
256 void UpdateAndLaunchShimOnFileThread(
257 const web_app::ShortcutInfo& shortcut_info,
258 const extensions::FileHandlersInfo& file_handlers_info) {
259 base::FilePath shortcut_data_dir = web_app::GetWebAppDataDirectory(
260 shortcut_info.profile_path, shortcut_info.extension_id, GURL());
261 web_app::internals::UpdatePlatformShortcuts(
262 shortcut_data_dir, base::string16(), shortcut_info, file_handlers_info);
263 LaunchShimOnFileThread(shortcut_info, true);
266 void UpdateAndLaunchShim(
267 const web_app::ShortcutInfo& shortcut_info,
268 const extensions::FileHandlersInfo& file_handlers_info) {
269 content::BrowserThread::PostTask(
270 content::BrowserThread::FILE,
273 &UpdateAndLaunchShimOnFileThread, shortcut_info, file_handlers_info));
276 void RebuildAppAndLaunch(const web_app::ShortcutInfo& shortcut_info) {
277 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
278 if (shortcut_info.extension_id == app_mode::kAppListModeId) {
279 AppListService* app_list_service =
280 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE);
281 app_list_service->CreateShortcut();
282 app_list_service->Show();
286 ProfileManager* profile_manager = g_browser_process->profile_manager();
288 profile_manager->GetProfileByPath(shortcut_info.profile_path);
289 if (!profile || !profile_manager->IsValidProfile(profile))
292 extensions::ExtensionRegistry* registry =
293 extensions::ExtensionRegistry::Get(profile);
294 const extensions::Extension* extension = registry->GetExtensionById(
295 shortcut_info.extension_id, extensions::ExtensionRegistry::ENABLED);
296 if (!extension || !extension->is_platform_app())
299 web_app::GetInfoForApp(extension, profile, base::Bind(&UpdateAndLaunchShim));
302 base::FilePath GetLocalizableAppShortcutsSubdirName() {
303 static const char kChromiumAppDirName[] = "Chromium Apps.localized";
304 static const char kChromeAppDirName[] = "Chrome Apps.localized";
305 static const char kChromeCanaryAppDirName[] = "Chrome Canary Apps.localized";
307 switch (chrome::VersionInfo::GetChannel()) {
308 case chrome::VersionInfo::CHANNEL_UNKNOWN:
309 return base::FilePath(kChromiumAppDirName);
311 case chrome::VersionInfo::CHANNEL_CANARY:
312 return base::FilePath(kChromeCanaryAppDirName);
315 return base::FilePath(kChromeAppDirName);
319 // Creates a canvas the same size as |overlay|, copies the appropriate
320 // representation from |backgound| into it (according to Cocoa), then draws
321 // |overlay| over it using NSCompositeSourceOver.
322 NSImageRep* OverlayImageRep(NSImage* background, NSImageRep* overlay) {
324 NSInteger dimension = [overlay pixelsWide];
325 DCHECK_EQ(dimension, [overlay pixelsHigh]);
326 base::scoped_nsobject<NSBitmapImageRep> canvas([[NSBitmapImageRep alloc]
327 initWithBitmapDataPlanes:NULL
334 colorSpaceName:NSCalibratedRGBColorSpace
338 // There isn't a colorspace name constant for sRGB, so retag.
339 NSBitmapImageRep* srgb_canvas = [canvas
340 bitmapImageRepByRetaggingWithColorSpace:[NSColorSpace sRGBColorSpace]];
341 canvas.reset([srgb_canvas retain]);
343 // Communicate the DIP scale (1.0). TODO(tapted): Investigate HiDPI.
344 [canvas setSize:NSMakeSize(dimension, dimension)];
346 NSGraphicsContext* drawing_context =
347 [NSGraphicsContext graphicsContextWithBitmapImageRep:canvas];
348 [NSGraphicsContext saveGraphicsState];
349 [NSGraphicsContext setCurrentContext:drawing_context];
350 [background drawInRect:NSMakeRect(0, 0, dimension, dimension)
352 operation:NSCompositeCopy
354 [overlay drawInRect:NSMakeRect(0, 0, dimension, dimension)
356 operation:NSCompositeSourceOver
360 [NSGraphicsContext restoreGraphicsState];
361 return canvas.autorelease();
364 // Helper function to extract the single NSImageRep held in a resource bundle
366 NSImageRep* ImageRepForResource(int resource_id) {
368 ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
369 NSArray* image_reps = [image.AsNSImage() representations];
370 DCHECK_EQ(1u, [image_reps count]);
371 return [image_reps objectAtIndex:0];
374 // Adds a localized strings file for the Chrome Apps directory using the current
375 // locale. OSX will use this for the display name.
376 // + Chrome Apps.localized (|apps_directory|)
380 void UpdateAppShortcutsSubdirLocalizedName(
381 const base::FilePath& apps_directory) {
382 base::FilePath localized = apps_directory.Append(".localized");
383 if (!base::CreateDirectory(localized))
386 base::FilePath directory_name = apps_directory.BaseName().RemoveExtension();
387 base::string16 localized_name = ShellIntegration::GetAppShortcutsSubdirName();
388 NSDictionary* strings_dict = @{
389 base::mac::FilePathToNSString(directory_name) :
390 base::SysUTF16ToNSString(localized_name)
393 std::string locale = l10n_util::NormalizeLocale(
394 l10n_util::GetApplicationLocale(std::string()));
396 NSString* strings_path = base::mac::FilePathToNSString(
397 localized.Append(locale + ".strings"));
398 [strings_dict writeToFile:strings_path
401 base::scoped_nsobject<NSImage> folder_icon_image([[NSImage alloc] init]);
403 // Use complete assets for the small icon sizes. -[NSWorkspace setIcon:] has a
404 // bug when dealing with named NSImages where it incorrectly handles alpha
405 // premultiplication. This is most noticable with small assets since the 1px
406 // border is a much larger component of the small icons.
407 // See http://crbug.com/305373 for details.
408 [folder_icon_image addRepresentation:ImageRepForResource(IDR_APPS_FOLDER_16)];
409 [folder_icon_image addRepresentation:ImageRepForResource(IDR_APPS_FOLDER_32)];
411 // Brand larger folder assets with an embossed app launcher logo to conserve
412 // distro size and for better consistency with changing hue across OSX
413 // versions. The folder is textured, so compresses poorly without this.
414 const int kBrandResourceIds[] = {
415 IDR_APPS_FOLDER_OVERLAY_128,
416 IDR_APPS_FOLDER_OVERLAY_512,
418 NSImage* base_image = [NSImage imageNamed:NSImageNameFolder];
419 for (size_t i = 0; i < arraysize(kBrandResourceIds); ++i) {
420 NSImageRep* with_overlay =
421 OverlayImageRep(base_image, ImageRepForResource(kBrandResourceIds[i]));
422 DCHECK(with_overlay);
424 [folder_icon_image addRepresentation:with_overlay];
426 [[NSWorkspace sharedWorkspace]
427 setIcon:folder_icon_image
428 forFile:base::mac::FilePathToNSString(apps_directory)
432 void DeletePathAndParentIfEmpty(const base::FilePath& app_path) {
433 DCHECK(!app_path.empty());
434 base::DeleteFile(app_path, true);
435 base::FilePath apps_folder = app_path.DirName();
436 if (base::IsDirectoryEmpty(apps_folder))
437 base::DeleteFile(apps_folder, false);
440 bool IsShimForProfile(const base::FilePath& base_name,
441 const std::string& profile_base_name) {
442 if (!StartsWithASCII(base_name.value(), profile_base_name, true))
445 if (base_name.Extension() != ".app")
448 std::string app_id = base_name.RemoveExtension().value();
449 // Strip (profile_base_name + " ") from the start.
450 app_id = app_id.substr(profile_base_name.size() + 1);
451 return crx_file::id_util::IdIsValid(app_id);
454 std::vector<base::FilePath> GetAllAppBundlesInPath(
455 const base::FilePath& internal_shortcut_path,
456 const std::string& profile_base_name) {
457 std::vector<base::FilePath> bundle_paths;
459 base::FileEnumerator enumerator(internal_shortcut_path,
460 true /* recursive */,
461 base::FileEnumerator::DIRECTORIES);
462 for (base::FilePath bundle_path = enumerator.Next();
463 !bundle_path.empty(); bundle_path = enumerator.Next()) {
464 if (IsShimForProfile(bundle_path.BaseName(), profile_base_name))
465 bundle_paths.push_back(bundle_path);
471 web_app::ShortcutInfo BuildShortcutInfoFromBundle(
472 const base::FilePath& bundle_path) {
473 NSDictionary* plist = ReadPlist(GetPlistPath(bundle_path));
475 web_app::ShortcutInfo shortcut_info;
476 shortcut_info.extension_id = base::SysNSStringToUTF8(
477 [plist valueForKey:app_mode::kCrAppModeShortcutIDKey]);
478 shortcut_info.is_platform_app = true;
479 shortcut_info.url = GURL(base::SysNSStringToUTF8(
480 [plist valueForKey:app_mode::kCrAppModeShortcutURLKey]));
481 shortcut_info.title = base::SysNSStringToUTF16(
482 [plist valueForKey:app_mode::kCrAppModeShortcutNameKey]);
483 shortcut_info.profile_name = base::SysNSStringToUTF8(
484 [plist valueForKey:app_mode::kCrAppModeProfileNameKey]);
486 // Figure out the profile_path. Since the user_data_dir could contain the
487 // path to the web app data dir.
488 base::FilePath user_data_dir = base::mac::NSStringToFilePath(
489 [plist valueForKey:app_mode::kCrAppModeUserDataDirKey]);
490 base::FilePath profile_base_name = base::mac::NSStringToFilePath(
491 [plist valueForKey:app_mode::kCrAppModeProfileDirKey]);
492 if (user_data_dir.DirName().DirName().BaseName() == profile_base_name)
493 shortcut_info.profile_path = user_data_dir.DirName().DirName();
495 shortcut_info.profile_path = user_data_dir.Append(profile_base_name);
497 return shortcut_info;
500 web_app::ShortcutInfo RecordAppShimErrorAndBuildShortcutInfo(
501 const base::FilePath& bundle_path) {
502 NSDictionary* plist = ReadPlist(GetPlistPath(bundle_path));
503 NSString* version_string = [plist valueForKey:app_mode::kCrBundleVersionKey];
504 if (!version_string) {
505 // Older bundles have the Chrome version in the following key.
507 [plist valueForKey:app_mode::kCFBundleShortVersionStringKey];
509 base::Version full_version(base::SysNSStringToUTF8(version_string));
510 uint32_t major_version = 0;
511 if (full_version.IsValid())
512 major_version = full_version.components()[0];
513 UMA_HISTOGRAM_SPARSE_SLOWLY("Apps.AppShimErrorVersion", major_version);
515 return BuildShortcutInfoFromBundle(bundle_path);
518 void UpdateFileTypes(NSMutableDictionary* plist,
519 const extensions::FileHandlersInfo& file_handlers_info) {
520 NSMutableArray* document_types =
521 [NSMutableArray arrayWithCapacity:file_handlers_info.size()];
523 for (extensions::FileHandlersInfo::const_iterator info_it =
524 file_handlers_info.begin();
525 info_it != file_handlers_info.end();
527 const extensions::FileHandlerInfo& info = *info_it;
529 NSMutableArray* file_extensions =
530 [NSMutableArray arrayWithCapacity:info.extensions.size()];
531 for (std::set<std::string>::iterator it = info.extensions.begin();
532 it != info.extensions.end();
534 [file_extensions addObject:base::SysUTF8ToNSString(*it)];
537 NSMutableArray* mime_types =
538 [NSMutableArray arrayWithCapacity:info.types.size()];
539 for (std::set<std::string>::iterator it = info.types.begin();
540 it != info.types.end();
542 [mime_types addObject:base::SysUTF8ToNSString(*it)];
545 NSDictionary* type_dictionary = @{
546 // TODO(jackhou): Add the type name and and icon file once the manifest
548 // app_mode::kCFBundleTypeNameKey : ,
549 // app_mode::kCFBundleTypeIconFileKey : ,
550 app_mode::kCFBundleTypeExtensionsKey : file_extensions,
551 app_mode::kCFBundleTypeMIMETypesKey : mime_types,
552 app_mode::kCFBundleTypeRoleKey : app_mode::kBundleTypeRoleViewer
554 [document_types addObject:type_dictionary];
557 [plist setObject:document_types
558 forKey:app_mode::kCFBundleDocumentTypesKey];
561 void RevealAppShimInFinderForAppOnFileThread(
562 const web_app::ShortcutInfo& shortcut_info,
563 const base::FilePath& app_path) {
564 web_app::WebAppShortcutCreator shortcut_creator(
565 app_path, shortcut_info, extensions::FileHandlersInfo());
566 shortcut_creator.RevealAppShimInFinder();
571 @interface CrCreateAppShortcutCheckboxObserver : NSObject {
574 NSButton* continueButton_;
577 - (id)initWithCheckbox:(NSButton*)checkbox
578 continueButton:(NSButton*)continueButton;
579 - (void)startObserving;
580 - (void)stopObserving;
583 @implementation CrCreateAppShortcutCheckboxObserver
585 - (id)initWithCheckbox:(NSButton*)checkbox
586 continueButton:(NSButton*)continueButton {
587 if ((self = [super init])) {
588 checkbox_ = checkbox;
589 continueButton_ = continueButton;
594 - (void)startObserving {
595 [checkbox_ addObserver:self
596 forKeyPath:@"cell.state"
601 - (void)stopObserving {
602 [checkbox_ removeObserver:self
603 forKeyPath:@"cell.state"];
606 - (void)observeValueForKeyPath:(NSString*)keyPath
608 change:(NSDictionary*)change
609 context:(void*)context {
610 [continueButton_ setEnabled:([checkbox_ state] == NSOnState)];
617 WebAppShortcutCreator::WebAppShortcutCreator(
618 const base::FilePath& app_data_dir,
619 const ShortcutInfo& shortcut_info,
620 const extensions::FileHandlersInfo& file_handlers_info)
621 : app_data_dir_(app_data_dir),
622 info_(shortcut_info),
623 file_handlers_info_(file_handlers_info) {}
625 WebAppShortcutCreator::~WebAppShortcutCreator() {}
627 base::FilePath WebAppShortcutCreator::GetApplicationsShortcutPath() const {
628 base::FilePath applications_dir = GetApplicationsDirname();
629 return applications_dir.empty() ?
630 base::FilePath() : applications_dir.Append(GetShortcutBasename());
633 base::FilePath WebAppShortcutCreator::GetInternalShortcutPath() const {
634 return app_data_dir_.Append(GetShortcutBasename());
637 base::FilePath WebAppShortcutCreator::GetShortcutBasename() const {
638 std::string app_name;
639 // Check if there should be a separate shortcut made for different profiles.
640 // Such shortcuts will have a |profile_name| set on the ShortcutInfo,
641 // otherwise it will be empty.
642 if (!info_.profile_name.empty()) {
643 app_name += info_.profile_path.BaseName().value();
646 app_name += info_.extension_id;
647 return base::FilePath(app_name).ReplaceExtension("app");
650 bool WebAppShortcutCreator::BuildShortcut(
651 const base::FilePath& staging_path) const {
652 // Update the app's plist and icon in a temp directory. This works around
653 // a Finder bug where the app's icon doesn't properly update.
654 if (!base::CopyDirectory(GetAppLoaderPath(), staging_path, true)) {
655 LOG(ERROR) << "Copying app to staging path: " << staging_path.value()
660 return UpdatePlist(staging_path) &&
661 UpdateDisplayName(staging_path) &&
662 UpdateIcon(staging_path);
665 size_t WebAppShortcutCreator::CreateShortcutsIn(
666 const std::vector<base::FilePath>& folders) const {
667 size_t succeeded = 0;
669 base::ScopedTempDir scoped_temp_dir;
670 if (!scoped_temp_dir.CreateUniqueTempDir())
673 base::FilePath app_name = GetShortcutBasename();
674 base::FilePath staging_path = scoped_temp_dir.path().Append(app_name);
675 if (!BuildShortcut(staging_path))
678 for (std::vector<base::FilePath>::const_iterator it = folders.begin();
679 it != folders.end(); ++it) {
680 const base::FilePath& dst_path = *it;
681 if (!base::CreateDirectory(dst_path)) {
682 LOG(ERROR) << "Creating directory " << dst_path.value() << " failed.";
686 if (!base::CopyDirectory(staging_path, dst_path, true)) {
687 LOG(ERROR) << "Copying app to dst path: " << dst_path.value()
692 // Remove the quarantine attribute from both the bundle and the executable.
693 base::mac::RemoveQuarantineAttribute(dst_path.Append(app_name));
694 base::mac::RemoveQuarantineAttribute(
695 dst_path.Append(app_name)
696 .Append("Contents").Append("MacOS").Append("app_mode_loader"));
703 bool WebAppShortcutCreator::CreateShortcuts(
704 ShortcutCreationReason creation_reason,
705 ShortcutLocations creation_locations) {
706 const base::FilePath applications_dir = GetApplicationsDirname();
707 if (applications_dir.empty() ||
708 !base::DirectoryExists(applications_dir.DirName())) {
709 LOG(ERROR) << "Couldn't find an Applications directory to copy app to.";
713 UpdateAppShortcutsSubdirLocalizedName(applications_dir);
715 // If non-nil, this path is added to the OSX Dock after creating shortcuts.
716 NSString* path_to_add_to_dock = nil;
718 std::vector<base::FilePath> paths;
720 // The app list shim is not tied to a particular profile, so omit the copy
721 // placed under the profile path. For shims, this copy is used when the
722 // version under Applications is removed, and not needed for app list because
723 // setting LSUIElement means there is no Dock "running" status to show.
724 const bool is_app_list = info_.extension_id == app_mode::kAppListModeId;
726 path_to_add_to_dock = base::SysUTF8ToNSString(
727 applications_dir.Append(GetShortcutBasename()).AsUTF8Unsafe());
729 paths.push_back(app_data_dir_);
732 bool shortcut_visible =
733 creation_locations.applications_menu_location != APP_MENU_LOCATION_HIDDEN;
734 if (shortcut_visible)
735 paths.push_back(applications_dir);
737 DCHECK(!paths.empty());
738 size_t success_count = CreateShortcutsIn(paths);
739 if (success_count == 0)
743 UpdateInternalBundleIdentifier();
745 if (success_count != paths.size())
748 if (creation_locations.in_quick_launch_bar && path_to_add_to_dock &&
750 switch (dock::AddIcon(path_to_add_to_dock, nil)) {
751 case dock::IconAddFailure:
752 // If adding the icon failed, instead reveal the Finder window.
753 RevealAppShimInFinder();
755 case dock::IconAddSuccess:
756 case dock::IconAlreadyPresent:
762 if (creation_reason == SHORTCUT_CREATION_BY_USER)
763 RevealAppShimInFinder();
768 void WebAppShortcutCreator::DeleteShortcuts() {
769 base::FilePath app_path = GetApplicationsShortcutPath();
770 if (!app_path.empty() && HasSameUserDataDir(app_path))
771 DeletePathAndParentIfEmpty(app_path);
773 // In case the user has moved/renamed/copied the app bundle.
774 base::FilePath bundle_path = GetAppBundleById(GetBundleIdentifier());
775 if (!bundle_path.empty() && HasSameUserDataDir(bundle_path))
776 base::DeleteFile(bundle_path, true);
778 // Delete the internal one.
779 DeletePathAndParentIfEmpty(GetInternalShortcutPath());
782 bool WebAppShortcutCreator::UpdateShortcuts() {
783 std::vector<base::FilePath> paths;
784 base::DeleteFile(GetInternalShortcutPath(), true);
785 paths.push_back(app_data_dir_);
787 // Try to update the copy under /Applications. If that does not exist, check
788 // if a matching bundle can be found elsewhere.
789 base::FilePath app_path = GetApplicationsShortcutPath();
790 if (app_path.empty() || !base::PathExists(app_path))
791 app_path = GetAppBundleById(GetBundleIdentifier());
793 if (!app_path.empty()) {
794 base::DeleteFile(app_path, true);
795 paths.push_back(app_path.DirName());
798 size_t success_count = CreateShortcutsIn(paths);
799 if (success_count == 0)
802 UpdateInternalBundleIdentifier();
803 return success_count == paths.size() && !app_path.empty();
806 base::FilePath WebAppShortcutCreator::GetApplicationsDirname() const {
807 base::FilePath path = GetWritableApplicationsDirectory();
811 return path.Append(GetLocalizableAppShortcutsSubdirName());
814 bool WebAppShortcutCreator::UpdatePlist(const base::FilePath& app_path) const {
815 NSString* extension_id = base::SysUTF8ToNSString(info_.extension_id);
816 NSString* extension_title = base::SysUTF16ToNSString(info_.title);
817 NSString* extension_url = base::SysUTF8ToNSString(info_.url.spec());
818 NSString* chrome_bundle_id =
819 base::SysUTF8ToNSString(base::mac::BaseBundleID());
820 NSDictionary* replacement_dict =
821 [NSDictionary dictionaryWithObjectsAndKeys:
822 extension_id, app_mode::kShortcutIdPlaceholder,
823 extension_title, app_mode::kShortcutNamePlaceholder,
824 extension_url, app_mode::kShortcutURLPlaceholder,
825 chrome_bundle_id, app_mode::kShortcutBrowserBundleIDPlaceholder,
828 NSString* plist_path = GetPlistPath(app_path);
829 NSMutableDictionary* plist = ReadPlist(plist_path);
830 NSArray* keys = [plist allKeys];
832 // 1. Fill in variables.
833 for (id key in keys) {
834 NSString* value = [plist valueForKey:key];
835 if (![value isKindOfClass:[NSString class]] || [value length] < 2)
838 // Remove leading and trailing '@'s.
840 [value substringWithRange:NSMakeRange(1, [value length] - 2)];
842 NSString* substitution = [replacement_dict valueForKey:variable];
844 [plist setObject:substitution forKey:key];
847 // 2. Fill in other values.
848 [plist setObject:base::SysUTF8ToNSString(chrome::VersionInfo().Version())
849 forKey:app_mode::kCrBundleVersionKey];
850 [plist setObject:base::SysUTF8ToNSString(info_.version_for_display)
851 forKey:app_mode::kCFBundleShortVersionStringKey];
852 [plist setObject:base::SysUTF8ToNSString(GetBundleIdentifier())
853 forKey:base::mac::CFToNSCast(kCFBundleIdentifierKey)];
854 [plist setObject:base::mac::FilePathToNSString(app_data_dir_)
855 forKey:app_mode::kCrAppModeUserDataDirKey];
856 [plist setObject:base::mac::FilePathToNSString(info_.profile_path.BaseName())
857 forKey:app_mode::kCrAppModeProfileDirKey];
858 [plist setObject:base::SysUTF8ToNSString(info_.profile_name)
859 forKey:app_mode::kCrAppModeProfileNameKey];
860 [plist setObject:[NSNumber numberWithBool:YES]
861 forKey:app_mode::kLSHasLocalizedDisplayNameKey];
862 if (info_.extension_id == app_mode::kAppListModeId) {
863 // Prevent the app list from bouncing in the dock, and getting a run light.
864 [plist setObject:[NSNumber numberWithBool:YES]
865 forKey:kLSUIElement];
868 base::FilePath app_name = app_path.BaseName().RemoveExtension();
869 [plist setObject:base::mac::FilePathToNSString(app_name)
870 forKey:base::mac::CFToNSCast(kCFBundleNameKey)];
872 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
873 switches::kEnableAppsFileAssociations)) {
874 UpdateFileTypes(plist, file_handlers_info_);
877 return [plist writeToFile:plist_path
881 bool WebAppShortcutCreator::UpdateDisplayName(
882 const base::FilePath& app_path) const {
883 // OSX searches for the best language in the order of preferred languages.
884 // Since we only have one localization directory, it will choose this one.
885 base::FilePath localized_dir = GetResourcesPath(app_path).Append("en.lproj");
886 if (!base::CreateDirectory(localized_dir))
889 NSString* bundle_name = base::SysUTF16ToNSString(info_.title);
890 NSString* display_name = base::SysUTF16ToNSString(info_.title);
891 if (HasExistingExtensionShim(GetApplicationsDirname(),
893 app_path.BaseName())) {
894 display_name = [bundle_name
895 stringByAppendingString:base::SysUTF8ToNSString(
896 " (" + info_.profile_name + ")")];
899 NSDictionary* strings_plist = @{
900 base::mac::CFToNSCast(kCFBundleNameKey) : bundle_name,
901 app_mode::kCFBundleDisplayNameKey : display_name
904 NSString* localized_path = base::mac::FilePathToNSString(
905 localized_dir.Append("InfoPlist.strings"));
906 return [strings_plist writeToFile:localized_path
910 bool WebAppShortcutCreator::UpdateIcon(const base::FilePath& app_path) const {
911 if (info_.favicon.empty())
914 ScopedCarbonHandle icon_family(0);
915 bool image_added = false;
916 for (gfx::ImageFamily::const_iterator it = info_.favicon.begin();
917 it != info_.favicon.end(); ++it) {
921 // Missing an icon size is not fatal so don't fail if adding the bitmap
923 if (!AddGfxImageToIconFamily(icon_family.GetAsIconFamilyHandle(), *it))
932 base::FilePath resources_path = GetResourcesPath(app_path);
933 if (!base::CreateDirectory(resources_path))
936 return icon_family.WriteDataToFile(resources_path.Append("app.icns"));
939 bool WebAppShortcutCreator::UpdateInternalBundleIdentifier() const {
940 NSString* plist_path = GetPlistPath(GetInternalShortcutPath());
941 NSMutableDictionary* plist = ReadPlist(plist_path);
943 [plist setObject:base::SysUTF8ToNSString(GetInternalBundleIdentifier())
944 forKey:base::mac::CFToNSCast(kCFBundleIdentifierKey)];
945 return [plist writeToFile:plist_path
949 base::FilePath WebAppShortcutCreator::GetAppBundleById(
950 const std::string& bundle_id) const {
951 base::ScopedCFTypeRef<CFStringRef> bundle_id_cf(
952 base::SysUTF8ToCFStringRef(bundle_id));
953 CFURLRef url_ref = NULL;
954 OSStatus status = LSFindApplicationForInfo(
955 kLSUnknownCreator, bundle_id_cf.get(), NULL, NULL, &url_ref);
957 return base::FilePath();
959 base::ScopedCFTypeRef<CFURLRef> url(url_ref);
960 NSString* path_string = [base::mac::CFToNSCast(url.get()) path];
961 return base::FilePath([path_string fileSystemRepresentation]);
964 std::string WebAppShortcutCreator::GetBundleIdentifier() const {
965 // Replace spaces in the profile path with hyphen.
966 std::string normalized_profile_path;
967 base::ReplaceChars(info_.profile_path.BaseName().value(),
968 " ", "-", &normalized_profile_path);
970 // This matches APP_MODE_APP_BUNDLE_ID in chrome/chrome.gyp.
971 std::string bundle_id =
972 base::mac::BaseBundleID() + std::string(".app.") +
973 normalized_profile_path + "-" + info_.extension_id;
978 std::string WebAppShortcutCreator::GetInternalBundleIdentifier() const {
979 return GetBundleIdentifier() + "-internal";
982 void WebAppShortcutCreator::RevealAppShimInFinder() const {
983 base::FilePath app_path = GetApplicationsShortcutPath();
984 if (app_path.empty())
987 // Check if the app shim exists.
988 if (base::PathExists(app_path)) {
989 // Use selectFile to show the contents of parent directory with the app
991 [[NSWorkspace sharedWorkspace]
992 selectFile:base::mac::FilePathToNSString(app_path)
993 inFileViewerRootedAtPath:nil];
997 // Otherwise, go up a directory.
998 app_path = app_path.DirName();
999 // Check if the Chrome apps folder exists, otherwise go up to ~/Applications.
1000 if (!base::PathExists(app_path))
1001 app_path = app_path.DirName();
1002 // Since |app_path| is a directory, use openFile to show the contents of
1003 // that directory in Finder.
1004 [[NSWorkspace sharedWorkspace]
1005 openFile:base::mac::FilePathToNSString(app_path)];
1008 base::FilePath GetAppInstallPath(const ShortcutInfo& shortcut_info) {
1009 WebAppShortcutCreator shortcut_creator(
1010 base::FilePath(), shortcut_info, extensions::FileHandlersInfo());
1011 return shortcut_creator.GetApplicationsShortcutPath();
1014 void MaybeLaunchShortcut(const ShortcutInfo& shortcut_info) {
1015 if (AppShimsDisabledForTest() &&
1016 !g_app_shims_allow_update_and_launch_in_tests) {
1020 content::BrowserThread::PostTask(
1021 content::BrowserThread::FILE,
1023 base::Bind(&LaunchShimOnFileThread, shortcut_info, false));
1026 bool MaybeRebuildShortcut(const base::CommandLine& command_line) {
1027 if (!command_line.HasSwitch(app_mode::kAppShimError))
1030 base::PostTaskAndReplyWithResult(
1031 content::BrowserThread::GetBlockingPool(),
1033 base::Bind(&RecordAppShimErrorAndBuildShortcutInfo,
1034 command_line.GetSwitchValuePath(app_mode::kAppShimError)),
1035 base::Bind(&RebuildAppAndLaunch));
1039 // Called when the app's ShortcutInfo (with icon) is loaded when creating app
1041 void CreateAppShortcutInfoLoaded(
1043 const extensions::Extension* app,
1044 const base::Callback<void(bool)>& close_callback,
1045 const ShortcutInfo& shortcut_info) {
1046 base::scoped_nsobject<NSAlert> alert([[NSAlert alloc] init]);
1048 NSButton* continue_button = [alert
1049 addButtonWithTitle:l10n_util::GetNSString(IDS_CREATE_SHORTCUTS_COMMIT)];
1050 [continue_button setKeyEquivalent:kKeyEquivalentReturn];
1052 NSButton* cancel_button =
1053 [alert addButtonWithTitle:l10n_util::GetNSString(IDS_CANCEL)];
1054 [cancel_button setKeyEquivalent:kKeyEquivalentEscape];
1056 [alert setMessageText:l10n_util::GetNSString(IDS_CREATE_SHORTCUTS_LABEL)];
1057 [alert setAlertStyle:NSInformationalAlertStyle];
1059 base::scoped_nsobject<NSButton> application_folder_checkbox(
1060 [[NSButton alloc] initWithFrame:NSZeroRect]);
1061 [application_folder_checkbox setButtonType:NSSwitchButton];
1062 [application_folder_checkbox
1063 setTitle:l10n_util::GetNSString(IDS_CREATE_SHORTCUTS_APP_FOLDER_CHKBOX)];
1064 [application_folder_checkbox setState:NSOnState];
1065 [application_folder_checkbox sizeToFit];
1067 base::scoped_nsobject<CrCreateAppShortcutCheckboxObserver> checkbox_observer(
1068 [[CrCreateAppShortcutCheckboxObserver alloc]
1069 initWithCheckbox:application_folder_checkbox
1070 continueButton:continue_button]);
1071 [checkbox_observer startObserving];
1073 [alert setAccessoryView:application_folder_checkbox];
1075 const int kIconPreviewSizePixels = 128;
1076 const int kIconPreviewTargetSize = 64;
1077 const gfx::Image* icon = shortcut_info.favicon.GetBest(
1078 kIconPreviewSizePixels, kIconPreviewSizePixels);
1080 if (icon && !icon->IsEmpty()) {
1081 NSImage* icon_image = icon->ToNSImage();
1083 setSize:NSMakeSize(kIconPreviewTargetSize, kIconPreviewTargetSize)];
1084 [alert setIcon:icon_image];
1087 bool dialog_accepted = false;
1088 if ([alert runModal] == NSAlertFirstButtonReturn &&
1089 [application_folder_checkbox state] == NSOnState) {
1090 dialog_accepted = true;
1092 SHORTCUT_CREATION_BY_USER, ShortcutLocations(), profile, app);
1095 [checkbox_observer stopObserving];
1097 if (!close_callback.is_null())
1098 close_callback.Run(dialog_accepted);
1101 void UpdateShortcutsForAllApps(Profile* profile,
1102 const base::Closure& callback) {
1103 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1105 extensions::ExtensionRegistry* registry =
1106 extensions::ExtensionRegistry::Get(profile);
1111 scoped_ptr<extensions::ExtensionSet> everything =
1112 registry->GenerateInstalledExtensionsSet();
1113 for (extensions::ExtensionSet::const_iterator it = everything->begin();
1114 it != everything->end(); ++it) {
1115 if (web_app::ShouldCreateShortcutFor(SHORTCUT_CREATION_AUTOMATED, profile,
1117 web_app::UpdateAllShortcuts(base::string16(), profile, it->get());
1124 void RevealAppShimInFinderForApp(Profile* profile,
1125 const extensions::Extension* app) {
1126 const web_app::ShortcutInfo shortcut_info =
1127 ShortcutInfoForExtensionAndProfile(app, profile);
1128 content::BrowserThread::PostTask(
1129 content::BrowserThread::FILE, FROM_HERE,
1130 base::Bind(&RevealAppShimInFinderForAppOnFileThread, shortcut_info,
1134 namespace internals {
1136 bool CreatePlatformShortcuts(
1137 const base::FilePath& app_data_path,
1138 const ShortcutInfo& shortcut_info,
1139 const extensions::FileHandlersInfo& file_handlers_info,
1140 const ShortcutLocations& creation_locations,
1141 ShortcutCreationReason creation_reason) {
1142 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
1143 if (AppShimsDisabledForTest())
1146 WebAppShortcutCreator shortcut_creator(
1147 app_data_path, shortcut_info, file_handlers_info);
1148 return shortcut_creator.CreateShortcuts(creation_reason, creation_locations);
1151 void DeletePlatformShortcuts(const base::FilePath& app_data_path,
1152 const ShortcutInfo& shortcut_info) {
1153 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
1154 WebAppShortcutCreator shortcut_creator(
1155 app_data_path, shortcut_info, extensions::FileHandlersInfo());
1156 shortcut_creator.DeleteShortcuts();
1159 void UpdatePlatformShortcuts(
1160 const base::FilePath& app_data_path,
1161 const base::string16& old_app_title,
1162 const ShortcutInfo& shortcut_info,
1163 const extensions::FileHandlersInfo& file_handlers_info) {
1164 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
1165 if (AppShimsDisabledForTest() &&
1166 !g_app_shims_allow_update_and_launch_in_tests) {
1170 WebAppShortcutCreator shortcut_creator(
1171 app_data_path, shortcut_info, file_handlers_info);
1172 shortcut_creator.UpdateShortcuts();
1175 void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) {
1176 const std::string profile_base_name = profile_path.BaseName().value();
1177 std::vector<base::FilePath> bundles = GetAllAppBundlesInPath(
1178 profile_path.Append(chrome::kWebAppDirname), profile_base_name);
1180 for (std::vector<base::FilePath>::const_iterator it = bundles.begin();
1181 it != bundles.end(); ++it) {
1182 web_app::ShortcutInfo shortcut_info =
1183 BuildShortcutInfoFromBundle(*it);
1184 WebAppShortcutCreator shortcut_creator(
1185 it->DirName(), shortcut_info, extensions::FileHandlersInfo());
1186 shortcut_creator.DeleteShortcuts();
1190 } // namespace internals
1192 } // namespace web_app
1196 void ShowCreateChromeAppShortcutsDialog(
1197 gfx::NativeWindow /*parent_window*/,
1199 const extensions::Extension* app,
1200 const base::Callback<void(bool)>& close_callback) {
1201 web_app::GetShortcutInfoForApp(
1204 base::Bind(&web_app::CreateAppShortcutInfoLoaded,
1210 } // namespace chrome