@@ -11,7 +11,7 @@ const OP_DRAW_TEXT = 7;
1111const OP_RETAINED_BEGIN = 8 ;
1212const OP_RETAINED_END = 9 ;
1313
14- export function play ( ck , buffer , canvas , typeface ) {
14+ export function play ( ck , buffer , canvas , ... typefaces ) {
1515 const view = new DataView ( buffer ) ;
1616 let offset = 0 ;
1717
@@ -89,28 +89,55 @@ export function play(ck, buffer, canvas, typeface) {
8989 const x = readFloat ( ) ;
9090 const y = readFloat ( ) ;
9191 const fontSize = readFloat ( ) ;
92- readInt32 ( ) ; // fontWeight (unused)
92+ const fontWeight = readInt32 ( ) ; // fontWeight
9393 const color = readUint32 ( ) ;
9494 const boundsWidth = readFloat ( ) ;
9595 // fontFamily (4-byte length + UTF-8 bytes, length 0 = nil)
9696 const familyLen = readInt32 ( ) ;
97+ let fontFamily = null ;
9798 if ( familyLen > 0 ) {
99+ const familyBytes = new Uint8Array ( buffer , offset , familyLen ) ;
98100 offset += familyLen ;
101+ fontFamily = new TextDecoder ( ) . decode ( familyBytes ) ;
99102 }
100- readInt32 ( ) ; // lineLimit
103+ const lineLimit = readInt32 ( ) ;
101104 readInt32 ( ) ; // lineBreakMode
102- setColor ( color ) ;
105+
106+ // Font fallback management:
107+ const fontProvider = ck . TypefaceFontProvider . Make ( ) ;
108+ for ( const tf of typefaces ) {
109+ fontProvider . registerTypeface ( tf , "" ) ; // Registering with empty string allows them to be used as fallbacks
110+ }
111+
112+ const style = new ck . ParagraphStyle ( {
113+ textStyle : {
114+ color : ck . Color4f (
115+ ( ( color >> 16 ) & 0xFF ) / 255 ,
116+ ( ( color >> 8 ) & 0xFF ) / 255 ,
117+ ( color & 0xFF ) / 255 ,
118+ ( ( color >>> 24 ) & 0xFF ) / 255
119+ ) ,
120+ fontSize : fontSize ,
121+ fontFamilies : fontFamily ? [ fontFamily , 'sans-serif' ] : [ 'sans-serif' ] ,
122+ } ,
123+ maxLines : lineLimit > 0 ? lineLimit : undefined ,
124+ ellipsis : lineLimit > 0 ? '...' : undefined ,
125+ } ) ;
126+
127+ const builder = ck . ParagraphBuilder . MakeFromFontProvider ( style , fontProvider ) ;
128+ builder . addText ( text ) ;
129+ const paragraph = builder . build ( ) ;
130+ paragraph . layout ( boundsWidth > 0 ? boundsWidth : 100000 ) ;
103131
104- const font = new ck . Font ( typeface , fontSize ) ;
105132 let drawX = x ;
106133 if ( boundsWidth > 0 ) {
107- const ids = font . getGlyphIDs ( text ) ;
108- const widths = font . getGlyphWidths ( ids ) ;
109- const actualWidth = widths . reduce ( ( sum , w ) => sum + w , 0 ) ;
110- drawX = ( boundsWidth - actualWidth ) / 2 ;
134+ drawX = ( boundsWidth - paragraph . getMaxIntrinsicWidth ( ) ) / 2 ;
111135 }
112- canvas . drawText ( text , drawX , y , paint , font ) ;
113- font . delete ( ) ;
136+ canvas . drawParagraph ( paragraph , drawX , y ) ;
137+
138+ paragraph . delete ( ) ;
139+ builder . delete ( ) ;
140+ fontProvider . delete ( ) ;
114141 break ;
115142 }
116143 case OP_RETAINED_BEGIN :
0 commit comments