File: holding_space_client_impl.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (379 lines) | stat: -rw-r--r-- 15,051 bytes parent folder | download | duplicates (4)
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Copyright 2020 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/ui/ash/holding_space/holding_space_client_impl.h"

#include <algorithm>
#include <memory>
#include <optional>

#include "ash/public/cpp/holding_space/holding_space_constants.h"
#include "ash/public/cpp/holding_space/holding_space_item.h"
#include "ash/public/cpp/holding_space/holding_space_metrics.h"
#include "ash/public/cpp/holding_space/holding_space_progress.h"
#include "base/barrier_closure.h"
#include "base/functional/bind.h"
#include "base/notreached.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/ash/file_manager/fileapi_util.h"
#include "chrome/browser/ash/file_manager/open_util.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/ash/clipboard/clipboard_util.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service_factory.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_util.h"
#include "components/drive/drive_pref_names.h"
#include "components/prefs/pref_service.h"
#include "net/base/mime_util.h"
#include "storage/browser/file_system/file_system_context.h"

namespace ash {
namespace {

using ItemLaunchFailureReason = holding_space_metrics::ItemLaunchFailureReason;

// Helpers ---------------------------------------------------------------------

// Returns the `HoldingSpaceKeyedService` associated with the given `profile`.
HoldingSpaceKeyedService* GetHoldingSpaceKeyedService(Profile* profile) {
  return HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(profile);
}

// Returns file info for the specified `file_path` or `std::nullopt` in the
// event that file info cannot be obtained.
using GetFileInfoCallback =
    base::OnceCallback<void(const std::optional<base::File::Info>&)>;
void GetFileInfo(Profile* profile,
                 const base::FilePath& file_path,
                 GetFileInfoCallback callback) {
  scoped_refptr<storage::FileSystemContext> file_system_context =
      file_manager::util::GetFileManagerFileSystemContext(profile);
  file_manager::util::GetMetadataForPath(
      file_system_context, file_path,
      {storage::FileSystemOperation::GetMetadataField::kIsDirectory,
       storage::FileSystemOperation::GetMetadataField::kSize},
      base::BindOnce(
          [](GetFileInfoCallback callback, base::File::Error error,
             const base::File::Info& info) {
            std::move(callback).Run(error == base::File::FILE_OK
                                        ? std::make_optional<>(info)
                                        : std::nullopt);
          },
          std::move(callback)));
}

// Opens an in-progress item and returns the reason for failure if any. Returns
// `std::nullopt` if successful. Runs the command `kOpenItem` if there is one;
// otherwise, opens `item` when the underlying download completes.
std::optional<ItemLaunchFailureReason> OpenInProgressItem(
    Profile* profile,
    const HoldingSpaceItem& item) {
  CHECK(!item.progress().IsComplete());

  auto command_iter = std::ranges::find(
      item.in_progress_commands(), HoldingSpaceCommandId::kOpenItem,
      &HoldingSpaceItem::InProgressCommand::command_id);
  if (command_iter != item.in_progress_commands().end()) {
    command_iter->handler.Run(&item, command_iter->command_id);
    return std::nullopt;
  }

  return GetHoldingSpaceKeyedService(profile)->OpenItemWhenComplete(&item);
}

// Returns the reason for failing to launch a holding space item for the
// specified open operation `result`. Returns `std::nullopt` on success.
std::optional<ItemLaunchFailureReason> ToItemLaunchFailureReason(
    platform_util::OpenOperationResult result) {
  switch (result) {
    case platform_util::OpenOperationResult::OPEN_SUCCEEDED:
      return std::nullopt;
    case platform_util::OpenOperationResult::OPEN_FAILED_PATH_NOT_FOUND:
      return ItemLaunchFailureReason::kPathNotFound;
    case platform_util::OpenOperationResult::OPEN_FAILED_INVALID_TYPE:
      return ItemLaunchFailureReason::kInvalidType;
    case platform_util::OpenOperationResult::
        OPEN_FAILED_NO_HANLDER_FOR_FILE_TYPE:
      return ItemLaunchFailureReason::kNoHandlerForFileType;
    case platform_util::OpenOperationResult::OPEN_FAILED_FILE_ERROR:
      return ItemLaunchFailureReason::kFileError;
  }
}

}  // namespace

// HoldingSpaceClientImpl ------------------------------------------------------

HoldingSpaceClientImpl::HoldingSpaceClientImpl(Profile* profile)
    : profile_(profile) {}

HoldingSpaceClientImpl::~HoldingSpaceClientImpl() = default;

const std::string& HoldingSpaceClientImpl::AddItemOfType(
    HoldingSpaceItem::Type type,
    const base::FilePath& file_path) {
  return GetHoldingSpaceKeyedService(profile_)->AddItemOfType(type, file_path);
}

void HoldingSpaceClientImpl::CopyImageToClipboard(const HoldingSpaceItem& item,
                                                  SuccessCallback callback) {
  holding_space_metrics::RecordItemAction(
      {&item}, holding_space_metrics::ItemAction::kCopy);

  std::string mime_type;
  if (!net::GetWellKnownMimeTypeFromFile(item.file().file_path, &mime_type) ||
      !net::MatchesMimeType(kMimeTypeImage, mime_type)) {
    std::move(callback).Run(/*success=*/false);
    return;
  }

  // Reading and decoding of the image file needs to be done on an I/O thread.
  base::ThreadPool::PostTaskAndReply(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(&clipboard_util::ReadFileAndCopyToClipboardLocal,
                     item.file().file_path),
      base::BindOnce(
          [](SuccessCallback callback) {
            // We don't currently receive a signal regarding whether image
            // decoding was successful or not. For the time being, assume
            // success when the task runs until proven otherwise.
            std::move(callback).Run(/*success=*/true);
          },
          std::move(callback)));
}

base::FilePath HoldingSpaceClientImpl::CrackFileSystemUrl(
    const GURL& file_system_url) const {
  return file_manager::util::GetFileManagerFileSystemContext(profile_)
      ->CrackURLInFirstPartyContext(file_system_url)
      .path();
}

bool HoldingSpaceClientImpl::IsDriveDisabled() const {
  return profile_->GetPrefs()->GetBoolean(drive::prefs::kDisableDrive);
}

void HoldingSpaceClientImpl::OpenDownloads(SuccessCallback callback) {
  auto file_path = file_manager::util::GetDownloadsFolderForProfile(profile_);
  if (file_path.empty()) {
    std::move(callback).Run(/*success=*/false);
    return;
  }
  file_manager::util::OpenItem(
      profile_, file_path, platform_util::OPEN_FOLDER,
      base::BindOnce(
          [](SuccessCallback callback,
             platform_util::OpenOperationResult result) {
            const bool success = result == platform_util::OPEN_SUCCEEDED;
            std::move(callback).Run(success);
          },
          std::move(callback)));
}

void HoldingSpaceClientImpl::OpenItems(
    const std::vector<const HoldingSpaceItem*>& items,
    SuccessCallback callback) {
  holding_space_metrics::RecordItemAction(
      items, holding_space_metrics::ItemAction::kLaunch);

  if (items.empty()) {
    std::move(callback).Run(/*success=*/false);
    return;
  }

  auto complete_success = std::make_unique<bool>(true);
  auto* complete_success_ptr = complete_success.get();

  base::RepeatingClosure barrier_closure = base::BarrierClosure(
      items.size(),
      base::BindOnce(
          [](std::unique_ptr<bool> complete_success, SuccessCallback callback) {
            std::move(callback).Run(*complete_success);
          },
          std::move(complete_success), std::move(callback)));

  for (const HoldingSpaceItem* item : items) {
    if (item->file().file_path.empty()) {
      holding_space_metrics::RecordItemLaunchFailure(
          item->type(), item->file().file_path,
          ItemLaunchFailureReason::kPathEmpty);
      *complete_success_ptr = false;
      barrier_closure.Run();
      continue;
    }
    if (!item->progress().IsComplete()) {
      const std::optional<ItemLaunchFailureReason> failure_to_launch_reason =
          OpenInProgressItem(profile_, *item);
      if (failure_to_launch_reason) {
        holding_space_metrics::RecordItemLaunchFailure(
            item->type(), item->file().file_path,
            failure_to_launch_reason.value());
      }
      *complete_success_ptr &= !failure_to_launch_reason.has_value();
      barrier_closure.Run();
      continue;
    }
    GetFileInfo(
        profile_, item->file().file_path,
        base::BindOnce(
            [](const base::WeakPtr<HoldingSpaceClientImpl>& weak_ptr,
               base::RepeatingClosure barrier_closure, bool* complete_success,
               const base::FilePath& file_path, HoldingSpaceItem::Type type,
               const std::optional<base::File::Info>& info) {
              if (!weak_ptr || !info.has_value()) {
                holding_space_metrics::RecordItemLaunchFailure(
                    type, file_path,
                    weak_ptr ? ItemLaunchFailureReason::kFileInfoError
                             : ItemLaunchFailureReason::kShutdown);
                *complete_success = false;
                barrier_closure.Run();
                return;
              }
              if (!info->size) {
                holding_space_metrics::RecordItemLaunchEmpty(type, file_path);
              }
              file_manager::util::OpenItem(
                  weak_ptr->profile_, file_path,
                  info.value().is_directory ? platform_util::OPEN_FOLDER
                                            : platform_util::OPEN_FILE,
                  base::BindOnce(
                      [](base::RepeatingClosure barrier_closure,
                         bool* complete_success, HoldingSpaceItem::Type type,
                         const base::FilePath& file_path,
                         platform_util::OpenOperationResult result) {
                        const bool success =
                            result == platform_util::OPEN_SUCCEEDED;
                        if (!success) {
                          holding_space_metrics::RecordItemLaunchFailure(
                              type, file_path,
                              ToItemLaunchFailureReason(result).value());
                          *complete_success = false;
                        }
                        barrier_closure.Run();
                      },
                      barrier_closure, complete_success, type, file_path));
            },
            weak_factory_.GetWeakPtr(), barrier_closure, complete_success_ptr,
            item->file().file_path, item->type()));
  }
}

void HoldingSpaceClientImpl::OpenMyFiles(SuccessCallback callback) {
  auto file_path = file_manager::util::GetMyFilesFolderForProfile(profile_);
  if (file_path.empty()) {
    std::move(callback).Run(/*success=*/false);
    return;
  }
  file_manager::util::OpenItem(
      profile_, file_path, platform_util::OPEN_FOLDER,
      base::BindOnce(
          [](SuccessCallback callback,
             platform_util::OpenOperationResult result) {
            const bool success = result == platform_util::OPEN_SUCCEEDED;
            std::move(callback).Run(success);
          },
          std::move(callback)));
}

void HoldingSpaceClientImpl::PinFiles(
    const std::vector<base::FilePath>& file_paths) {
  std::vector<storage::FileSystemURL> file_system_urls;

  for (const base::FilePath& file_path : file_paths) {
    const GURL crack_url =
        holding_space_util::ResolveFileSystemUrl(profile_, file_path);
    const storage::FileSystemURL& file_system_url =
        file_manager::util::GetFileManagerFileSystemContext(profile_)
            ->CrackURLInFirstPartyContext(crack_url);
    file_system_urls.push_back(file_system_url);
  }

  if (!file_system_urls.empty()) {
    GetHoldingSpaceKeyedService(profile_)->AddPinnedFiles(file_system_urls);
  }
}

void HoldingSpaceClientImpl::PinItems(
    const std::vector<const HoldingSpaceItem*>& items) {
  std::vector<storage::FileSystemURL> file_system_urls;

  // NOTE: In-progress holding space items are neither pin- nor unpin-able.
  HoldingSpaceKeyedService* service = GetHoldingSpaceKeyedService(profile_);
  for (const HoldingSpaceItem* item : items) {
    if (!item->progress().IsComplete()) {
      continue;
    }
    const GURL& crack_url = item->file().file_system_url;
    const storage::FileSystemURL& file_system_url =
        file_manager::util::GetFileManagerFileSystemContext(profile_)
            ->CrackURLInFirstPartyContext(crack_url);
    if (!service->ContainsPinnedFile(file_system_url)) {
      file_system_urls.push_back(file_system_url);
    }
  }

  if (!file_system_urls.empty()) {
    service->AddPinnedFiles(file_system_urls);
  }
}

void HoldingSpaceClientImpl::RefreshSuggestions() {
  GetHoldingSpaceKeyedService(profile_)->RefreshSuggestions();
}

void HoldingSpaceClientImpl::RemoveSuggestions(
    const std::vector<base::FilePath>& absolute_file_paths) {
  GetHoldingSpaceKeyedService(profile_)->RemoveSuggestions(absolute_file_paths);
}

void HoldingSpaceClientImpl::ShowItemInFolder(const HoldingSpaceItem& item,
                                              SuccessCallback callback) {
  holding_space_metrics::RecordItemAction(
      {&item}, holding_space_metrics::ItemAction::kShowInFolder);

  if (item.file().file_path.empty()) {
    std::move(callback).Run(/*success=*/false);
    return;
  }

  file_manager::util::ShowItemInFolder(
      profile_, item.file().file_path,
      base::BindOnce(
          [](SuccessCallback callback,
             platform_util::OpenOperationResult result) {
            const bool success = result == platform_util::OPEN_SUCCEEDED;
            std::move(callback).Run(success);
          },
          std::move(callback)));
}

void HoldingSpaceClientImpl::UnpinItems(
    const std::vector<const HoldingSpaceItem*>& items) {
  std::vector<storage::FileSystemURL> file_system_urls;

  // NOTE: In-progress holding space items are neither pin- nor unpin-able.
  HoldingSpaceKeyedService* service = GetHoldingSpaceKeyedService(profile_);
  for (const HoldingSpaceItem* item : items) {
    if (!item->progress().IsComplete()) {
      continue;
    }
    const GURL& crack_url = item->file().file_system_url;
    const storage::FileSystemURL& file_system_url =
        file_manager::util::GetFileManagerFileSystemContext(profile_)
            ->CrackURLInFirstPartyContext(crack_url);
    if (service->ContainsPinnedFile(file_system_url)) {
      file_system_urls.push_back(file_system_url);
    }
  }

  if (!file_system_urls.empty()) {
    service->RemovePinnedFiles(file_system_urls);
  }
}

}  // namespace ash