File: font_data_service_impl.cc

package info (click to toggle)
chromium 145.0.7632.159-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,976,224 kB
  • sloc: cpp: 36,198,469; ansic: 7,634,080; javascript: 3,564,060; python: 1,649,622; xml: 838,470; asm: 717,087; pascal: 185,708; sh: 88,786; perl: 88,718; objc: 79,984; sql: 59,811; cs: 42,452; fortran: 24,101; makefile: 21,144; tcl: 15,277; php: 14,022; yacc: 9,066; ruby: 7,553; awk: 3,720; lisp: 3,233; lex: 1,328; ada: 727; jsp: 228; sed: 36
file content (385 lines) | stat: -rw-r--r-- 14,830 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
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
380
381
382
383
384
385
// 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 "components/services/font_data/font_data_service_impl.h"

#if BUILDFLAG(IS_WIN)
#include <windows.h>
#endif  // BUILDFLAG(IS_WIN)

#include <algorithm>
#include <utility>

#include "base/check.h"
#include "base/containers/heap_array.h"
#include "base/debug/dump_without_crashing.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/task/thread_pool.h"
#include "base/trace_event/trace_event.h"
#include "skia/ext/font_utils.h"
#include "third_party/skia/include/core/SkFontStyle.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/core/SkString.h"
#include "third_party/skia/include/core/SkTypeface.h"

namespace font_data_service {

namespace {

// Recorded in Chrome.FontDataService.CreateResult, don't modify/reorder without
// also changing FontDataServiceCreateResult in
// tools/metrics/histograms/metadata/chrome/enums.xml
enum class CreateResult {
  kNoTypeface = 0,
  kSuccessExistingSharedMemory = 1,
  kFailureExistingSharedMemory = 2,
  kSuccessSharingFileHandle = 3,
  kSuccessSharingNewMemoryRegion = 4,
  kFailureSharingNewMemoryRegion = 5,
  kMaxValue = kFailureSharingNewMemoryRegion,
};

// Recorded in Chrome.FontDataService.InvokedIPC, don't modify or re-order
// without also changing FontDataServiceIPC.
enum class FontDataServiceIPC {
  kMatchFamilyName = 0,
  kMatchFamilyNameCharacter = 1,
  kGetAllFamilyNames = 2,
  kLegacyMakeTypeface = 3,
  kMaxValue = kLegacyMakeTypeface,
};

// Value is arbitrary. The number should be small to conserve memory but large
// enough to fit a meaningful amount of fonts.
constexpr int kMemoryMapCacheSize = 128;

BASE_FEATURE(kDumpOnOOBFontDataServiceCache, base::FEATURE_DISABLED_BY_DEFAULT);

base::SequencedTaskRunner* GetFontDataServiceTaskRunner() {
  static base::NoDestructor<scoped_refptr<base::SequencedTaskRunner>>
      task_runner{base::ThreadPool::CreateSequencedTaskRunner(
          {base::MayBlock(), base::TaskPriority::USER_BLOCKING})};
  return task_runner->get();
}

void BindToFontService(
    mojo::PendingReceiver<font_data_service::mojom::FontDataService> receiver) {
  static base::NoDestructor<font_data_service::FontDataServiceImpl> service;
  service->BindReceiver(std::move(receiver));
}

constexpr SkFontStyle::Slant ConvertToFontStyle(mojom::TypefaceSlant slant) {
  switch (slant) {
    case mojom::TypefaceSlant::kRoman:
      return SkFontStyle::Slant::kUpright_Slant;
    case mojom::TypefaceSlant::kItalic:
      return SkFontStyle::Slant::kItalic_Slant;
    case mojom::TypefaceSlant::kOblique:
      return SkFontStyle::Slant::kOblique_Slant;
  }
  NOTREACHED();
}

}  // namespace

FontDataServiceImpl::MappedAsset::MappedAsset(
    std::unique_ptr<SkStreamAsset> asset,
    base::MappedReadOnlyRegion shared_memory)
    : asset(std::move(asset)), shared_memory(std::move(shared_memory)) {}

FontDataServiceImpl::MappedAsset::~MappedAsset() = default;

FontDataServiceImpl::FontDataServiceImpl()
    : font_manager_(skia::DefaultFontMgr()) {
  CHECK(font_manager_);
}

FontDataServiceImpl::~FontDataServiceImpl() = default;

void FontDataServiceImpl::ConnectToFontService(
    mojo::PendingReceiver<font_data_service::mojom::FontDataService> receiver) {
  GetFontDataServiceTaskRunner()->PostTask(
      FROM_HERE, base::BindOnce(&BindToFontService, std::move(receiver)));
}

void FontDataServiceImpl::BindReceiver(
    mojo::PendingReceiver<mojom::FontDataService> receiver) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  receivers_.Add(this, std::move(receiver));
}

std::tuple<base::File, uint64_t> FontDataServiceImpl::GetFileHandle(
    SkTypeface& typeface) {
  SkString font_path;
  typeface.getResourceName(&font_path);
  base::UmaHistogramBoolean("Chrome.FontDataService.EmptyPathOnGetFileHandle",
                            font_path.isEmpty());
#if BUILDFLAG(IS_LINUX)
  // TODO(crbug.com/463411679): `getResourceName()` is not implemented for
  // Linux, so the returned file will always be invalid and a memory region will
  // be shared instead.
  CHECK(font_path.isEmpty());
#endif  // BUILDFLAG(IS_LINUX)
  if (font_path.isEmpty()) {
    return {};
  }

  auto font_file_path = base::FilePath::FromUTF8Unsafe(font_path.c_str());
  base::UmaHistogramBoolean(
      "Chrome.FontDataService.FileHandlePathReferencesParent",
      font_file_path.ReferencesParent());

  auto font_file =
      base::File(font_file_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
                                     base::File::FLAG_WIN_EXCLUSIVE_WRITE);
#if BUILDFLAG(IS_WIN)
  if (!font_file.IsValid()) {
    base::UmaHistogramSparse("Chrome.FontDataService.WinLastError",
                             ::GetLastError());
  }
#endif  // BUILDFLAG(IS_WIN)

  return std::make_tuple(std::move(font_file), GetUniqueFileId(font_file_path));
}

void FontDataServiceImpl::MatchFamilyName(const std::string& family_name,
                                          mojom::TypefaceStylePtr style,
                                          MatchFamilyNameCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TRACE_EVENT("fonts", "FontDataServiceImpl::MatchFamilyName", "family_name",
              family_name);
  base::UmaHistogramEnumeration("Chrome.FontDataService.InvokedIPC",
                                FontDataServiceIPC::kMatchFamilyName);

  // Call the font manager of the browser process to process the proxied match
  // family request.
  SkFontStyle sk_font_style(style->weight, style->width,
                            ConvertToFontStyle(style->slant));
  sk_sp<SkTypeface> typeface =
      font_manager_->matchFamilyStyle(family_name.c_str(), sk_font_style);

  std::move(callback).Run(CreateMatchFamilyNameResult(typeface));
}

void FontDataServiceImpl::MatchFamilyNameCharacter(
    const std::string& family_name,
    mojom::TypefaceStylePtr style,
    const std::vector<std::string>& bcp47s,
    int32_t character,
    MatchFamilyNameCharacterCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TRACE_EVENT("fonts", "FontDataServiceImpl::MatchFamilyNameCharacter",
              "family_name", family_name);
  base::UmaHistogramEnumeration("Chrome.FontDataService.InvokedIPC",
                                FontDataServiceIPC::kMatchFamilyNameCharacter);

  // Call the font manager of the browser process to process the proxied match
  // family request.
  SkFontStyle sk_font_style(style->weight, style->width,
                            ConvertToFontStyle(style->slant));

  // Skia passes the language tags as an array of null-terminated c-strings with
  // a count. We transform that to an std::vector<std::string> to pass it over
  // mojo, but have to recreate the same structure before passing it to skia
  // functions again.
  std::vector<const char*> bcp47s_array;
  for (const auto& bcp47 : bcp47s) {
    bcp47s_array.push_back(bcp47.c_str());
  }

  sk_sp<SkTypeface> typeface = font_manager_->matchFamilyStyleCharacter(
      family_name.c_str(), sk_font_style, bcp47s_array.data(), bcp47s.size(),
      character);

  std::move(callback).Run(CreateMatchFamilyNameResult(typeface));
}

void FontDataServiceImpl::GetAllFamilyNames(
    GetAllFamilyNamesCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TRACE_EVENT("fonts", "FontDataServiceImpl::GetAllFamilyNames");
  base::UmaHistogramEnumeration("Chrome.FontDataService.InvokedIPC",
                                FontDataServiceIPC::kGetAllFamilyNames);

  int family_count = font_manager_->countFamilies();
  std::vector<std::string> result;
  result.reserve(family_count);

  for (int i = 0; i < family_count; ++i) {
    SkString out;
    font_manager_->getFamilyName(i, &out);
    result.emplace_back(out.begin(), out.end());
  }

  std::move(callback).Run(std::move(result));
}

void FontDataServiceImpl::LegacyMakeTypeface(
    const std::optional<std::string>& family_name,
    mojom::TypefaceStylePtr style,
    LegacyMakeTypefaceCallback callback) {
  base::UmaHistogramEnumeration("Chrome.FontDataService.InvokedIPC",
                                FontDataServiceIPC::kLegacyMakeTypeface);
  SkFontStyle sk_font_style(style->weight, style->width,
                            ConvertToFontStyle(style->slant));

  sk_sp<SkTypeface> typeface = font_manager_->legacyMakeTypeface(
      family_name ? family_name->c_str() : nullptr, sk_font_style);

  std::move(callback).Run(CreateMatchFamilyNameResult(typeface));
}

size_t FontDataServiceImpl::GetOrCreateAssetIndex(
    std::unique_ptr<SkStreamAsset> asset) {
  TRACE_EVENT("fonts", "FontDataServiceImpl::GetOrCreateAssetIndex");

  // An asset can be used for multiple typefaces (a.k.a different ttc_index).

  // On Windows, with DWrite font manager.
  //     SkDWriteFontFileStream : public SkStreamMemory
  // getMemoryBase would not be a nullptr in this case.
  intptr_t memory_base = reinterpret_cast<intptr_t>(asset->getMemoryBase());
  // Check into the memory assets cache.
  if (auto iter = address_to_asset_index_.find(memory_base);
      iter != address_to_asset_index_.end()) {
    return iter->second;
  }

  size_t asset_length = asset->getLength();
  base::MappedReadOnlyRegion shared_memory_region =
      base::ReadOnlySharedMemoryRegion::Create(asset_length);
  PCHECK(shared_memory_region.IsValid());

  size_t asset_index = assets_.size();

  {
    TRACE_EVENT("fonts",
                "FontDataServiceImpl::GetOrCreateAssetIndex - memory copy",
                "size", asset_length);
    size_t bytes_read = asset->read(shared_memory_region.mapping.memory(),
                                    shared_memory_region.mapping.size());
    CHECK_EQ(bytes_read, asset_length);
  }

  assets_.push_back(std::make_unique<MappedAsset>(
      std::move(asset), std::move(shared_memory_region)));

  // Update the assets cache.
  address_to_asset_index_[memory_base] = asset_index;

  return asset_index;
}

uint64_t FontDataServiceImpl::GetUniqueFileId(base::FilePath path) {
  uint64_t new_id = unique_path_ids_.size() + 1;
  auto [it, inserted] = unique_path_ids_.try_emplace(path, new_id);
  return it->second;
}

mojom::MatchFamilyNameResultPtr
FontDataServiceImpl::CreateMatchFamilyNameResult(sk_sp<SkTypeface> typeface) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  CreateResult result_status = CreateResult::kNoTypeface;

  auto result = mojom::MatchFamilyNameResult::New();

  if (typeface) {
    auto iter = typeface_to_asset_index_.find(typeface->uniqueID());
    if (iter != typeface_to_asset_index_.end()) {
      const size_t asset_index = iter->second.asset_index;
      base::ReadOnlySharedMemoryRegion region =
          assets_[asset_index]->shared_memory.region.Duplicate();
      result->ttc_index = iter->second.ttc_index;
      if (region.IsValid()) {
        result->typeface_data =
            mojom::TypefaceData::NewRegion(std::move(region));
        result_status = CreateResult::kSuccessExistingSharedMemory;
      } else {
        result_status = CreateResult::kFailureExistingSharedMemory;
      }
    } else {
      // While the stream is not necessary for file handles, fetch the ttc_index
      // if available. It is possible that the index will be set even if
      // openStream fails.
      auto stream = typeface->openStream(&result->ttc_index);

      // Try to share the font with a base::File. This is avoiding copy of the
      // content of the file.
      base::File font_file;
      uint64_t font_file_unique_id;
      std::tie(font_file, font_file_unique_id) = GetFileHandle(*typeface);
      if (font_file.IsValid()) {
        TRACE_EVENT("fonts", "FontDataServiceImpl - sharing file handle");
        result->typeface_data =
            mojom::TypefaceData::NewFontFile(mojom::TypefaceFile::New(
                std::move(font_file), font_file_unique_id));

        result_status = CreateResult::kSuccessSharingFileHandle;
      } else {
        TRACE_EVENT("fonts", "FontDataServiceImpl - sharing memory region");
        // If it failed to share as an base::File, try sharing with shared
        // memory. Try to open the stream and prepare shared memory that will be
        // shared with renderers. The content of the stream is copied into the
        // shared memory. If the stream data is invalid or if the cache is full,
        // return an invalid memory map region.
        // TODO(crbug.com/335680565): Improve cache by transitioning to LRU.
        if (stream && stream->hasLength() && (stream->getLength() > 0u) &&
            stream->getMemoryBase()) {
          UMA_HISTOGRAM_COUNTS_10000(
              "Chrome.FontDataService.MemoryMapCacheSize", assets_.size());
          if (assets_.size() >= kMemoryMapCacheSize &&
              base::FeatureList::IsEnabled(kDumpOnOOBFontDataServiceCache)) {
            base::debug::DumpWithoutCrashing();
          }
          const size_t asset_index = GetOrCreateAssetIndex(std::move(stream));
          base::ReadOnlySharedMemoryRegion region =
              assets_[asset_index]->shared_memory.region.Duplicate();
          typeface_to_asset_index_[typeface->uniqueID()] =
              MappedTypeface{asset_index, result->ttc_index};
          if (region.IsValid()) {
            result->typeface_data =
                mojom::TypefaceData::NewRegion(std::move(region));
            result_status = CreateResult::kSuccessSharingNewMemoryRegion;
          } else {
            result_status = CreateResult::kFailureSharingNewMemoryRegion;
          }
        }
      }
    }
  }

  UMA_HISTOGRAM_ENUMERATION("Chrome.FontDataService.CreateResult",
                            result_status);

  if (!result->typeface_data) {
    return nullptr;
  }

  const int axis_count = typeface->getVariationDesignPosition({});
  if (axis_count > 0) {
    auto coordinate_list =
        base::HeapArray<SkFontArguments::VariationPosition::Coordinate>::Uninit(
            axis_count);
    if (typeface->getVariationDesignPosition(coordinate_list) > 0) {
      result->variation_position = mojom::VariationPosition::New();
      result->variation_position->coordinates.reserve(coordinate_list.size());
      result->variation_position->coordinateCount = axis_count;
      std::ranges::transform(
          coordinate_list,
          std::back_inserter(result->variation_position->coordinates),
          [](const SkFontArguments::VariationPosition::Coordinate& coordinate) {
            return mojom::Coordinate::New(coordinate.axis, coordinate.value);
          });
    }
  }

  return result;
}

}  // namespace font_data_service