summaryrefslogtreecommitdiffstats
path: root/chrome/browser/web_applications/web_app_mac.mm
blob: 6da97950ee5a5e139698734de2e44b03c3bafc7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/web_applications/web_app_mac.h"

#import <Cocoa/Cocoa.h>

#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/mac/bundle_locations.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mac_logging.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/memory/scoped_nsobject.h"
#include "base/strings/sys_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/mac/app_mode_common.h"
#include "content/public/browser/browser_thread.h"
#include "grit/chromium_strings.h"
#include "skia/ext/skia_utils_mac.h"
#include "third_party/icon_family/IconFamily.h"
#include "ui/base/l10n/l10n_util_mac.h"
#include "ui/gfx/image/image_family.h"

namespace {

// Get the 100% image representation for |image|.
// This returns the representation with the same width and height as |image|
// itself. If there is no such representation, returns nil.
NSBitmapImageRep* NSImageGet100PRepresentation(NSImage* image) {
  NSSize image_size = [image size];
  for (NSBitmapImageRep* image_rep in [image representations]) {
    NSSize image_rep_size = [image_rep size];
    if (image_rep_size.width == image_size.width &&
        image_rep_size.height == image_size.height) {
      return image_rep;
    }
  }
  return nil;
}

// Adds |image_rep| to |icon_family|. Returns true on success, false on failure.
bool AddBitmapImageRepToIconFamily(IconFamily* icon_family,
                                   NSBitmapImageRep* image_rep) {
  NSSize size = [image_rep size];
  if (size.width != size.height)
    return false;

  switch (static_cast<int>(size.width)) {
    case 512:
      return [icon_family setIconFamilyElement:kIconServices512PixelDataARGB
                            fromBitmapImageRep:image_rep];
    case 256:
      return [icon_family setIconFamilyElement:kIconServices256PixelDataARGB
                            fromBitmapImageRep:image_rep];
    case 128:
      return [icon_family setIconFamilyElement:kThumbnail32BitData
                            fromBitmapImageRep:image_rep] &&
             [icon_family setIconFamilyElement:kThumbnail8BitMask
                            fromBitmapImageRep:image_rep];
    case 32:
      return [icon_family setIconFamilyElement:kLarge32BitData
                            fromBitmapImageRep:image_rep] &&
             [icon_family setIconFamilyElement:kLarge8BitData
                            fromBitmapImageRep:image_rep] &&
             [icon_family setIconFamilyElement:kLarge8BitMask
                            fromBitmapImageRep:image_rep] &&
             [icon_family setIconFamilyElement:kLarge1BitMask
                            fromBitmapImageRep:image_rep];
    case 16:
      return [icon_family setIconFamilyElement:kSmall32BitData
                            fromBitmapImageRep:image_rep] &&
             [icon_family setIconFamilyElement:kSmall8BitData
                            fromBitmapImageRep:image_rep] &&
             [icon_family setIconFamilyElement:kSmall8BitMask
                            fromBitmapImageRep:image_rep] &&
             [icon_family setIconFamilyElement:kSmall1BitMask
                            fromBitmapImageRep:image_rep];
    default:
      return false;
  }
}

base::FilePath GetWritableApplicationsDirectory() {
  base::FilePath path;
  if (base::mac::GetLocalDirectory(NSApplicationDirectory, &path) &&
      file_util::PathIsWritable(path)) {
    return path;
  }
  if (base::mac::GetUserDirectory(NSApplicationDirectory, &path))
    return path;
  return base::FilePath();
}

}  // namespace


namespace web_app {

const char kChromeAppDirName[] = "Chrome Apps.localized";

WebAppShortcutCreator::WebAppShortcutCreator(
    const base::FilePath& user_data_dir,
    const ShellIntegration::ShortcutInfo& shortcut_info,
    const string16& chrome_bundle_id)
    : user_data_dir_(user_data_dir),
      info_(shortcut_info),
      chrome_bundle_id_(chrome_bundle_id) {
}

WebAppShortcutCreator::~WebAppShortcutCreator() {
}

bool WebAppShortcutCreator::CreateShortcut() {
  base::FilePath app_name = internals::GetSanitizedFileName(info_.title);
  base::FilePath app_file_name = app_name.ReplaceExtension("app");
  base::FilePath dst_path = GetDestinationPath();
  if (dst_path.empty() || !file_util::DirectoryExists(dst_path.DirName())) {
    LOG(ERROR) << "Couldn't find an Applications directory to copy app to.";
    return false;
  }
  if (!file_util::CreateDirectory(dst_path)) {
    LOG(ERROR) << "Creating directory " << dst_path.value() << " failed.";
    return false;
  }

  base::FilePath app_path = dst_path.Append(app_file_name);
  app_path = file_util::MakeUniqueDirectory(app_path);
  if (app_path.empty()) {
    LOG(ERROR) << "Couldn't create a unique directory for app path: "
               << app_path.value();
    return false;
  }
  app_file_name = app_path.BaseName();

  base::ScopedTempDir scoped_temp_dir;
  if (!scoped_temp_dir.CreateUniqueTempDir())
    return false;
  base::FilePath staging_path = scoped_temp_dir.path().Append(app_file_name);

  // Update the app's plist and icon in a temp directory. This works around
  // a Finder bug where the app's icon doesn't properly update.
  if (!file_util::CopyDirectory(GetAppLoaderPath(), staging_path, true)) {
    LOG(ERROR) << "Copying app to staging path: " << staging_path.value()
               << " failed";
    return false;
  }

  if (!UpdatePlist(staging_path))
    return false;

  if (!UpdateIcon(staging_path))
    return false;

  if (!file_util::CopyDirectory(staging_path, dst_path, true)) {
    LOG(ERROR) << "Copying app to dst path: " << dst_path.value() << " failed";
    return false;
  }

  base::mac::RemoveQuarantineAttribute(app_path);
  RevealGeneratedBundleInFinder(app_path);

  return true;
}

base::FilePath WebAppShortcutCreator::GetAppLoaderPath() const {
  return base::mac::PathForFrameworkBundleResource(
      base::mac::NSToCFCast(@"app_mode_loader.app"));
}

base::FilePath WebAppShortcutCreator::GetDestinationPath() const {
  base::FilePath path = GetWritableApplicationsDirectory();
  if (path.empty())
    return path;
  return path.Append(kChromeAppDirName);
}

bool WebAppShortcutCreator::UpdatePlist(const base::FilePath& app_path) const {
  NSString* plist_path = base::mac::FilePathToNSString(
      app_path.Append("Contents").Append("Info.plist"));

  NSString* extension_id = base::SysUTF8ToNSString(info_.extension_id);
  NSString* extension_title = base::SysUTF16ToNSString(info_.title);
  NSString* extension_url = base::SysUTF8ToNSString(info_.url.spec());
  NSString* chrome_bundle_id = base::SysUTF16ToNSString(chrome_bundle_id_);
  NSDictionary* replacement_dict =
      [NSDictionary dictionaryWithObjectsAndKeys:
          extension_id, app_mode::kShortcutIdPlaceholder,
          extension_title, app_mode::kShortcutNamePlaceholder,
          extension_url, app_mode::kShortcutURLPlaceholder,
          chrome_bundle_id, app_mode::kShortcutBrowserBundleIDPlaceholder,
          nil];

  NSMutableDictionary* plist =
      [NSMutableDictionary dictionaryWithContentsOfFile:plist_path];
  NSArray* keys = [plist allKeys];

  // 1. Fill in variables.
  for (id key in keys) {
    NSString* value = [plist valueForKey:key];
    if (![value isKindOfClass:[NSString class]] || [value length] < 2)
      continue;

    // Remove leading and trailing '@'s.
    NSString* variable =
        [value substringWithRange:NSMakeRange(1, [value length] - 2)];

    NSString* substitution = [replacement_dict valueForKey:variable];
    if (substitution)
      [plist setObject:substitution forKey:key];
  }

  // 2. Fill in other values.
  [plist setObject:GetBundleIdentifier(plist)
            forKey:base::mac::CFToNSCast(kCFBundleIdentifierKey)];
  [plist setObject:base::mac::FilePathToNSString(user_data_dir_)
            forKey:app_mode::kCrAppModeUserDataDirKey];
  [plist setObject:base::mac::FilePathToNSString(info_.profile_path.BaseName())
            forKey:app_mode::kCrAppModeProfileDirKey];
  return [plist writeToFile:plist_path atomically:YES];
}

bool WebAppShortcutCreator::UpdateIcon(const base::FilePath& app_path) const {
  if (info_.favicon.empty())
    return true;

  scoped_nsobject<IconFamily> icon_family([[IconFamily alloc] init]);
  bool image_added = false;
  for (gfx::ImageFamily::const_iterator it = info_.favicon.begin();
       it != info_.favicon.end(); ++it) {
    if (it->IsEmpty())
      continue;
    NSBitmapImageRep* image_rep = NSImageGet100PRepresentation(it->ToNSImage());
    if (!image_rep)
      continue;

    // Missing an icon size is not fatal so don't fail if adding the bitmap
    // doesn't work.
    if (!AddBitmapImageRepToIconFamily(icon_family, image_rep))
      continue;

    image_added = true;
  }

  if (!image_added)
    return false;

  base::FilePath resources_path =
      app_path.Append("Contents").Append("Resources");
  if (!file_util::CreateDirectory(resources_path))
    return false;
  base::FilePath icon_path = resources_path.Append("app.icns");
  return [icon_family writeToFile:base::mac::FilePathToNSString(icon_path)];
}

NSString* WebAppShortcutCreator::GetBundleIdentifier(NSDictionary* plist) const
{
  NSString* bundle_id_template =
    base::mac::ObjCCast<NSString>(
        [plist objectForKey:base::mac::CFToNSCast(kCFBundleIdentifierKey)]);
  NSString* extension_id = base::SysUTF8ToNSString(info_.extension_id);
  NSString* placeholder =
      [NSString stringWithFormat:@"@%@@", app_mode::kShortcutIdPlaceholder];
  NSString* bundle_id =
      [bundle_id_template
          stringByReplacingOccurrencesOfString:placeholder
                                    withString:extension_id];
  return bundle_id;
}

void WebAppShortcutCreator::RevealGeneratedBundleInFinder(
    const base::FilePath& generated_bundle) const {
  [[NSWorkspace sharedWorkspace]
                    selectFile:base::mac::FilePathToNSString(generated_bundle)
      inFileViewerRootedAtPath:nil];
}

}  // namespace

namespace web_app {

namespace internals {

base::FilePath GetAppBundleByExtensionId(std::string extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
  // This matches APP_MODE_APP_BUNDLE_ID in chrome/chrome.gyp.
  std::string bundle_id =
      base::mac::BaseBundleID() + std::string(".app.") + extension_id;
  base::mac::ScopedCFTypeRef<CFStringRef> bundle_id_cf(
      base::SysUTF8ToCFStringRef(bundle_id));
  CFURLRef url_ref = NULL;
  OSStatus status = LSFindApplicationForInfo(
      kLSUnknownCreator, bundle_id_cf.get(), NULL, NULL, &url_ref);
  base::mac::ScopedCFTypeRef<CFURLRef> url(url_ref);

  if (status != noErr)
    return base::FilePath();

  NSString* path_string = [base::mac::CFToNSCast(url.get()) path];
  return base::FilePath([path_string fileSystemRepresentation]);
}

bool CreatePlatformShortcuts(
    const base::FilePath& web_app_path,
    const ShellIntegration::ShortcutInfo& shortcut_info,
    const ShellIntegration::ShortcutLocations& /*creation_locations*/) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
  string16 bundle_id = UTF8ToUTF16(base::mac::BaseBundleID());
  WebAppShortcutCreator shortcut_creator(web_app_path, shortcut_info,
                            bundle_id);
  return shortcut_creator.CreateShortcut();
}

void DeletePlatformShortcuts(
    const base::FilePath& web_app_path,
    const ShellIntegration::ShortcutInfo& info) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));

  base::FilePath bundle_path = GetAppBundleByExtensionId(info.extension_id);
  file_util::Delete(bundle_path, true);
}

void UpdatePlatformShortcuts(
    const base::FilePath& web_app_path,
    const ShellIntegration::ShortcutInfo& shortcut_info) {
  // TODO(benwells): Implement this when shortcuts / weblings are enabled on
  // mac.
}

}  // namespace internals

}  // namespace web_app