File: file_result.cc

package info (click to toggle)
chromium 139.0.7258.127-1~deb13u1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,096 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 (341 lines) | stat: -rw-r--r-- 12,652 bytes parent folder | download | duplicates (6)
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
// 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/ash/app_list/search/files/file_result.h"

#include <string>
#include <utility>
#include <vector>

#include "ash/public/cpp/app_list/app_list_types.h"
#include "ash/public/cpp/image_util.h"
#include "ash/public/cpp/style/dark_light_mode_controller.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ash/app_list/search/common/icon_constants.h"
#include "chrome/browser/ash/app_list/search/files/file_title.h"
#include "chrome/browser/ash/app_list/search/search_features.h"
#include "chrome/browser/ash/file_manager/fileapi_util.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/ui/ash/thumbnail_loader/thumbnail_loader.h"
#include "chromeos/ash/components/string_matching/fuzzy_tokenized_string_match.h"
#include "chromeos/ash/components/string_matching/tokenized_string.h"
#include "chromeos/ash/components/string_matching/tokenized_string_match.h"
#include "chromeos/ui/base/file_icon_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/mime_util.h"
#include "storage/browser/file_system/file_system_context.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"

namespace app_list {

namespace {

using ::ash::string_matching::FuzzyTokenizedStringMatch;
using ::ash::string_matching::TokenizedString;
using ::ash::string_matching::TokenizedStringMatch;

// The default relevance returned by CalculateRelevance.
constexpr double kDefaultRelevance = 0.5;

// The maximum penalty applied to a relevance by PenalizeRelevanceByAccessTime,
// which will multiply the relevance by a number in [`kMaxPenalty`, 1].
constexpr double kMaxPenalty = 0.6;

// The steepness of the penalty curve of PenalizeRelevanceByAccessTime. Larger
// values make the penalty increase faster as the last access time of the file
// increases. A value of 0.0029 results in a penalty multiplier of ~0.63 for a 1
// month old file.
// Note that files which have all been modified recently may end up with the
// same penalty, since this coefficient is not large enough to differentiate
// between them.
constexpr double kPenaltyCoeff = 0.0029;

constexpr int64_t kMillisPerDay = 1000 * 60 * 60 * 24;

gfx::Size GetIconSizeForDisplayType(ash::SearchResultDisplayType display_type) {
  switch (display_type) {
    case ash::SearchResultDisplayType::kList:
      return gfx::Size(kThumbnailDimension, kThumbnailDimension);
    case ash::SearchResultDisplayType::kImage:
      return gfx::Size(kImageSearchWidth, kImageSearchHeight);
    case ash::SearchResultDisplayType::kContinue:
    case ash::SearchResultDisplayType::kNone:
    case ash::SearchResultDisplayType::kAnswerCard:
    case ash::SearchResultDisplayType::kRecentApps:
    case ash::SearchResultDisplayType::kLast:
      NOTREACHED();
  }
}

// Generates base::File::Info for the result at `file_path`.
// Performs blocking File IO, so should not be run on UI thread.
base::File::Info GetFileInfo(base::FilePath file_path) {
  CHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI))
      << "FileIO attempted on UI thread.";

  base::File::Info info;
  if (!base::GetFileInfo(file_path, &info)) {
    return base::File::Info();
  }

  return info;
}

void LogRelevance(ChromeSearchResult::ResultType result_type,
                  const double relevance) {
  // Relevance scores are between 0 and 1, so we scale to 0 to 100 for logging.
  DCHECK((relevance >= 0) && (relevance <= 1));
  const int scaled_relevance = floor(100 * relevance);
  switch (result_type) {
    case FileResult::ResultType::kFileSearch:
      UMA_HISTOGRAM_EXACT_LINEAR("Apps.AppList.FileSearchProvider.Relevance",
                                 scaled_relevance, /*exclusive_max=*/101);
      break;
    case FileResult::ResultType::kDriveSearch:
      UMA_HISTOGRAM_EXACT_LINEAR("Apps.AppList.DriveSearchProvider.Relevance",
                                 scaled_relevance, /*exclusive_max=*/101);
      break;
    case FileResult::ResultType::kZeroStateFile:
      UMA_HISTOGRAM_EXACT_LINEAR("Apps.AppList.ZeroStateFileProvider.Relevance",
                                 scaled_relevance, /*exclusive_max=*/101);
      break;
    case FileResult::ResultType::kZeroStateDrive:
      UMA_HISTOGRAM_EXACT_LINEAR(
          "Apps.AppList.ZeroStateDriveProvider.Relevance", scaled_relevance,
          /*exclusive_max=*/101);
      break;
    case FileResult::ResultType::kImageSearch:
      // TODO(b/260646344): add UMA metric
      break;
    default:
      NOTREACHED();
  }
}

}  // namespace

FileResult::FileResult(const std::string& id,
                       const base::FilePath& filepath,
                       const std::optional<std::u16string>& details,
                       ResultType result_type,
                       DisplayType display_type,
                       float relevance,
                       const std::u16string& query,
                       Type type,
                       Profile* profile,
                       ash::ThumbnailLoader* thumbnail_loader)
    : filepath_(filepath),
      type_(type),
      profile_(profile),
      thumbnail_loader_(thumbnail_loader) {
  DCHECK(profile);
  set_id(id);
  SetCategory(Category::kFiles);
  SetDisplayType(display_type);

  set_relevance(relevance);
  if (display_type == DisplayType::kList) {
    // Chip and list results overlap, and only list results are fully launched.
    // So we only log metrics for list results.
    LogRelevance(result_type, relevance);
  }

  SetResultType(result_type);
  switch (result_type) {
    case ResultType::kZeroStateDrive:
      SetMetricsType(ash::ZERO_STATE_DRIVE);
      break;
    case ResultType::kZeroStateFile:
      SetMetricsType(ash::ZERO_STATE_FILE);
      break;
    case ResultType::kFileSearch:
      SetMetricsType(ash::FILE_SEARCH);
      break;
    case ResultType::kDriveSearch:
      SetMetricsType(ash::DRIVE_SEARCH);
      break;
    case ResultType::kImageSearch:
      SetMetricsType(ash::IMAGE_SEARCH);
      break;
    default:
      NOTREACHED();
  }

  SetTitle(GetFileTitle(filepath));

  if (details)
    SetDetails(details.value());

  // Initialize the file metadata.
  SetFilePath(filepath_);
  if (result_type == ash::AppListSearchResultType::kImageSearch) {
    SetDisplayableFilePath(
        file_manager::util::GetDisplayablePath(profile_, filepath_)
            .value_or(filepath_));
    SetMetadataLoaderCallback(base::BindRepeating(&GetFileInfo, filepath_));
  }

  if (display_type == DisplayType::kContinue) {
    UpdateChipIcon();
  } else {
    thumbnail_image_ = std::make_unique<ash::HoldingSpaceImage>(
        GetIconSizeForDisplayType(display_type), filepath_,
        base::BindRepeating(&FileResult::RequestThumbnail,
                            weak_factory_.GetWeakPtr()),
        base::BindRepeating(&FileResult::GetPlaceholderImage,
                            base::Unretained(this)));
    thumbnail_image_update_sub_ =
        thumbnail_image_->AddImageSkiaChangedCallback(base::BindRepeating(
            &FileResult::UpdateThumbnailIcon, base::Unretained(this)));
    UpdateThumbnailIcon();
  }

  if (auto* dark_light_mode_controller = ash::DarkLightModeController::Get())
    dark_light_mode_controller->AddObserver(this);
}

FileResult::~FileResult() {
  if (auto* dark_light_mode_controller = ash::DarkLightModeController::Get())
    dark_light_mode_controller->RemoveObserver(this);
}

void FileResult::Open(int event_flags) {
  switch (type_) {
    case Type::kFile:
      platform_util::OpenItem(profile_, filepath_,
                              platform_util::OpenItemType::OPEN_FILE,
                              platform_util::OpenOperationCallback());
      break;
    case Type::kDirectory:
    case Type::kSharedDirectory:
      platform_util::OpenItem(profile_, filepath_,
                              platform_util::OpenItemType::OPEN_FOLDER,
                              platform_util::OpenOperationCallback());
      break;
  }
}

std::optional<std::string> FileResult::DriveId() const {
  return drive_id_;
}

std::optional<GURL> FileResult::url() const {
  return url_;
}

// static
double FileResult::CalculateRelevance(
    const std::optional<TokenizedString>& query,
    const base::FilePath& filepath,
    const std::optional<base::Time>& last_accessed) {
  const std::u16string raw_title = GetFileTitle(filepath);
  const TokenizedString title(raw_title, TokenizedString::Mode::kWords);

  const bool use_default_relevance =
      !query || query.value().text().empty() || title.text().empty();
  UMA_HISTOGRAM_BOOLEAN("Apps.AppList.FileResult.DefaultRelevanceUsed",
                        use_default_relevance);
  if (use_default_relevance)
    return kDefaultRelevance;
  TokenizedStringMatch match;
  double relevance = match.Calculate(query.value(), title);
  if (!last_accessed) {
    return relevance;
  }

  // Apply a gaussian penalty based on the time delta. `time_delta` is converted
  // into millisecond fractions of a day for numerical stability.
  const double time_delta =
      static_cast<double>(
          (base::Time::Now() - last_accessed.value()).InMilliseconds()) /
      kMillisPerDay;
  const double penalty =
      kMaxPenalty +
      (1.0 - kMaxPenalty) * std::exp(-kPenaltyCoeff * time_delta * time_delta);
  DCHECK(penalty > 0.0 && penalty <= 1.0);
  return relevance * penalty;
}

void FileResult::RequestThumbnail(
    const base::FilePath& file_path,
    const gfx::Size& size,
    ash::HoldingSpaceImage::BitmapCallback callback) {
  if (!thumbnail_loader_) {
    std::move(callback).Run(nullptr, base::File::FILE_ERROR_FAILED);
    return;
  }
  thumbnail_loader_->Load({file_path, size}, std::move(callback));
}

void FileResult::OnColorModeChanged(bool dark_mode_enabled) {
  if (display_type() == DisplayType::kContinue) {
    UpdateChipIcon();
  }
}

void FileResult::UpdateThumbnailIcon() {
  const int dimension = GetIconSizeForDisplayType(display_type()).width();
  const auto shape = display_type() == DisplayType::kList
                         ? ash::SearchResultIconShape::kCircle
                         : ash::SearchResultIconShape::kRoundedRectangle;
  SetIcon(
      IconInfo(ui::ImageModel::FromImageSkia(thumbnail_image_->GetImageSkia()),
               dimension, shape, thumbnail_image_->UsingPlaceholder()));
}

gfx::ImageSkia FileResult::GetPlaceholderImage(
    const base::FilePath& file_path,
    const gfx::Size& size,
    const std::optional<bool>& dark_background,
    const std::optional<bool>& is_folder) {
  // Do not set the default chromeos icon to the image search result.
  if (display_type() == DisplayType::kImage) {
    return ash::image_util::CreateEmptyImage(size);
  }

  gfx::ImageSkia icon_image;
  switch (type_) {
    case Type::kFile:
      icon_image = chromeos::GetIconForPath(
          file_path, dark_background.value_or(true), kSystemIconDimension);
      break;
    case Type::kDirectory:
      icon_image = chromeos::GetIconFromType(chromeos::IconType::kFolder,
                                             dark_background.value_or(true),
                                             kSystemIconDimension);
      break;
    case Type::kSharedDirectory:
      icon_image = chromeos::GetIconFromType(chromeos::IconType::kFolderShared,
                                             dark_background.value_or(true),
                                             kSystemIconDimension);
      break;
  }
  return gfx::ImageSkiaOperations::CreateSuperimposedImage(
      ash::image_util::CreateEmptyImage(size), icon_image);
}

void FileResult::UpdateChipIcon() {
  // DarkLightModeController might be nullptr in tests.
  auto* dark_light_mode_controller = ash::DarkLightModeController::Get();
  const bool dark_background = dark_light_mode_controller &&
                               dark_light_mode_controller->IsDarkModeEnabled();

  SetChipIcon(chromeos::GetChipIconForPath(filepath_, dark_background));
}

::std::ostream& operator<<(::std::ostream& os, const FileResult& result) {
  return os << "{" << result.title() << ", " << result.relevance() << "}";
}

}  // namespace app_list