diff --git a/cocos/2d/assembler/label/font-utils.ts b/cocos/2d/assembler/label/font-utils.ts index 5faf752c94..46c6c6b26f 100644 --- a/cocos/2d/assembler/label/font-utils.ts +++ b/cocos/2d/assembler/label/font-utils.ts @@ -32,6 +32,7 @@ import { safeMeasureText, BASELINE_RATIO, MIDDLE_RATIO, getBaselineOffset, getSy import { director, DirectorEvent } from '../../../game/director'; import { ccwindow } from '../../../core/global-exports'; import { TextureBase } from '../../../asset/assets/texture-base'; +import { buildFontDesc, CssFontFamily, DEFAULT_FONT_FAMILY } from '../../utils/font-family'; export interface ISharedLabelData { canvas: HTMLCanvasElement; @@ -102,7 +103,7 @@ interface ILabelInfo { fontSize: number; lineHeight: number; hash: string; - fontFamily: string; + fontFamily: CssFontFamily; fontDesc: string; hAlign: number; vAlign: number; @@ -194,10 +195,7 @@ class LetterTexture { // Add a white background to avoid black edges. context.fillStyle = _backgroundStyle; context.fillRect(0, 0, width, height); - context.font = labelInfo.fontDesc.replace( - /(\d+)(\.\d+)?(px|em|rem|pt)/g, - (w, m: string, n: string, u: string) => (+m * fontScale + (+n || 0) * fontScale).toString() + u, - ); + context.font = buildFontDesc(labelInfo.fontSize * fontScale, labelInfo.fontFamily); const fontSize = labelInfo.fontSize * fontScale; const startX = width / 2; @@ -425,7 +423,7 @@ export interface IShareLabelInfo { hAlign: number; vAlign: number; hash: string; - fontFamily: string; + fontFamily: CssFontFamily; fontDesc: string; color: Color; isOutlined: boolean; @@ -441,7 +439,7 @@ export const shareLabelInfo: IShareLabelInfo = { hAlign: 0, vAlign: 0, hash: '', - fontFamily: '', + fontFamily: DEFAULT_FONT_FAMILY, fontDesc: 'Arial', color: Color.WHITE.clone(), isOutlined: false, diff --git a/cocos/2d/assembler/label/letter-font.ts b/cocos/2d/assembler/label/letter-font.ts index 57fd95d712..1b62165f93 100644 --- a/cocos/2d/assembler/label/letter-font.ts +++ b/cocos/2d/assembler/label/letter-font.ts @@ -26,6 +26,7 @@ import type { Label } from '../../components'; import { IAssembler } from '../../renderer/base'; import { BmfontUtils } from './bmfontUtils'; import { shareLabelInfo, LetterAtlas, computeHash, LetterRenderTexture } from './font-utils'; +import { buildFontDesc, CssFontFamily, getCanvasFontFamily } from '../../utils/font-family'; const _atlasWidth = 1024; const _atlasHeight = 1024; @@ -59,17 +60,8 @@ export class LetterFont extends BmfontUtils { } } - protected _getFontFamily (comp: Label): string { - let fontFamily = 'Arial'; - if (!comp.useSystemFont) { - if (comp.font) { - fontFamily = comp.font._nativeAsset || 'Arial'; - } - } else { - fontFamily = comp.fontFamily || 'Arial'; - } - - return fontFamily; + protected _getFontFamily (comp: Label): CssFontFamily { + return getCanvasFontFamily(comp); } protected _updateLabelInfo (comp: Label): void { @@ -79,12 +71,6 @@ export class LetterFont extends BmfontUtils { } protected _getFontDesc (): string { - let fontDesc = `${shareLabelInfo.fontSize.toString()}px `; - fontDesc += shareLabelInfo.fontFamily; - if (_isBold) { - fontDesc = `bold ${fontDesc}`; - } - - return fontDesc; + return buildFontDesc(shareLabelInfo.fontSize, shareLabelInfo.fontFamily, _isBold); } } diff --git a/cocos/2d/assembler/label/text-processing.ts b/cocos/2d/assembler/label/text-processing.ts index 90f1275159..fad2e4b279 100644 --- a/cocos/2d/assembler/label/text-processing.ts +++ b/cocos/2d/assembler/label/text-processing.ts @@ -45,6 +45,7 @@ import { safeMeasureText, } from '../../utils/text-utils'; import type { Batcher2D } from '../../renderer/batcher-2d'; +import { buildFontDesc, CssFontFamily } from '../../utils/font-family'; const Alignment = [ 'left', // macro.TextAlignment.LEFT @@ -260,18 +261,8 @@ export class TextProcessing { } // can cache - private _getFontDesc (fontSize: number, fontFamily: string, isBold: boolean, isItalic: boolean): string { - let fontDesc = `${fontSize.toString()}px `; - fontDesc += fontFamily; - if (isBold) { - fontDesc = `bold ${fontDesc}`; - } - - if (isItalic) { - fontDesc = `italic ${fontDesc}`; - } - - return fontDesc; + private _getFontDesc (fontSize: number, fontFamily: CssFontFamily, isBold: boolean, isItalic: boolean): string { + return buildFontDesc(fontSize, fontFamily, isBold, isItalic); } // can cache diff --git a/cocos/2d/assembler/label/text-style.ts b/cocos/2d/assembler/label/text-style.ts index 590f4c0384..3a01f5e3a3 100644 --- a/cocos/2d/assembler/label/text-style.ts +++ b/cocos/2d/assembler/label/text-style.ts @@ -25,6 +25,7 @@ import { Color } from '../../../core'; import { IConfig } from '../../assets/bitmap-font'; import { SpriteFrame } from '../../assets/sprite-frame'; +import { CssFontFamily, DEFAULT_FONT_FAMILY } from '../../utils/font-family'; export class TextStyle { // ---------------ttf extra part----------------- @@ -59,7 +60,7 @@ export class TextStyle { public bmfontScale = 1.0;// both // font info // todo merge to font - public fontFamily = 'Arial'; // both + public fontFamily: CssFontFamily = DEFAULT_FONT_FAMILY; // Serialized CSS family, both TTF and CHAR. public fontDesc = ''; // both // -----------------------bitMap extra part------------------------- diff --git a/cocos/2d/assembler/label/ttfUtils.ts b/cocos/2d/assembler/label/ttfUtils.ts index 8addf52da3..d9350f2a37 100644 --- a/cocos/2d/assembler/label/ttfUtils.ts +++ b/cocos/2d/assembler/label/ttfUtils.ts @@ -31,6 +31,7 @@ import type { TextStyle } from './text-style'; import type { TextLayout } from './text-layout'; import { view } from '../../../ui/view'; import { approx } from '../../../core'; +import { CssFontFamily, getCanvasFontFamily } from '../../utils/font-family'; const Overflow = Label.Overflow; @@ -192,18 +193,8 @@ export class TTFUtils { // no needs to update uv data } - _updateFontFamily (comp: Label): string { - let _fontFamily = ''; - if (!comp.useSystemFont) { - if (comp.font) { - _fontFamily = comp.font._nativeAsset || 'Arial'; - } else { - _fontFamily = 'Arial'; - } - } else { - _fontFamily = comp.fontFamily || 'Arial'; - } - return _fontFamily; + _updateFontFamily (comp: Label): CssFontFamily { + return getCanvasFontFamily(comp); } _calDynamicAtlas (comp: Label, outputLayoutData: TextOutputLayoutData): void { diff --git a/cocos/2d/utils/font-family.ts b/cocos/2d/utils/font-family.ts new file mode 100644 index 0000000000..45c04e38c8 --- /dev/null +++ b/cocos/2d/utils/font-family.ts @@ -0,0 +1,65 @@ +/* + Copyright (c) 2026 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** A CSS family expression, distinct from an asset's raw font name. */ +export type CssFontFamily = string & { readonly __cssFontFamily: unique symbol }; + +export const DEFAULT_FONT_FAMILY = 'Arial' as CssFontFamily; + +/** Serialize one raw family name as a CSS string, preserving literal quotes and commas. */ +export function quoteFontFamily (name: string): CssFontFamily { + let result = '"'; + for (const character of name) { + const code = character.codePointAt(0)!; + if (code === 0 || (code >= 0xD800 && code <= 0xDFFF)) { + result += '\uFFFD'; + } else if (code <= 0x1F || code === 0x7F) { + result += `\\${code.toString(16)} `; + } else if (character === '"' || character === '\\') { + result += `\\${character}`; + } else { + result += character; + } + } + return `${result}"` as CssFontFamily; +} + +interface FontFamilySource { + readonly useSystemFont: boolean; + readonly fontFamily: string; + readonly font: { readonly _nativeAsset: unknown } | null; +} + +/** Resolve at the component boundary, before measurement, drawing or CSS assignment. */ +export function getCanvasFontFamily (source: FontFamilySource): CssFontFamily { + const system = source.useSystemFont; + const value = system ? source.fontFamily : source.font?._nativeAsset; + const name = typeof value === 'string' && value ? value : DEFAULT_FONT_FAMILY; + return system ? name as CssFontFamily : quoteFontFamily(name); +} + +/** Family is already serialized: changing size or style must never quote it again. */ +export function buildFontDesc (size: number, family: CssFontFamily, bold = false, italic = false): string { + return `${italic ? 'italic ' : ''}${bold ? 'bold ' : ''}${size}px ${family}`; +} diff --git a/cocos/2d/utils/font-loader.ts b/cocos/2d/utils/font-loader.ts index a4940d8a90..c6c9aa1add 100644 --- a/cocos/2d/utils/font-loader.ts +++ b/cocos/2d/utils/font-loader.ts @@ -23,7 +23,7 @@ */ import { warnID } from '../../core'; -import { safeMeasureText } from './text-utils'; +import { buildFontDesc, quoteFontFamily } from './font-family'; import downloader from '../../asset/asset-manager/downloader'; import factory from '../../asset/asset-manager/factory'; import { TTFFont } from '../assets/ttf-font'; @@ -31,10 +31,13 @@ import { ccwindow } from '../../core/global-exports'; const ccdocument = ccwindow.document; +type FontCallback = (err: Error | null, family?: string) => void; + interface IFontLoadHandle { fontFamilyName: string; + fontDesc: string; refWidth: number; - onComplete: ((err: Error | null, data?: any | null) => void); + onComplete: FontCallback; startTime: number; } @@ -90,9 +93,9 @@ function checkFontLoaded (): void { } const oldWidth = fontLoadHandle.refWidth; - const fontDesc = `40px ${fontFamily}`; - _canvasContext!.font = fontDesc; - const newWidth = safeMeasureText(_canvasContext!, _testString, fontDesc); + _canvasContext!.font = fontLoadHandle.fontDesc; + // Font availability changes while loading; do not cache fallback-font metrics. + const newWidth = _canvasContext!.measureText(_testString).width; // loaded successfully if (oldWidth !== newWidth) { _loadingFonts.splice(i, 1); @@ -109,7 +112,7 @@ function checkFontLoaded (): void { } // refer to https://github.com/typekit/webfontloader/blob/master/src/core/nativefontwatchrunner.js -function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Error | null, data?: any | null) => void)): void { +function nativeCheckFontLoaded (start: number, font: string, fontDesc: string, callback: FontCallback): void { const loader = new Promise((resolve, reject) => { const check = (): void => { const now = Date.now(); @@ -117,7 +120,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Er if (now - start >= _timeout) { reject(); } else { - (ccdocument as any).fonts.load(`40px ${font}`).then((fonts) => { + (ccdocument as any).fonts.load(fontDesc).then((fonts) => { if (fonts.length >= 1) { resolve(); } else { @@ -150,7 +153,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Er }); } -export function loadFont (url: string, options: Record, onComplete: ((err: Error | null, data?: any | null) => void)): void { +export function loadFont (url: string, options: Record, onComplete: FontCallback): void { const fontFamilyName = getFontFamily(url); // Already loaded fonts if (_fontFaces[fontFamilyName]) { @@ -166,17 +169,13 @@ export function loadFont (url: string, options: Record, onComplete: } // Default width reference to test whether new font is loaded correctly - const fontDesc = `40px ${fontFamilyName}`; + const familyCss = quoteFontFamily(fontFamilyName); + const fontDesc = buildFontDesc(40, familyCss); // Setup font face style const fontStyle = ccdocument.createElement('style'); fontStyle.type = 'text/css'; - let fontStr = ''; - if (Number.isNaN(fontFamilyName)) { - fontStr += `@font-face { font-family:${fontFamilyName}; src:`; - } else { - fontStr += `@font-face { font-family:"${fontFamilyName}"; src:`; - } + let fontStr = `@font-face { font-family:${familyCss}; src:`; fontStr += `url("${url}");`; fontStyle.textContent = `${fontStr}}`; ccdocument.body.appendChild(fontStyle); @@ -184,7 +183,7 @@ export function loadFont (url: string, options: Record, onComplete: // Preload font with div const preloadDiv = ccdocument.createElement('div'); const divStyle = preloadDiv.style; - divStyle.fontFamily = fontFamilyName; + divStyle.fontFamily = familyCss; preloadDiv.innerHTML = '.'; divStyle.position = 'absolute'; divStyle.left = '-100px'; @@ -192,12 +191,14 @@ export function loadFont (url: string, options: Record, onComplete: ccdocument.body.appendChild(preloadDiv); if (useNativeCheck()) { - nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete); + nativeCheckFontLoaded(Date.now(), fontFamilyName, fontDesc, onComplete); } else { - const refWidth = safeMeasureText(_canvasContext!, _testString, fontDesc); + _canvasContext!.font = fontDesc; + const refWidth = _canvasContext!.measureText(_testString).width; // Save loading font const fontLoadHandle = { fontFamilyName, + fontDesc, refWidth, onComplete, startTime: Date.now(), @@ -221,9 +222,6 @@ export function getFontFamily (fontHandle: string): string { } else { fontFamilyName = `${fontHandle.substring(slashPos + 1, ttfIndex)}_LABEL`; } - if (fontFamilyName.indexOf(' ') !== -1) { - fontFamilyName = `"${fontFamilyName}"`; - } return fontFamilyName; } diff --git a/cocos/ui/editbox/edit-box-impl.ts b/cocos/ui/editbox/edit-box-impl.ts index 78d712a4c8..ac9aed9409 100644 --- a/cocos/ui/editbox/edit-box-impl.ts +++ b/cocos/ui/editbox/edit-box-impl.ts @@ -41,6 +41,7 @@ import { InputFlag, InputMode, KeyboardReturnType } from './types'; import { EditBoxImplBase } from './edit-box-impl-base'; import { BrowserType, OS } from '../../../pal/system-info/enum-type'; import { ccwindow } from '../../core/global-exports'; +import { getCanvasFontFamily } from '../../2d/utils/font-family'; const ccdocument = ccwindow.document; @@ -519,7 +520,7 @@ export class EditBoxImpl extends EditBoxImplBase { let font = textLabel.font; if (font && !(font instanceof BitmapFont)) { - font = font._fontFamily; + font = getCanvasFontFamily(textLabel as Label); } else { font = textLabel.fontFamily; } @@ -570,7 +571,7 @@ export class EditBoxImpl extends EditBoxImplBase { let font = placeholderLabel.font; if (font && !(font instanceof BitmapFont)) { - font = placeholderLabel.font._fontFamily; + font = getCanvasFontFamily(placeholderLabel as Label); } else { font = placeholderLabel.fontFamily; } @@ -610,9 +611,12 @@ export class EditBoxImpl extends EditBoxImplBase { break; } - styleEl!.innerHTML = `#${this._domId}::-webkit-input-placeholder{text-transform: initial;-family: ${font};font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}` - + `#${this._domId}::-moz-placeholder{text-transform: initial;-family: ${font};font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}` - + `#${this._domId}::-ms-input-placeholder{text-transform: initial;-family: ${font};font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}`; + styleEl!.innerHTML = `#${this._domId}::-webkit-input-placeholder{text-transform: initial;-family: ${font};` + + `font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}` + + `#${this._domId}::-moz-placeholder{text-transform: initial;-family: ${font};` + + `font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}` + + `#${this._domId}::-ms-input-placeholder{text-transform: initial;-family: ${font};` + + `font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}`; // EDGE_BUG_FIX: hide clear button, because clearing input box in Edge does not emit input event // issue refference: https://github.com/angular/angular/issues/26307 if (sys.browserType === BrowserType.EDGE) { diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index f20e2fe822..e211ff739d 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -660,6 +660,8 @@ elseif(OPENHARMONY) endif() cocos_source_files( + cocos/platform/interfaces/modules/canvas/CanvasFont.cpp + cocos/platform/interfaces/modules/canvas/CanvasFont.h cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h diff --git a/native/cocos/platform/interfaces/modules/canvas/CanvasFont.cpp b/native/cocos/platform/interfaces/modules/canvas/CanvasFont.cpp new file mode 100644 index 0000000000..4f69dfbb9a --- /dev/null +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasFont.cpp @@ -0,0 +1,279 @@ +/* + Copyright (c) 2026 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "platform/interfaces/modules/canvas/CanvasFont.h" + +#include +#include +#include +#include +#include + +namespace cc::detail { +namespace { + +bool isSpace(char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; +} + +bool isNewline(char c) { + return c == '\n' || c == '\r' || c == '\f'; +} + +void skipSpace(std::string_view input, size_t &pos) { + while (pos < input.size() && isSpace(input[pos])) ++pos; +} + +int hexValue(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +void appendCodePoint(std::string &output, uint32_t code) { + if (code == 0 || code > 0x10FFFF || (code >= 0xD800 && code <= 0xDFFF)) code = 0xFFFD; + if (code < 0x80) { + output += static_cast(code); + } else if (code < 0x800) { + output += static_cast(0xC0 | (code >> 6)); + output += static_cast(0x80 | (code & 0x3F)); + } else if (code < 0x10000) { + output += static_cast(0xE0 | (code >> 12)); + output += static_cast(0x80 | ((code >> 6) & 0x3F)); + output += static_cast(0x80 | (code & 0x3F)); + } else { + output += static_cast(0xF0 | (code >> 18)); + output += static_cast(0x80 | ((code >> 12) & 0x3F)); + output += static_cast(0x80 | ((code >> 6) & 0x3F)); + output += static_cast(0x80 | (code & 0x3F)); + } +} + +// https://www.w3.org/TR/css-syntax-3/#consume-an-escaped-code-point +bool readEscape(std::string_view input, size_t &pos, bool quoted, std::string &output) { + if (++pos == input.size()) return false; + if (isNewline(input[pos])) { + if (!quoted) return false; + if (input[pos++] == '\r' && pos < input.size() && input[pos] == '\n') ++pos; + return true; + } + if (hexValue(input[pos]) >= 0) { + uint32_t code = 0; + for (int digits = 0; digits < 6 && pos < input.size() && hexValue(input[pos]) >= 0; ++digits) { + code = code * 16 + static_cast(hexValue(input[pos++])); + } + if (pos < input.size() && isSpace(input[pos])) { + if (input[pos++] == '\r' && pos < input.size() && input[pos] == '\n') ++pos; + } + appendCodePoint(output, code); + } else if (input[pos] == '\0') { + appendCodePoint(output, 0); + ++pos; + } else { + output += input[pos++]; + } + return true; +} + +bool decodeQuotedFamily(std::string_view input, std::string &family) { + size_t pos = 0; + skipSpace(input, pos); + if (pos == input.size() || (input[pos] != '"' && input[pos] != '\'')) return false; + const char quote = input[pos++]; + while (pos < input.size()) { + const char c = input[pos]; + if (c == quote) { + ++pos; + skipSpace(input, pos); + return pos == input.size() && !family.empty(); + } + if (isNewline(c)) return false; + if (c == '\\') { + if (!readEscape(input, pos, true, family)) return false; + } else if (c == '\0') { + appendCodePoint(family, 0); + ++pos; + } else { + family += c; + ++pos; + } + } + return false; +} + +} // namespace + +static CanvasFont parseLegacyCanvasFont(const std::string &font) { +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + + std::string boldStr; + std::string fontName = "Arial"; + std::string fontSizeStr = "30"; + + std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); + std::match_results results; + if (std::regex_search(font.cbegin(), font.cend(), results, re)) { + fontSizeStr = results[2].str(); + // support get font name from `60px American` or `60px "American abc-abc_abc"` + // support get font name contain space,example `times new roman` + // if regex rule that does not conform to the rules,such as Chinese,it defaults to Arial + std::match_results fontResults; + std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); + std::string tmp(results[4].str()); + if (std::regex_match(tmp, fontResults, fontRe)) { + fontName = results[4].str(); + } + } + + auto fontSize = static_cast(atof(fontSizeStr.c_str())); + bool isBold = !boldStr.empty() || font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos; + bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos; + return {fontName, static_cast(fontSize), isBold, isItalic, false, false}; +#elif CC_PLATFORM == CC_PLATFORM_QNX + + std::string boldStr; + std::string fontName = "Arial"; + std::string fontSizeStr = "30"; + + // support get font name from `60px American` or `60px "American abc-abc_abc"` + std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); + std::match_results results; + if (std::regex_search(font.cbegin(), font.cend(), results, re)) { + boldStr = results[1].str(); + fontSizeStr = results[2].str(); + fontName = results[5].str(); + } + bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos; + auto fontSize = static_cast(atof(fontSizeStr.c_str())); + bool isBold = !boldStr.empty() || font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos; + // SE_LOGD("CanvasRenderingContext2D::setfont: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold); + return {fontName, fontSize, isBold, isItalic, false, false}; +#elif CC_PLATFORM == CC_PLATFORM_LINUX + + std::string fontName = "sans-serif"; + std::string fontSizeStr = "30"; + std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); + std::match_results results; + if (std::regex_search(font.cbegin(), font.cend(), results, re)) { + fontSizeStr = results[2].str(); + // support get font name from `60px American` or `60px "American abc-abc_abc"` + // support get font name contain space,example `times new roman` + // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif + std::match_results fontResults; + std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); + std::string tmp(results[4].str()); + if (std::regex_match(tmp, fontResults, fontRe)) { + // fontName = results[4].str(); + } + } + + bool isBold = font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos; + bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos; + float fontSize = static_cast(atof(fontSizeStr.c_str())); + // SE_LOGD("CanvasRenderingContext2D::setfont: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold); + return {fontName, fontSize, isBold, isItalic, false, false}; +#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY + std::string fontName = "sans-serif"; + std::string fontSizeStr = "30"; + std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); + std::match_results results; + if (std::regex_search(font.cbegin(), font.cend(), results, re)) { + fontSizeStr = results[2].str(); + // support get font name from `60px American` or `60px "American abc-abc_abc"` + // support get font name contain space,example `times new roman` + // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif + std::match_results fontResults; + std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); + std::string tmp(results[4].str()); + if (std::regex_match(tmp, fontResults, fontRe)) { + fontName = results[4].str(); + } + } + + double fontSize = atof(fontSizeStr.c_str()); + bool isBold = font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos; + bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos; + bool isSmallCaps = font.find("small-caps", 0) != std::string::npos || font.find("Small-Caps") != std::string::npos; + bool isOblique = font.find("oblique", 0) != std::string::npos || font.find("Oblique", 0) != std::string::npos; + // font-style: italic, oblique, normal + // font-weight: normal, bold + // font-variant: normal, small-caps + return {fontName, static_cast(fontSize), isBold, isItalic, isOblique, isSmallCaps}; +#elif CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS + + std::string boldStr; + std::string fontName = "Arial"; + std::string fontSizeStr = "30"; + bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos; + + // support get font name from `60px American` or `60px "American abc-abc_abc"` + std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); + std::match_results results; + if (std::regex_search(font.cbegin(), font.cend(), results, re)) { + boldStr = results[1].str(); + fontSizeStr = results[2].str(); + fontName = results[5].str(); + } + float fontSize = atof(fontSizeStr.c_str()); + bool isBold = !boldStr.empty() || font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos; + return {fontName, static_cast(fontSize), isBold, isItalic, false, false}; +#endif + return {}; +} + +CanvasFont parseCanvasFont(const std::string &font) { + static const std::regex DESCRIPTION(R"(\s*((\d+)([\.]\d+)?)px\s+([\s\S]*))"); + std::smatch match; + std::string family; + if (!std::regex_search(font, match, DESCRIPTION) || !decodeQuotedFamily(match[4].str(), family)) { + return parseLegacyCanvasFont(font); + } + + // Recover the descriptor used before TS serialized the asset's registered alias. + // Use it only when the old platform parser recognizes that complete alias; + // partial matches and unsupported names keep the original fallback behavior. + const auto legacyDescription = font.substr(0, static_cast(match.position(4))) + family; + auto compatible = parseLegacyCanvasFont(legacyDescription); + if (compatible.family == family) { + return compatible; + } + auto fallback = parseLegacyCanvasFont(font); +#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX + // These platforms used to lose the size when the family was rejected. + // Recover it only for complete quoted families with an engine-supported + // style prefix. Keep the fallback family and existing style flags intact. + static const std::regex STYLE_PREFIX(R"(\s*(?:(?:normal|bold|italic|oblique|small-caps)\s+)*)", std::regex::icase); + if (std::regex_match(font.cbegin(), font.cbegin() + match.position(1), STYLE_PREFIX)) { + const auto size = static_cast(atof(match[1].str().c_str())); + // Native backends may narrow sizes to int. Do not recover unsafe values. + if (std::isfinite(size) && size >= 0.F && static_cast(size) <= std::numeric_limits::max()) { + fallback.size = size; + } + } +#endif + return fallback; +} + +} // namespace cc::detail diff --git a/native/cocos/platform/interfaces/modules/canvas/CanvasFont.h b/native/cocos/platform/interfaces/modules/canvas/CanvasFont.h new file mode 100644 index 0000000000..5d562934c7 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasFont.h @@ -0,0 +1,46 @@ +/* + Copyright (c) 2026 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#pragma once + +#include +#include "base/Macros.h" + +namespace cc::detail { + +struct CanvasFont { + std::string family; + float size{0.F}; + bool bold{false}; + bool italic{false}; + bool oblique{false}; + bool smallCaps{false}; +}; + +// Internal native Canvas parsing, including the existing per-platform fallbacks. +// Family interpretation must not depend on the font registry. Callers serialize raw +// asset aliases once as CSS strings, including any literal quotes in the alias. +CC_DLL CanvasFont parseCanvasFont(const std::string &font); + +} // namespace cc::detail diff --git a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp index 7d68e2719a..d462ac2d57 100644 --- a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp @@ -25,12 +25,12 @@ #include "platform/interfaces/modules/canvas/CanvasRenderingContext2D.h" #include -#include #include "base/csscolorparser.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_platform.h" #include "math/Math.h" #include "platform/FileUtils.h" +#include "platform/interfaces/modules/canvas/CanvasFont.h" #if defined(CC_SERVER_MODE) #include "platform/empty/modules/CanvasRenderingContext2DDelegate.h" @@ -218,133 +218,13 @@ void CanvasRenderingContext2D::rect(float x, float y, float w, float h) { void CanvasRenderingContext2D::setFont(const ccstd::string &font) { recreateBufferIfNeeded(); -#if CC_PLATFORM == CC_PLATFORM_WINDOWS +#if CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_QNX || CC_PLATFORM == CC_PLATFORM_LINUX \ + || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY \ + || CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS if (_font != font) { _font = font; - - ccstd::string boldStr; - ccstd::string fontName = "Arial"; - ccstd::string fontSizeStr = "30"; - - std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); - std::match_results results; - if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - fontSizeStr = results[2].str(); - // support get font name from `60px American` or `60px "American abc-abc_abc"` - // support get font name contain space,example `times new roman` - // if regex rule that does not conform to the rules,such as Chinese,it defaults to Arial - std::match_results fontResults; - std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); - ccstd::string tmp(results[4].str()); - if (std::regex_match(tmp, fontResults, fontRe)) { - fontName = results[4].str(); - } - } - - auto fontSize = static_cast(atof(fontSizeStr.c_str())); - bool isBold = !boldStr.empty() || font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos; - bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos; - _delegate->updateFont(fontName, static_cast(fontSize), isBold, isItalic, false, false); - } -#elif CC_PLATFORM == CC_PLATFORM_QNX - if (_font != font) { - _font = font; - - ccstd::string boldStr; - ccstd::string fontName = "Arial"; - ccstd::string fontSizeStr = "30"; - - // support get font name from `60px American` or `60px "American abc-abc_abc"` - std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); - std::match_results results; - if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - boldStr = results[1].str(); - fontSizeStr = results[2].str(); - fontName = results[5].str(); - } - bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos; - auto fontSize = static_cast(atof(fontSizeStr.c_str())); - bool isBold = !boldStr.empty() || font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos; - //SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold); - _delegate->updateFont(fontName, fontSize, isBold, isItalic, false, false); - } -#elif CC_PLATFORM == CC_PLATFORM_LINUX - if (_font != font) { - _font = font; - - ccstd::string fontName = "sans-serif"; - ccstd::string fontSizeStr = "30"; - std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); - std::match_results results; - if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - fontSizeStr = results[2].str(); - // support get font name from `60px American` or `60px "American abc-abc_abc"` - // support get font name contain space,example `times new roman` - // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif - std::match_results fontResults; - std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); - ccstd::string tmp(results[4].str()); - if (std::regex_match(tmp, fontResults, fontRe)) { - //fontName = results[4].str(); - } - } - - bool isBold = font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos; - bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos; - float fontSize = static_cast(atof(fontSizeStr.c_str())); - //SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold); - _delegate->updateFont(fontName, fontSize, isBold, isItalic, false, false); - } -#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY - if (_font != font) { - _font = font; - ccstd::string fontName = "sans-serif"; - ccstd::string fontSizeStr = "30"; - std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); - std::match_results results; - if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - fontSizeStr = results[2].str(); - // support get font name from `60px American` or `60px "American abc-abc_abc"` - // support get font name contain space,example `times new roman` - // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif - std::match_results fontResults; - std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); - ccstd::string tmp(results[4].str()); - if (std::regex_match(tmp, fontResults, fontRe)) { - fontName = results[4].str(); - } - } - - double fontSize = atof(fontSizeStr.c_str()); - bool isBold = font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos; - bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos; - bool isSmallCaps = font.find("small-caps", 0) != ccstd::string::npos || font.find("Small-Caps") != ccstd::string::npos; - bool isOblique = font.find("oblique", 0) != ccstd::string::npos || font.find("Oblique", 0) != ccstd::string::npos; - //font-style: italic, oblique, normal - //font-weight: normal, bold - //font-variant: normal, small-caps - _delegate->updateFont(fontName, static_cast(fontSize), isBold, isItalic, isOblique, isSmallCaps); - } -#elif CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS - if (_font != font) { - _font = font; - - ccstd::string boldStr; - ccstd::string fontName = "Arial"; - ccstd::string fontSizeStr = "30"; - bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos; - - // support get font name from `60px American` or `60px "American abc-abc_abc"` - std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); - std::match_results results; - if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - boldStr = results[1].str(); - fontSizeStr = results[2].str(); - fontName = results[5].str(); - } - float fontSize = atof(fontSizeStr.c_str()); - bool isBold = !boldStr.empty() || font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos; - _delegate->updateFont(fontName, static_cast(fontSize), isBold, isItalic, false, false); + const auto parsed = detail::parseCanvasFont(font); + _delegate->updateFont(parsed.family, parsed.size, parsed.bold, parsed.italic, parsed.oblique, parsed.smallCaps); } #endif } diff --git a/native/tests/unit-test/src/canvas_font_compatibility_test.cpp b/native/tests/unit-test/src/canvas_font_compatibility_test.cpp new file mode 100644 index 0000000000..d067bfdfea --- /dev/null +++ b/native/tests/unit-test/src/canvas_font_compatibility_test.cpp @@ -0,0 +1,84 @@ +/* + Copyright (c) 2026 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include "gtest/gtest.h" +#include "platform/interfaces/modules/canvas/CanvasFont.h" + +namespace { + +std::string expectedFamily(const std::string &family) { +#if CC_PLATFORM == CC_PLATFORM_LINUX + return "sans-serif"; +#else + return family; +#endif +} + +} // namespace + +using cc::detail::parseCanvasFont; + +TEST(CanvasFontCompatibilityTest, ExplicitSerializationKeepsCollidingAliasesDistinct) { + // Quotes in a registered key are data; quotes in the descriptor are CSS syntax. + const std::unordered_map registry = { + {"Example_LABEL", "plain.ttf"}, + {R"("Example_LABEL")", "literal-quotes.ttf"}, + {"sans-serif", "system"}, + }; + const char *plain = R"(40px "Example_LABEL")"; + const char *literalQuotes = R"(40px "\"Example_LABEL\"")"; + const auto plainFont = parseCanvasFont(plain); + const auto quotedFont = parseCanvasFont(literalQuotes); + EXPECT_EQ(plainFont.family, expectedFamily("Example_LABEL")); + EXPECT_EQ(quotedFont.family, expectedFamily(R"("Example_LABEL")")); +#if CC_PLATFORM == CC_PLATFORM_LINUX + EXPECT_EQ(registry.at(plainFont.family), "system"); + EXPECT_EQ(registry.at(quotedFont.family), "system"); +#else + EXPECT_EQ(registry.at(plainFont.family), "plain.ttf"); + EXPECT_EQ(registry.at(quotedFont.family), "literal-quotes.ttf"); +#endif +} + +TEST(CanvasFontCompatibilityTest, MigratedAliasesKeepLegacySizeAndStyles) { + const char *description = R"(italic bold 12.5px "\"My Font_LABEL\"")"; + const auto font = parseCanvasFont(description); + EXPECT_EQ(font.family, expectedFamily(R"("My Font_LABEL")")); +#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX + EXPECT_FLOAT_EQ(font.size, 12.5F); +#else + EXPECT_FLOAT_EQ(font.size, 12.F); +#endif + EXPECT_TRUE(font.bold); + EXPECT_TRUE(font.italic); +} + +TEST(CanvasFontCompatibilityTest, DoesNotDecodeLiteralQuotesTwice) { + const char *escaped = R"(40px "\"Example_LABEL\"")"; + const char *hexEscaped = R"(40px "\22 Example_LABEL\22 ")"; + const auto expected = expectedFamily(R"("Example_LABEL")"); + EXPECT_EQ(parseCanvasFont(escaped).family, expected); + EXPECT_EQ(parseCanvasFont(hexEscaped).family, expected); +} diff --git a/native/tests/unit-test/src/canvas_font_size_test.cpp b/native/tests/unit-test/src/canvas_font_size_test.cpp new file mode 100644 index 0000000000..a9f463d339 --- /dev/null +++ b/native/tests/unit-test/src/canvas_font_size_test.cpp @@ -0,0 +1,83 @@ +/* + Copyright (c) 2026 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "gtest/gtest.h" +#include "platform/interfaces/modules/canvas/CanvasFont.h" + +using cc::detail::parseCanvasFont; + +namespace { +const char *fallbackFamily() { +#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY || CC_PLATFORM == CC_PLATFORM_LINUX + return "sans-serif"; +#else + return "Arial"; +#endif +} +} // namespace + +TEST(CanvasFontSizeTest, KeepsTheRequestedSizeWhenAQuotedNameIsRejected) { + for (const char *input : {u8R"(48px "中文体")", R"(48px "Family3.0")", R"(48px "A, B")", R"(48px "A\a B")"}) { + SCOPED_TRACE(input); + const auto font = parseCanvasFont(input); + EXPECT_EQ(font.family, fallbackFamily()); + EXPECT_FLOAT_EQ(font.size, 48.F); + } +} + +TEST(CanvasFontSizeTest, KeepsPlatformSizeConversionAndFallbackStyles) { + const auto font = parseCanvasFont(u8R"(italic bold 48.5px "中文体")"); + EXPECT_EQ(font.family, fallbackFamily()); + EXPECT_TRUE(font.bold); + EXPECT_TRUE(font.italic); +#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX + EXPECT_FLOAT_EQ(font.size, 48.5F); +#else + EXPECT_FLOAT_EQ(font.size, 48.F); +#endif +} + +TEST(CanvasFontSizeTest, DoesNotRelaxMalformedDescriptions) { + for (const char *input : {u8R"(bad 48px "中文体")", "48px \"unterminated", u8R"(48px "中文体", Arial)"}) { + SCOPED_TRACE(input); + const auto font = parseCanvasFont(input); + EXPECT_EQ(font.family, fallbackFamily()); +#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX + EXPECT_FLOAT_EQ(font.size, 30.F); +#else + EXPECT_FLOAT_EQ(font.size, 48.F); +#endif + } +} + +TEST(CanvasFontSizeTest, RejectsUnsafeSizesOnTheRecoveredFallbackPath) { +#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX + for (const auto &number : {std::string("-1"), std::string(".5"), std::string("2147483648"), std::string(400, '9')}) { + SCOPED_TRACE(number); + const auto font = parseCanvasFont(number + u8R"(px "中文体")"); + EXPECT_EQ(font.family, fallbackFamily()); + EXPECT_FLOAT_EQ(font.size, 30.F); + } +#endif +} diff --git a/native/tests/unit-test/src/canvas_font_test.cpp b/native/tests/unit-test/src/canvas_font_test.cpp new file mode 100644 index 0000000000..c55e8cbfc3 --- /dev/null +++ b/native/tests/unit-test/src/canvas_font_test.cpp @@ -0,0 +1,127 @@ +/* + Copyright (c) 2026 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "gtest/gtest.h" +#include "platform/interfaces/modules/canvas/CanvasFont.h" + +using cc::detail::parseCanvasFont; + +namespace { +const char *fallbackFamily() { +#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY || CC_PLATFORM == CC_PLATFORM_LINUX + return "sans-serif"; +#else + return "Arial"; +#endif +} +} // namespace + +TEST(CanvasFontTest, RestoresPreviouslyRecognizedAssetAliases) { + const struct { + const char *description; + const char *alias; + } cases[] = { + {R"(40px "Example_LABEL")", "Example_LABEL"}, + {R"(40px "AlibabaPuHuiTi-3-105-Heavy_LABEL")", "AlibabaPuHuiTi-3-105-Heavy_LABEL"}, + {R"(40px "\"My Font_LABEL\"")", R"("My Font_LABEL")"}, + {R"(40px "Demo12px")", "Demo12px"}, + {R"(40px 'Example_LABEL')", "Example_LABEL"}, + }; + for (const auto &item : cases) { + SCOPED_TRACE(item.description); + const auto font = parseCanvasFont(item.description); +#if CC_PLATFORM == CC_PLATFORM_LINUX + EXPECT_EQ(font.family, "sans-serif"); +#else + EXPECT_EQ(font.family, item.alias); +#endif + EXPECT_FLOAT_EQ(font.size, 40.F); + } +} + +TEST(CanvasFontTest, DoesNotExpandNativeFontNameSupport) { + for (const char *input : {u8R"(48px "中文体")", R"(48px "Family3.0")", R"(48px "A, B")", + R"(48px "A\"B")", R"(48px "\\61")", R"(48px "\0 \d800 \110000 ")", + R"(48px "\"Family 3.0_LABEL\"")", R"(48px "A\a B")"}) { + SCOPED_TRACE(input); + EXPECT_EQ(parseCanvasFont(input).family, fallbackFamily()); + } +} + +TEST(CanvasFontTest, ChecksDecodedNamesUsingTheExistingPolicy) { + for (const char *input : {R"(40px "\52 egular")", R"(40px "\000052egular")", "40px \"Reg\\\r\nular\""}) { + SCOPED_TRACE(input); +#if CC_PLATFORM == CC_PLATFORM_LINUX + EXPECT_EQ(parseCanvasFont(input).family, "sans-serif"); +#else + EXPECT_EQ(parseCanvasFont(input).family, "Regular"); +#endif + } + EXPECT_EQ(parseCanvasFont(R"(40px "\4e2d \6587 ")").family, fallbackFamily()); +} + +TEST(CanvasFontTest, PreservesLegacyStyleAndFractionalSizeRules) { + const auto font = parseCanvasFont(R"(12.5px "BoldItalicOblique-small-caps_LABEL")"); +#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX + EXPECT_FLOAT_EQ(font.size, 12.5F); +#else + EXPECT_FLOAT_EQ(font.size, 12.F); +#endif + EXPECT_TRUE(font.bold); + EXPECT_TRUE(font.italic); +#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY + EXPECT_TRUE(font.oblique); + EXPECT_TRUE(font.smallCaps); +#else + EXPECT_FALSE(font.oblique); + EXPECT_FALSE(font.smallCaps); +#endif +} + +TEST(CanvasFontTest, KeepsListsAndMalformedQuotesOnTheLegacyPath) { + for (const char *input : {R"(48px "A, B", Arial)", R"(48px "A" extra)", "48px \"unterminated"}) { + SCOPED_TRACE(input); + const auto font = parseCanvasFont(input); + EXPECT_EQ(font.family, fallbackFamily()); +#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX + EXPECT_FLOAT_EQ(font.size, 30.F); +#else + EXPECT_FLOAT_EQ(font.size, 48.F); +#endif + } +} + +TEST(CanvasFontTest, LeavesUnquotedNamesAndExistingDefaultsUnchanged) { + const auto invalid = parseCanvasFont("bad description"); + EXPECT_EQ(invalid.family, fallbackFamily()); + EXPECT_FLOAT_EQ(invalid.size, 30.F); + const auto unquoted = parseCanvasFont("40px Times New Roman"); +#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX + EXPECT_EQ(unquoted.family, "Times"); +#elif CC_PLATFORM == CC_PLATFORM_LINUX + EXPECT_EQ(unquoted.family, "sans-serif"); +#else + EXPECT_EQ(unquoted.family, "Times New Roman"); +#endif +} diff --git a/scripts/test-declarations/font-family.test.ts b/scripts/test-declarations/font-family.test.ts new file mode 100644 index 0000000000..b3c1f103b8 --- /dev/null +++ b/scripts/test-declarations/font-family.test.ts @@ -0,0 +1,14 @@ +import { Label } from 'cc'; + +// Check the bundled type through a consumer, even when skipLibCheck is enabled. +export class FontFamilyDeclarationTest extends Label { + checkFontFamily (): void { + const style = this._textStyle!; + const serializedFamily = style.fontFamily; + const familyText: string = serializedFamily; + style.fontFamily = serializedFamily; + + // @ts-expect-error A plain string must not bypass the serialized family type. + style.fontFamily = familyText; + } +} diff --git a/scripts/test-declarations/test.d.ts b/scripts/test-declarations/test.d.ts index a325d87076..954e64c70b 100644 --- a/scripts/test-declarations/test.d.ts +++ b/scripts/test-declarations/test.d.ts @@ -1,2 +1,3 @@ /// -/// \ No newline at end of file +/// +import './font-family.test'; diff --git a/tests/asset-manager/mock-downloader.ts b/tests/asset-manager/mock-downloader.ts index ce9e261a63..e5475975ed 100644 --- a/tests/asset-manager/mock-downloader.ts +++ b/tests/asset-manager/mock-downloader.ts @@ -64,9 +64,6 @@ function getFontFamily (fontHandle: string): string { } else { fontFamilyName = `${fontHandle.substring(slashPos + 1, ttfIndex)}_LABEL`; } - if (fontFamilyName.indexOf(' ') !== -1) { - fontFamilyName = `"${fontFamilyName}"`; - } return fontFamilyName; } @@ -120,4 +117,4 @@ downloader.register({ '.ttc': loadFont, default: downloadText, -}); \ No newline at end of file +}); diff --git a/tests/ui/font-char-scale.test.ts b/tests/ui/font-char-scale.test.ts new file mode 100644 index 0000000000..f85cab55c7 --- /dev/null +++ b/tests/ui/font-char-scale.test.ts @@ -0,0 +1,43 @@ +import { buildFontDesc, quoteFontFamily } from '../../cocos/2d/utils/font-family'; +import { CanvasPool, LetterAtlas, shareLabelInfo } from '../../cocos/2d/assembler/label/font-utils'; + +test('the actual CHAR draw path scales the size, not a unit-like substring in the name', () => { + const measuredFonts: string[] = []; + const drawnFonts: string[] = []; + const context: Pick = { + font: '', + measureText: jest.fn(() => { + measuredFonts.push(context.font); + return { width: 20 } as TextMetrics; + }), + clearRect: jest.fn(), + fillRect: jest.fn(), + fillText: jest.fn(() => drawnFonts.push(context.font)), + }; + const canvas = document.createElement('canvas'); + const pool = CanvasPool.getInstance(); + const get = jest.spyOn(pool, 'get').mockReturnValue({ canvas, context: context as unknown as CanvasRenderingContext2D }); + const put = jest.spyOn(pool, 'put').mockImplementation(() => {}); + const family = quoteFontFamily('Demo12px'); + const info = { + ...shareLabelInfo, + fontFamily: family, + fontDesc: buildFontDesc(40, family), + fontSize: 40, + fontScale: 2, + hash: 'unit-in-font-name', + }; + const atlas = { + fontDefDictionary: { letterDefinitions: {} }, + insertLetterTexture: jest.fn(() => null), + } as unknown as LetterAtlas; + try { + LetterAtlas.prototype.getLetterDefinitionForChar.call(atlas, 'X', info); + expect(measuredFonts).toEqual(['40px "Demo12px"']); + expect(drawnFonts).toEqual(['80px "Demo12px"']); + expect(info.fontDesc).toBe('40px "Demo12px"'); + } finally { + get.mockRestore(); + put.mockRestore(); + } +}); diff --git a/tests/ui/font-family.test.ts b/tests/ui/font-family.test.ts new file mode 100644 index 0000000000..5feff34bef --- /dev/null +++ b/tests/ui/font-family.test.ts @@ -0,0 +1,122 @@ +import { buildFontDesc, CssFontFamily, getCanvasFontFamily, quoteFontFamily } from '../../cocos/2d/utils/font-family'; +import { TTFFont } from '../../cocos/2d/assets/ttf-font'; +import type { Label } from '../../cocos/2d/components/label'; +import { TTFUtils } from '../../cocos/2d/assembler/label/ttfUtils'; +import { LetterFont } from '../../cocos/2d/assembler/label/letter-font'; +import { EditBoxImpl } from '../../cocos/ui/editbox/edit-box-impl'; +import { Color } from '../../cocos/core/math/color'; + +describe('font family serialization', () => { + test.each([ + ['Alibaba PuHuiTi 3.0 105 Heavy', '"Alibaba PuHuiTi 3.0 105 Heavy"'], + ['Arial', '"Arial"'], + [' A B ', '" A B "'], + ['A, B', '"A, B"'], + ['A"B\\C', '"A\\"B\\\\C"'], + ['"Foo"', '"\\"Foo\\""'], + ['A\nb\r\t\x7f', '"A\\a b\\d \\9 \\7f "'], + ['A\0B', '"A\uFFFDB"'], + ['\ud800A\udc00', '"\uFFFDA\uFFFD"'], + ['中文\u{1f680}', '"中文\u{1f680}"'], + ])('serializes raw name %p using CSS string rules', (input, expected) => { + expect(quoteFontFamily(input)).toBe(expected); + }); + + test('preserves system expressions when font sources change', () => { + const source = { + useSystemFont: false, + fontFamily: 'Arial, sans-serif', + font: { _nativeAsset: 'Alibaba PuHuiTi 3.0 105 Heavy' }, + }; + expect(getCanvasFontFamily(source)).toBe('"Alibaba PuHuiTi 3.0 105 Heavy"'); + expect(getCanvasFontFamily(source)).toBe('"Alibaba PuHuiTi 3.0 105 Heavy"'); + expect(source.font._nativeAsset).toBe('Alibaba PuHuiTi 3.0 105 Heavy'); + + source.font._nativeAsset = 'sans-serif'; + expect(getCanvasFontFamily(source)).toBe('"sans-serif"'); + source.useSystemFont = true; + expect(getCanvasFontFamily(source)).toBe('Arial, sans-serif'); + source.fontFamily = 'sans-serif'; + expect(getCanvasFontFamily(source)).toBe('sans-serif'); + source.fontFamily = '"Times New Roman", serif'; + expect(getCanvasFontFamily(source)).toBe('"Times New Roman", serif'); + + source.useSystemFont = false; + source.font = { _nativeAsset: 'Replacement 2' }; + expect(getCanvasFontFamily(source)).toBe('"Replacement 2"'); + }); + + test('uses the existing Arial fallback when no usable family is available', () => { + expect(getCanvasFontFamily({ useSystemFont: true, fontFamily: '', font: null })).toBe('Arial'); + expect(getCanvasFontFamily({ useSystemFont: false, fontFamily: 'ignored', font: null })).toBe('"Arial"'); + expect(getCanvasFontFamily({ useSystemFont: false, fontFamily: '', font: { _nativeAsset: null } })).toBe('"Arial"'); + }); + + test('explicitly serializes legacy raw aliases without conflating literal quotes with CSS syntax', () => { + const rawAliases = ['Example_LABEL', '"Example_LABEL"', '"My Font_LABEL"']; + const descriptions = rawAliases.map((rawAlias) => { + const source = { useSystemFont: false, fontFamily: 'Arial', font: { _nativeAsset: rawAlias } }; + // A migrated manual caller uses the original registered alias, not its old ctx.font text. + const migrated = buildFontDesc(40, quoteFontFamily(rawAlias)); + expect(migrated).toBe(buildFontDesc(40, getCanvasFontFamily(source))); + expect(source.font._nativeAsset).toBe(rawAlias); + return migrated; + }); + expect(descriptions).toEqual([ + '40px "Example_LABEL"', + '40px "\\"Example_LABEL\\""', + '40px "\\"My Font_LABEL\\""', + ]); + }); + + test('size and style changes do not re-quote the family', () => { + const family = quoteFontFamily('Demo12px'); + expect(buildFontDesc(40, family)).toBe('40px "Demo12px"'); + expect(buildFontDesc(80, family, true, true)).toBe('italic bold 80px "Demo12px"'); + expect(buildFontDesc(12.5, family)).toBe('12.5px "Demo12px"'); + }); +}); + +describe('Label font consumers', () => { + class ExposedLetterFont extends LetterFont { + familyFor (label: Label): CssFontFamily { + return this._getFontFamily(label); + } + } + + test('TTF and CHAR resolve the same raw asset without modifying it', () => { + const font = new TTFFont(); + font._nativeAsset = 'Alibaba PuHuiTi 3.0 105 Heavy'; + const label = { font, useSystemFont: false, fontFamily: 'Arial' } as unknown as Label; + const ttf = new TTFUtils(); + const char = new ExposedLetterFont(); + expect(ttf._updateFontFamily(label)).toBe('"Alibaba PuHuiTi 3.0 105 Heavy"'); + expect(char.familyFor(label)).toBe(ttf._updateFontFamily(label)); + expect(font._nativeAsset).toBe('Alibaba PuHuiTi 3.0 105 Heavy'); + }); + + test('Web EditBox applies a custom family as CSS and preserves system lists', () => { + const font = new TTFFont(); + font._nativeAsset = 'Alibaba PuHuiTi 3.0 105 Heavy'; + const label = { + font, + useSystemFont: false, + fontFamily: 'Arial, sans-serif', + fontSize: 40, + node: { scale: { y: 1 } }, + color: Color.WHITE, + horizontalAlign: 0, + }; + const input = document.createElement('input'); + const impl = Object.create(EditBoxImpl.prototype) as { + _edTxt: HTMLInputElement; + _updateTextLabel(label: unknown): void; + }; + impl._edTxt = input; + impl._updateTextLabel(label); + expect(input.style.fontFamily).toBe('"Alibaba PuHuiTi 3.0 105 Heavy"'); + expect(font._nativeAsset).toBe('Alibaba PuHuiTi 3.0 105 Heavy'); + impl._updateTextLabel({ ...label, useSystemFont: true, font: null }); + expect(input.style.fontFamily).toBe('Arial, sans-serif'); + }); +}); diff --git a/tests/ui/font-loader-polling.test.ts b/tests/ui/font-loader-polling.test.ts new file mode 100644 index 0000000000..de2cc9540d --- /dev/null +++ b/tests/ui/font-loader-polling.test.ts @@ -0,0 +1,48 @@ +import { loadFont } from '../../cocos/2d/utils/font-loader'; + +test('Web polling observes freshly loaded font metrics', () => { + jest.useFakeTimers(); + const callback = jest.fn(); + const createElement = document.createElement.bind(document); + const nodes: HTMLElement[] = []; + let loaded = false; + const measuredFonts: string[] = []; + const context = { + font: '10px sans-serif', + measureText: jest.fn(() => { + measuredFonts.push(context.font); + return { width: loaded ? 200 : 100 }; + }), + }; + const canvas = createElement('canvas'); + const getContext = jest.spyOn(canvas, 'getContext').mockImplementation((() => context) as unknown as typeof canvas.getContext); + const create = jest.spyOn(document, 'createElement').mockImplementation(((tag: string) => { + if (tag === 'canvas') return canvas; + const element = createElement(tag); + nodes.push(element); + return element; + }) as typeof document.createElement); + + try { + loadFont('fonts/Web Family 3.0.ttf', {}, callback); + const style = nodes.find((node) => node.tagName === 'STYLE')!; + const preload = nodes.find((node) => node.tagName === 'DIV')!; + expect(style.textContent).toBe('@font-face { font-family:"Web Family 3.0_LABEL"; src:url("fonts/Web Family 3.0.ttf");}'); + expect(preload.style.fontFamily).toBe('"Web Family 3.0_LABEL"'); + expect(measuredFonts).toEqual(['40px "Web Family 3.0_LABEL"']); + expect(callback).not.toHaveBeenCalled(); + + // Measuring again must observe the loaded font, rather than reuse a cached fallback width. + loaded = true; + jest.advanceTimersByTime(100); + expect(measuredFonts).toEqual(['40px "Web Family 3.0_LABEL"', '40px "Web Family 3.0_LABEL"']); + expect(callback).toHaveBeenCalledTimes(1); + expect(callback).toHaveBeenCalledWith(null, 'Web Family 3.0_LABEL'); + expect(jest.getTimerCount()).toBe(0); + } finally { + create.mockRestore(); + getContext.mockRestore(); + nodes.forEach((node) => node.remove()); + jest.useRealTimers(); + } +}); diff --git a/tests/ui/font-loader.test.ts b/tests/ui/font-loader.test.ts new file mode 100644 index 0000000000..dac66e42f9 --- /dev/null +++ b/tests/ui/font-loader.test.ts @@ -0,0 +1,59 @@ +import { getFontFamily, loadFont } from '../../cocos/2d/utils/font-loader'; + +test.each([ + ['fonts/Alibaba PuHuiTi 3.0.ttf', 'Alibaba PuHuiTi 3.0_LABEL'], + ['fonts/Font3.0.ttf', 'Font3.0_LABEL'], + ['fonts/A,B.ttf', 'A,B_LABEL'], +])('Web loader returns a raw alias for %s', (url, expected) => { + expect(getFontFamily(url)).toBe(expected); +}); + +test('Web registration and FontFaceSet loading share one CSS family and return a raw alias', async () => { + jest.useFakeTimers(); + const faceDescriptor = Object.getOwnPropertyDescriptor(window, 'FontFace'); + const fontsDescriptor = Object.getOwnPropertyDescriptor(document, 'fonts'); + const load = jest.fn().mockResolvedValue([{}]); + Object.defineProperty(window, 'FontFace', { value: class {}, configurable: true }); + Object.defineProperty(document, 'fonts', { value: { load }, configurable: true }); + const callback = jest.fn(); + const createElement = document.createElement.bind(document); + const nodes: HTMLElement[] = []; + const canvas = createElement('canvas'); + const getContext = jest.spyOn(canvas, 'getContext').mockImplementation((() => ({})) as unknown as typeof canvas.getContext); + const create = jest.spyOn(document, 'createElement').mockImplementation(((tag: string) => { + if (tag === 'canvas') return canvas; + const element = createElement(tag); + nodes.push(element); + return element; + }) as typeof document.createElement); + + try { + await new Promise((resolve, reject) => { + loadFont('fonts/Web Family 3.0.ttf', {}, (error, family) => { + if (error) { + reject(error); + return; + } + callback(family); + resolve(); + }); + }); + const style = nodes.find((node) => node.tagName === 'STYLE')!; + const preload = nodes.find((node) => node.tagName === 'DIV')!; + expect(style.textContent).toBe('@font-face { font-family:"Web Family 3.0_LABEL"; src:url("fonts/Web Family 3.0.ttf");}'); + expect(preload.style.fontFamily).toBe('"Web Family 3.0_LABEL"'); + expect(load).toHaveBeenCalledWith('40px "Web Family 3.0_LABEL"'); + expect(callback).toHaveBeenCalledTimes(1); + expect(callback).toHaveBeenCalledWith('Web Family 3.0_LABEL'); + expect(jest.getTimerCount()).toBe(0); + } finally { + create.mockRestore(); + getContext.mockRestore(); + nodes.forEach((node) => node.remove()); + if (faceDescriptor) Object.defineProperty(window, 'FontFace', faceDescriptor); + else Reflect.deleteProperty(window, 'FontFace'); + if (fontsDescriptor) Object.defineProperty(document, 'fonts', fontsDescriptor); + else Reflect.deleteProperty(document, 'fonts'); + jest.useRealTimers(); + } +});