Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ZWSP word break & seperate Font caches #420

Merged
merged 4 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions examples/tests/text-zwsp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2024 Comcast Cable Communications Management, LLC.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { ExampleSettings } from '../common/ExampleSettings.js';

export async function automation(settings: ExampleSettings) {
const next = await test(settings);
await settings.snapshot();
while (await next()) {
await settings.snapshot();
}
}

/**
* This test is to ensure that both the canvas text renderer and the sdf text
* renderer correctly support zero-width space (ZWSP) for text line-breaking.
*
* Two text nodes are created with ZWSP inserted between words to test if the
* line breaks appropriately without visible gaps or extra spaces.
*
* Expected results: The two text nodes should break lines where ZWSP is inserted,
* without any extra spaces, gaps, or visible issues.
*
* Press the right arrow key to cycle through the different ZWSP test cases.
*
* @param param0
* @returns
*/
export default async function test({ renderer, testRoot }: ExampleSettings) {
const fontFamily = 'Ubuntu';
const fontSize = 40;
const yPos = 0;
testRoot.width = 500;
testRoot.height = 500;
testRoot.clipping = true;
testRoot.color = 0xffffffff;

const canvasText = renderer.createTextNode({
y: yPos,
width: testRoot.width,
fontSize,
fontFamily,
contain: 'width',
color: 0xff0000ff,
textRendererOverride: 'canvas',
parent: testRoot,
});

const sdfText = renderer.createTextNode({
y: yPos,
width: testRoot.width,
fontSize,
fontFamily,
contain: 'width',
color: 0x0000ff77,
parent: testRoot,
zIndex: 3,
});
const indexInfo = renderer.createTextNode({
x: testRoot.width,
y: testRoot.height,
mount: 1,
width: 0,
height: 0,
color: 0x000000ff,
fontFamily: 'Ubuntu',
fontSize: 20,
text: '1',
parent: testRoot,
});

let i = 0;
const ZWSP = '\u200B';
const mutations = [
() => {
canvasText.text =
sdfText.text = `This${ZWSP}is${ZWSP}a${ZWSP}test${ZWSP}with${ZWSP}ZWSP${ZWSP}between${ZWSP}words.`;
},
() => {
canvasText.text =
sdfText.text = `Testing${ZWSP}the${ZWSP}line${ZWSP}break${ZWSP}capability${ZWSP}with${ZWSP}multiple${ZWSP}words.`;
},
() => {
canvasText.text =
sdfText.text = `Short${ZWSP}text${ZWSP}with${ZWSP}ZWSP.`;
},
];

/**
* Run the next mutation in the list
*
* @param idx
* @returns `false` if loop is set to false and we've already gone through all mutations. Otherwise `true`.
*/
async function next(loop = false, idx = i + 1): Promise<boolean> {
if (idx > mutations.length - 1) {
if (!loop) {
return false;
}
idx = 0;
}
i = idx;
mutations[i]?.();
indexInfo.text = (i + 1).toString();
return true;
}
await next(false, 0);

window.addEventListener('keydown', (event) => {
// When right arrow is pressed, call next
if (event.key === 'ArrowRight') {
next(true).catch(console.error);
}
});

return next;
}
3 changes: 2 additions & 1 deletion src/core/text-rendering/TrFontManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,10 @@ export class TrFontManager {
public resolveFontFace(
familyMapsByPriority: FontFamilyMap[],
props: TrFontProps,
rendererType: 'canvas' | 'sdf',
): TrFontFace | undefined {
const { fontFamily, fontWeight, fontStyle, fontStretch } = props;
const fontCacheString = `${fontFamily}${fontStyle}${fontWeight}${fontStretch}`;
const fontCacheString = `${rendererType}_${fontFamily}_${fontStyle}_${fontWeight}_${fontStretch}`;

if (this.fontCache.has(fontCacheString) === true) {
return this.fontCache.get(fontCacheString);
Expand Down
1 change: 1 addition & 0 deletions src/core/text-rendering/renderers/CanvasTextRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ export class CanvasTextRenderer extends TextRenderer<CanvasTextRendererState> {
const trFontFace = this.stage.fontManager.resolveFontFace(
this.fontFamilyArray,
state.props,
'canvas',
) as WebTrFontFace | undefined;
assertTruthy(trFontFace, `Could not resolve font face for ${cssString}`);
state.fontInfo = {
Expand Down
42 changes: 28 additions & 14 deletions src/core/text-rendering/renderers/LightningTextTextureRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
import { assertTruthy } from '../../../utils.js';
import { getRgbaString, type RGBA } from '../../lib/utils.js';
import { calcDefaultLineHeight } from '../TextRenderingUtils.js';
import { getWebFontMetrics } from '../TextTextureRendererUtils.js';
import {
getWebFontMetrics,
isZeroWidthSpace,
} from '../TextTextureRendererUtils.js';
import type { NormalizedFontMetrics } from '../font-face-types/TrFontFace.js';
import type { WebTrFontFace } from '../font-face-types/WebTrFontFace.js';

Expand Down Expand Up @@ -682,38 +685,43 @@ export class LightningTextTextureRenderer {
letterSpacing: number,
indent = 0,
) {
// Greedy wrapping algorithm that will wrap words as the line grows longer.
// than its horizontal bounds.
const spaceRegex = / |\u200B/g; // ZWSP and spaces
const lines = text.split(/\r?\n/g);
let allLines: string[] = [];
const realNewlines = [];
const realNewlines: number[] = [];

for (let i = 0; i < lines.length; i++) {
const resultLines = [];
const resultLines: string[] = [];
let result = '';
let spaceLeft = wordWrapWidth - indent;
const words = lines[i]!.split(' ');

// Split the line into words, considering ZWSP
const words = lines[i]!.split(spaceRegex);
const spaces = lines[i]!.match(spaceRegex) || [];

for (let j = 0; j < words.length; j++) {
const wordWidth = this.measureText(words[j]!, letterSpacing);
const wordWidthWithSpace =
wordWidth + this.measureText(' ', letterSpacing);
const space = spaces[j - 1] || '';
const word = words[j]!;
const wordWidth = this.measureText(word, letterSpacing);
const wordWidthWithSpace = isZeroWidthSpace(space)
? wordWidth
: wordWidth + this.measureText(space, letterSpacing);

if (j === 0 || wordWidthWithSpace > spaceLeft) {
// Skip printing the newline if it's the first word of the line that is.
// greater than the word wrap width.
if (j > 0) {
resultLines.push(result);
result = '';
}
result += words[j];
result += word;
spaceLeft = wordWrapWidth - wordWidth - (j === 0 ? indent : 0);
} else {
spaceLeft -= wordWidthWithSpace;
result += ` ${words[j]!}`;
result += space + word;
}
}

resultLines.push(result);
result = '';

allLines = allLines.concat(resultLines);

if (i < lines.length - 1) {
Expand All @@ -728,7 +736,13 @@ export class LightningTextTextureRenderer {
if (!space) {
return this._context.measureText(word).width;
}

// Split word into characters, but skip ZWSP in the width calculation
return word.split('').reduce((acc, char) => {
// Check if the character is a zero-width space and skip it
if (isZeroWidthSpace(char)) {
return acc;
}
return acc + this._context.measureText(char).width + space;
}, 0);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -791,9 +791,11 @@ export class SdfTextRenderer extends TextRenderer<SdfTextRendererState> {
//#endregion Overrides

public resolveFontFace(props: TrFontProps): SdfTrFontFace | undefined {
return this.stage.fontManager.resolveFontFace(this.fontFamilyArray, props) as
| SdfTrFontFace
| undefined;
return this.stage.fontManager.resolveFontFace(
this.fontFamilyArray,
props,
'sdf',
) as SdfTrFontFace | undefined;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,11 @@ export function layoutText(

// If we encounter a word boundary (white space or newline) we invalidate
// the lastWord and set the xStartLastWordBoundary if we haven't already.
if (glyph.codepoint === 32 || glyph.codepoint === 10) {
if (
glyph.codepoint === 32 ||
glyph.codepoint === 10 ||
glyph.codepoint === 8203
) {
if (lastWord.codepointIndex !== -1) {
lastWord.codepointIndex = -1;
xStartLastWordBoundary = curX;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ export function measureText(
);
let width = 0;
for (const glyph of glyphs) {
if (glyph.mapped) {
if (glyph.mapped && glyph.codepoint !== 8203) {
// Skip ZWSP (\u200B)
width += glyph.xAdvance;
}
}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading