summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm
blob: 11368b4b87bb60dee48584371029319dfdc208e7 (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
/*
 * This file is part of the internal font implementation.
 *
 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
 * Copyright (c) 2010 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#import "third_party/blink/renderer/platform/fonts/font_platform_data.h"

#import <AppKit/NSFont.h>
#import <AvailabilityMacros.h>
#import "third_party/blink/public/platform/mac/web_sandbox_support.h"
#import "third_party/blink/public/platform/platform.h"
#import "third_party/blink/renderer/platform/fonts/font.h"
#import "third_party/blink/renderer/platform/fonts/opentype/font_settings.h"
#import "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_face.h"
#import "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#import "third_party/blink/renderer/platform/layout_test_support.h"
#import "third_party/blink/renderer/platform/wtf/retain_ptr.h"
#import "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#import "third_party/skia/include/ports/SkTypeface_mac.h"

namespace blink {

static bool CanLoadInProcess(NSFont* ns_font) {
  RetainPtr<CGFontRef> cg_font(kAdoptCF,
                               CTFontCopyGraphicsFont(toCTFontRef(ns_font), 0));
  // Toll-free bridged types CFStringRef and NSString*.
  RetainPtr<NSString> font_name(
      kAdoptNS, const_cast<NSString*>(reinterpret_cast<const NSString*>(
                    CGFontCopyPostScriptName(cg_font.Get()))));
  return ![font_name.Get() isEqualToString:@"LastResort"];
}

static CTFontDescriptorRef CascadeToLastResortFontDescriptor() {
  static CTFontDescriptorRef descriptor;
  if (descriptor)
    return descriptor;

  RetainPtr<CTFontDescriptorRef> last_resort(
      kAdoptCF, CTFontDescriptorCreateWithNameAndSize(CFSTR("LastResort"), 0));
  const void* descriptors[] = {last_resort.Get()};
  RetainPtr<CFArrayRef> values_array(
      kAdoptCF, CFArrayCreate(kCFAllocatorDefault, descriptors,
                              arraysize(descriptors), &kCFTypeArrayCallBacks));

  const void* keys[] = {kCTFontCascadeListAttribute};
  const void* values[] = {values_array.Get()};
  RetainPtr<CFDictionaryRef> attributes(
      kAdoptCF,
      CFDictionaryCreate(kCFAllocatorDefault, keys, values, arraysize(keys),
                         &kCFTypeDictionaryKeyCallBacks,
                         &kCFTypeDictionaryValueCallBacks));

  descriptor = CTFontDescriptorCreateWithAttributes(attributes.Get());

  return descriptor;
}

static sk_sp<SkTypeface> LoadFromBrowserProcess(NSFont* ns_font,
                                                float text_size) {
  // Send cross-process request to load font.
  WebSandboxSupport* sandbox_support = Platform::Current()->GetSandboxSupport();
  if (!sandbox_support) {
    // This function should only be called in response to an error loading a
    // font due to being blocked by the sandbox.
    // This by definition shouldn't happen if there is no sandbox support.
    NOTREACHED();
    return nullptr;
  }

  CGFontRef loaded_cg_font;
  uint32_t font_id;
  if (!sandbox_support->LoadFont(toCTFontRef(ns_font), &loaded_cg_font,
                                 &font_id)) {
    // TODO crbug.com/461279: Make this appear in the inspector console?
    DLOG(ERROR)
        << "Loading user font \"" << [[ns_font familyName] UTF8String]
        << "\" from non system location failed. Corrupt or missing font file?";
    return nullptr;
  }
  RetainPtr<CGFontRef> cg_font(kAdoptCF, loaded_cg_font);
  RetainPtr<CTFontRef> ct_font(
      kAdoptCF,
      CTFontCreateWithGraphicsFont(cg_font.Get(), text_size, 0,
                                   CascadeToLastResortFontDescriptor()));
  sk_sp<SkTypeface> return_font(
      SkCreateTypefaceFromCTFont(ct_font.Get(), cg_font.Get()));

  if (!return_font.get())
    // TODO crbug.com/461279: Make this appear in the inspector console?
    DLOG(ERROR)
        << "Instantiating SkTypeface from user font failed for font family \""
        << [[ns_font familyName] UTF8String] << "\".";
  return return_font;
}

void FontPlatformData::SetupPaintFont(PaintFont* paint_font,
                                      float,
                                      const Font* font) const {
  bool should_smooth_fonts = true;
  bool should_antialias = true;
  bool should_subpixel_position = true;

  if (font) {
    switch (font->GetFontDescription().FontSmoothing()) {
      case kAntialiased:
        should_smooth_fonts = false;
        break;
      case kSubpixelAntialiased:
        break;
      case kNoSmoothing:
        should_antialias = false;
        should_smooth_fonts = false;
        break;
      case kAutoSmoothing:
        // For the AutoSmooth case, don't do anything! Keep the default
        // settings.
        break;
    }
  }

  if (LayoutTestSupport::IsRunningLayoutTest()) {
    should_smooth_fonts = false;
    should_antialias = should_antialias &&
                       LayoutTestSupport::IsFontAntialiasingEnabledForTest();
    should_subpixel_position =
        LayoutTestSupport::IsTextSubpixelPositioningAllowedForTest();
  }

  paint_font->SetAntiAlias(should_antialias);
  paint_font->SetEmbeddedBitmapText(false);
  const float ts = text_size_ >= 0 ? text_size_ : 12;
  paint_font->SetTextSize(SkFloatToScalar(ts));
  paint_font->SetTypeface(paint_typeface_);
  paint_font->SetFakeBoldText(synthetic_bold_);
  paint_font->SetTextSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
  paint_font->SetLcdRenderText(should_smooth_fonts);
  paint_font->SetSubpixelText(should_subpixel_position);

  // When rendering using CoreGraphics, disable hinting when
  // webkit-font-smoothing:antialiased or text-rendering:geometricPrecision is
  // used.  See crbug.com/152304
  if (font &&
      (font->GetFontDescription().FontSmoothing() == kAntialiased ||
       font->GetFontDescription().TextRendering() == kGeometricPrecision))
    paint_font->SetHinting(SkPaint::kNo_Hinting);
}

FontPlatformData::FontPlatformData(NSFont* ns_font,
                                   float size,
                                   bool synthetic_bold,
                                   bool synthetic_italic,
                                   FontOrientation orientation,
                                   FontVariationSettings* variation_settings)
    : text_size_(size),
      synthetic_bold_(synthetic_bold),
      synthetic_italic_(synthetic_italic),
      orientation_(orientation),
      is_hash_table_deleted_value_(false) {
  DCHECK(ns_font);
  sk_sp<SkTypeface> typeface;
  if (CanLoadInProcess(ns_font)) {
    typeface.reset(SkCreateTypefaceFromCTFont(toCTFontRef(ns_font)));
  } else {
    // In process loading fails for cases where third party font manager
    // software registers fonts in non system locations such as /Library/Fonts
    // and ~/Library Fonts, see crbug.com/72727 or crbug.com/108645.
    typeface = LoadFromBrowserProcess(ns_font, size);
  }

  if (variation_settings && variation_settings->size() < UINT16_MAX) {
    SkFontArguments::Axis axes[variation_settings->size()];
    for (size_t i = 0; i < variation_settings->size(); ++i) {
      AtomicString feature_tag = variation_settings->at(i).Tag();
      axes[i] = {AtomicStringToFourByteTag(feature_tag),
                 SkFloatToScalar(variation_settings->at(i).Value())};
    }
    sk_sp<SkFontMgr> fm(SkFontMgr::RefDefault());
    // TODO crbug.com/670246: Refactor this to a future Skia API that acccepts
    // axis parameters on system fonts directly.
    typeface = fm->makeFromStream(
        typeface->openStream(nullptr)->duplicate(),
        SkFontArguments().setAxes(axes, variation_settings->size()));
  }
  // TODO(vmpstr): Save the creation parameters in PaintTypeface instead.
  paint_typeface_ = PaintTypeface::FromSkTypeface(typeface);
}

}  // namespace blink