File: shortcut_creator_mac.mm

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (132 lines) | stat: -rw-r--r-- 5,155 bytes parent folder | download | duplicates (3)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/shortcuts/shortcut_creator.h"

#import <AppKit/AppKit.h>

#include "base/apple/bundle_locations.h"
#include "base/apple/foundation_util.h"
#include "base/base_paths.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/functional/concurrent_callbacks.h"
#include "base/functional/function_ref.h"
#include "base/mac/mac_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/shortcuts/chrome_webloc_file.h"
#include "chrome/browser/shortcuts/platform_util_mac.h"
#include "ui/gfx/image/image_family.h"
#include "url/gurl.h"

namespace shortcuts {

void CreateShortcutOnUserDesktop(ShortcutMetadata shortcut_metadata,
                                 ShortcutCreatorCallback complete) {
  CHECK(shortcut_metadata.IsValid());
  using Result = ShortcutCreatorResult;
  const GURL& shortcut_url = shortcut_metadata.shortcut_url;

  base::FilePath desktop_path;
  if (!base::PathService::Get(base::DIR_USER_DESKTOP, &desktop_path)) {
    std::move(complete).Run(/*created_shortcut_path=*/base::FilePath(),
                            Result::kError);
    return;
  }

  std::optional<base::SafeBaseName> base_name = SanitizeTitleForFileName(
      base::UTF16ToUTF8(shortcut_metadata.shortcut_title));
  if (!base_name.has_value()) {
    base_name = SanitizeTitleForFileName(shortcut_url.spec());
  }
  CHECK(base_name.has_value());

  base::FilePath target_path = base::GetUniquePath(
      desktop_path.Append(*base_name)
          .AddExtensionASCII(ChromeWeblocFile::kFileExtension));
  if (target_path.empty()) {
    std::move(complete).Run(/*created_shortcut_path=*/base::FilePath(),
                            Result::kError);
    return;
  }

  auto profile_path_name =
      base::SafeBaseName::Create(shortcut_metadata.profile_path);
  if (!profile_path_name.has_value() ||
      !ChromeWeblocFile(shortcut_url, *profile_path_name)
           .SaveToFile(target_path)) {
    std::move(complete).Run(/*created_shortcut_path=*/base::FilePath(),
                            Result::kError);
    return;
  }

  // None of the remaining operations are considered fatal; i.e. shortcut
  // creation is still considered a success if any of these fail as the
  // created shortcut should work just fine even without any of this in the
  // vast majority of cases.
  base::ConcurrentCallbacks<bool> concurrent;

  [NSWorkspace.sharedWorkspace
      setDefaultApplicationAtURL:base::apple::MainBundleURL()
                 toOpenFileAtURL:base::apple::FilePathToNSURL(target_path)
               completionHandler:
                   base::CallbackToBlock(base::BindPostTaskToCurrentDefault(
                       base::BindOnce([](NSError* error) {
                         if (error) {
                           LOG(ERROR) << "Failed to set default application "
                                         "for shortcut.";
                         }
                         return !error;
                       }).Then(concurrent.CreateCallback())))];

  NSImage* icon_image = [[NSImage alloc] init];
  for (const gfx::Image& image : shortcut_metadata.shortcut_images) {
    NSArray<NSImageRep*>* image_reps = image.AsNSImage().representations;
    DCHECK_GE(image_reps.count, 1u);
    for (NSImageRep* rep in image_reps) {
      [icon_image addRepresentation:rep];
    }
  }
  SetIconForFile(icon_image, target_path,
                 base::BindOnce([](bool success) {
                   if (!success) {
                     LOG(ERROR) << "Failed to set icon for shortcut.";
                   }
                   return success;
                 }).Then(concurrent.CreateCallback()));

  std::move(concurrent)
      .Done(
          base::BindOnce(
              [](const base::FilePath& path, std::vector<bool> step_successes) {
                bool success = base::mac::RemoveQuarantineAttribute(path);
                step_successes.push_back(success);
                if (!success) {
                  LOG(ERROR) << "Failed to remove quarantine attribute "
                                "from shortcut.";
                }
                return base::Contains(step_successes, false)
                           ? Result::kSuccessWithErrors
                           : Result::kSuccess;
              },
              target_path)
              .Then(base::BindOnce(std::move(complete), target_path)));
}

scoped_refptr<base::SequencedTaskRunner> GetShortcutsTaskRunner() {
  return base::ThreadPool::CreateSequencedTaskRunner(
      {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
       base::TaskShutdownBehavior::BLOCK_SHUTDOWN});
}

}  // namespace shortcuts