AtlatestRepositorysigil-ui

sigil-ui / tree / src / sigil / uitext.sgl

1;;; Monospace outline text with owned grayscale masks and bounded caching.
2;;; Explicit files provide the default faces and configured-family fallback.
3(define-library (sigil ui text)
4 (import (sigil struct) (sigil list) (sigil math) (sigil fs) (sigil string)
5 (sigil ui raster) (sigil font))
6 (export make-text-font text-font? text-font-close! text-font-family
7 text-font-source text-font-discovery-error
8 text-metrics measure-text draw-text! text-cache-stats)
9 (begin
10 (define-struct font-state
11 (regular) (bold) (fallbacks mutable: #t) (family) (source) (discovery-error)
12 (advance) (ascent) (descent) (height)
13 (byte-limit) (glyph-limit)
14 (cache mutable: #t)
15 (glyphs default: 0 mutable: #t)
16 (clock default: 0 mutable: #t)
17 (bytes default: 0 mutable: #t)
18 (hits default: 0 mutable: #t)
19 (misses default: 0 mutable: #t)
20 (closed? default: #f mutable: #t))
21 (define text-font? font-state?)
22 (define text-font-family font-state-family)
23 (define text-font-source font-state-source)
24 (define text-font-discovery-error font-state-discovery-error)
26 (define-struct cached-glyph
27 (face) (bold?) (size) (scale) (index) (mask) (bytes) (slot)
28 (used mutable: #t))
30 (define (check-font font)
31 (unless (and (text-font? font) (not (font-state-closed? font)))
32 (error "Expected an open text font")))
33 (define (check-size size)
34 (unless (and (real? size) (> size 0) (<= size 256))
35 (error "Text size must be positive and at most 256 logical pixels" size)))
36 (define (pixel value) (exact (round value)))
37 (define (up value) (exact (ceiling value)))
38 (define (down value) (exact (floor value)))
40 (define (open-face file)
41 (unless (string? file) (error "Text font path must be a string"))
42 (let ((bytes (file-size file)))
43 (cond
44 ((not bytes) (error (string-append "Text font file not found: " file)))
45 ((= bytes 0) (error (string-append "Text font file is empty: " file)))
46 ((> bytes 67108864)
47 (error (string-append "Text font file exceeds the byte limit: " file))))
48 (font-open-bytes (read-file-bytes file))))
50 ;; Attempt both releases even when one backend close raises.
51 (define (close-faces! regular bold (opts: (fallbacks '())))
52 (let close ((faces (append fallbacks (list bold regular))))
53 (unless (null? faces)
54 (dynamic-wind
55 (lambda () #f)
56 (lambda () (when (car faces) (font-face-close! (car faces))))
57 (lambda () (close (cdr faces)))))))
59 ;;; The owner must close the font after its display items are discarded.
60 ;;; An optional family needs real Regular and Bold faces; otherwise use files.
61 ;;; Explicit fallback files are opened once, in order, without discovery.
62 ;;; Their default collection face serves either weight without synthesis.
63 (define (make-text-font regular-path bold-path
64 (keys: (family #f) (fallback-files '()) (cache-bytes 4194304) (cache-glyphs 1024)))
65 (unless (and (exact-integer? cache-bytes) (> cache-bytes 0)
66 (exact-integer? cache-glyphs) (> cache-glyphs 0))
67 (error "Text cache limits must be positive exact integers"))
68 (unless (or (not family) (string? family))
69 (error "Text font family must be a nonempty string or #f"))
70 (unless (and (list? fallback-files) (<= (length fallback-files) 8)
71 (every string? fallback-files))
72 (error "Text fallback files must be a list of at most eight paths"))
73 (let total ((files fallback-files) (bytes 0) (seen '()))
74 (unless (null? files)
75 (when (member (car files) seen)
76 (error "Text fallback paths must be unique" (car files)))
77 (let ((size (file-size (car files))))
78 (unless (and size (> size 0) (<= (+ bytes size) 67108864))
79 (error "Text fallback files are missing, empty or exceed the 64-MiB input limit" (car files)))
80 (total (cdr files) (+ bytes size) (cons (car files) seen)))))
81 (let ((preferred (and family (string-trim family)))
82 (regular #f) (bold #f) (fallbacks '()) (source 'files) (discovery-error #f))
83 (when (and preferred (string=? preferred ""))
84 (error "Text font family must be a nonempty string or #f"))
85 (guard (failure
86 (#t (guard (cleanup (#t #f)) (close-faces! regular bold fallbacks))
87 (raise failure)))
88 (when preferred
89 (guard (failure (#t (set! discovery-error failure)))
90 (set! regular (font-open-family preferred))
91 (when regular
92 (set! bold (font-open-family preferred style: "Bold")))))
93 (if (and regular bold)
94 (set! source 'family)
95 (begin
96 (guard (cleanup
97 (#t (unless discovery-error (set! discovery-error cleanup))))
98 (close-faces! regular bold))
99 (set! regular #f)
100 (set! bold #f)
101 ;; File loading is outside the optional discovery guard.
102 (set! regular (open-face regular-path))
103 (set! bold (open-face bold-path))))
104 (for-each (lambda (file)
105 (set! fallbacks (append fallbacks (list (open-face file))))) fallback-files)
106 (let* ((a (font-face-em-metrics regular))
107 (b (font-face-em-metrics bold))
108 (extra (map font-face-em-metrics fallbacks))
109 (advance (max (dict-ref a advance:) (dict-ref b advance:)))
110 (ascent (apply max (append (list (dict-ref a ascent:) (dict-ref b ascent:))
111 (map (lambda (m) (dict-ref m ascent:)) extra))))
112 (descent (apply max (append (list 0 (dict-ref a descent:) (dict-ref b descent:))
113 (map (lambda (m) (dict-ref m descent:)) extra))))
114 (height (apply max (append
115 (list (dict-ref a line-height:) (dict-ref b line-height:) (+ ascent descent))
116 (map (lambda (m) (dict-ref m line-height:)) extra)))))
117 (unless (and (> advance 0) (> ascent 0) (> height 0))
118 (error "Text font has invalid layout metrics"))
119 (font-state regular: regular bold: bold fallbacks: fallbacks
120 family: (font-face-family regular)
121 source: source discovery-error: discovery-error
122 advance: advance ascent: ascent descent: descent height: height
123 byte-limit: cache-bytes glyph-limit: cache-glyphs
124 cache: (make-vector 1024 '()))))))
126 (define (text-font-close! font)
127 (unless (text-font? font) (error "Expected a text font"))
128 (unless (font-state-closed? font)
129 (set-font-state-closed?! font #t)
130 (set-font-state-cache! font #f)
131 (set-font-state-glyphs! font 0)
132 (set-font-state-bytes! font 0)
133 (let ((fallbacks (font-state-fallbacks font)))
134 (set-font-state-fallbacks! font '())
135 (close-faces! (font-state-regular font) (font-state-bold font) fallbacks))))
137 ;;; Primary cell advance and shared line metrics. Fallbacks can use
138 ;;; multiple whole cells; shaping and grapheme clustering are not provided.
139 (define (text-metrics font size)
140 (check-font font)
141 (check-size size)
142 (let ((ascent (up (* size (font-state-ascent font))))
143 (descent (up (* size (font-state-descent font)))))
144 ;; Preserve the font's pen advance until each device-pixel origin is
145 ;; rounded in draw-text!. Logical rounding compounds at higher scales.
146 (dict advance: (* size (font-state-advance font))
147 ascent: ascent descent: descent
148 height: (max (+ ascent descent) (up (* size (font-state-height font)))))))
150 (define (measure-text font text size (keys: (bold? #f)))
151 (unless (string? text) (error "Expected a text string"))
152 (unless (boolean? bold?) (error "Text weight must be boolean"))
153 (let ((advance (dict-ref (text-metrics font size) advance:))
154 (primary (if bold? (font-state-bold font) (font-state-regular font))))
155 (if (null? (font-state-fallbacks font))
156 (* (string-length text) advance)
157 (let loop ((characters (string->list text)) (columns 0))
158 (if (null? characters) (* columns advance)
159 (loop (cdr characters)
160 (+ columns (caddr (select-glyph font primary bold? (char->integer (car characters)))))))))))
162 (define (next-use! font)
163 (let ((next (+ 1 (font-state-clock font))))
164 (set-font-state-clock! font next)
165 next))
167 ;; Hash public inputs without allocating a composite key for every glyph.
168 ;; Exact input comparisons in the bucket also distinguish fractional sizes.
169 (define (cache-base bold? size scale)
170 (+ (if bold? 13 0) (* 131 scale) (* 17 (down (* size 64)))))
172 (define (cached font slot face bold? size scale index)
173 (let find ((entries (vector-ref (font-state-cache font) slot)))
174 (and (pair? entries)
175 (let ((entry (car entries)))
176 (if (and (eq? face (cached-glyph-face entry))
177 (eq? bold? (cached-glyph-bold? entry))
178 (= size (cached-glyph-size entry))
179 (= scale (cached-glyph-scale entry))
180 (= index (cached-glyph-index entry)))
181 entry
182 (find (cdr entries)))))))
184 ;; Only a bounded insertion that needs room scans the cache for its oldest
185 ;; entry. Hits update a use stamp; they never reconstruct the cache list.
186 (define (evict-oldest! font)
187 (let ((oldest #f) (buckets (font-state-cache font)))
188 (do ((slot 0 (+ slot 1))) ((= slot (vector-length buckets)))
189 (for-each
190 (lambda (entry)
191 (when (or (not oldest)
192 (< (cached-glyph-used entry) (cached-glyph-used oldest)))
193 (set! oldest entry)))
194 (vector-ref buckets slot)))
195 (when oldest
196 (let ((slot (cached-glyph-slot oldest)))
197 (vector-set! buckets slot
198 (filter (lambda (entry) (not (eq? entry oldest))) (vector-ref buckets slot))))
199 (set-font-state-bytes! font (- (font-state-bytes font) (cached-glyph-bytes oldest)))
200 (set-font-state-glyphs! font (- (font-state-glyphs font) 1)))))
202 (define (remember! font slot face bold? size scale index glyph)
203 (let ((bytes (bytevector-length (dict-ref glyph coverage:))))
204 (when (<= bytes (font-state-byte-limit font))
205 (let trim ()
206 (when (or (> (+ bytes (font-state-bytes font)) (font-state-byte-limit font))
207 (>= (font-state-glyphs font) (font-state-glyph-limit font)))
208 (evict-oldest! font)
209 (trim)))
210 (let* ((buckets (font-state-cache font))
211 (entry (cached-glyph face: face bold?: bold? size: size scale: scale index: index
212 mask: glyph bytes: bytes slot: slot used: (next-use! font))))
213 (vector-set! buckets slot (cons entry (vector-ref buckets slot)))
214 (set-font-state-bytes! font (+ bytes (font-state-bytes font)))
215 (set-font-state-glyphs! font (+ 1 (font-state-glyphs font)))))))
217 (define (glyph-mask font face bold? size scale glyph-index base)
218 (let* ((slot (modulo (+ base glyph-index) 1024))
219 (found (cached font slot face bold? size scale glyph-index)))
220 (if found
221 (begin
222 (set-font-state-hits! font (+ 1 (font-state-hits font)))
223 (set-cached-glyph-used! found (next-use! font))
224 (cached-glyph-mask found))
225 (begin
226 (set-font-state-misses! font (+ 1 (font-state-misses font)))
227 (font-face-set-size! face size scale: scale)
228 (let ((glyph (font-rasterize-glyph face glyph-index)))
229 (remember! font slot face bold? size scale glyph-index glyph)
230 glyph)))))
232 ;; Glyph IDs are face-local. A fallback's unhinted advance at one device
233 ;; em gives its em advance without scale-dependent rounding. These small
234 ;; metric rasters share the same bounded cache as drawing masks.
235 (define (select-glyph font primary bold? codepoint)
236 (let ((index (font-glyph-index primary codepoint)))
237 (if (> index 0)
238 (list primary index 1)
239 (let ((found (font-find-glyph (font-state-fallbacks font) codepoint)))
240 (if (not found)
241 (list #f 0 1)
242 (let* ((face (dict-ref found face:))
243 (index (dict-ref found index:))
244 (metrics (glyph-mask font face bold? 1 1 index (cache-base bold? 1 1)))
245 (columns (max 1 (up (/ (dict-ref metrics advance:) (font-state-advance font))))))
246 (list face index columns)))))))
248 (define (text-cache-stats font)
249 (unless (text-font? font) (error "Expected a text font"))
250 (dict glyphs: (font-state-glyphs font) bytes: (font-state-bytes font)
251 hits: (font-state-hits font) misses: (font-state-misses font)
252 byte-limit: (font-state-byte-limit font) glyph-limit: (font-state-glyph-limit font)))
254 ;; Device-pixel clip for the measured run, intersected with optional damage.
255 (define (run-clip x y width height scale clip)
256 (let ((bounds (list (down (* x scale)) (down (* y scale))
257 (up (* (+ x width) scale)) (up (* (+ y height) scale)))))
258 (if clip
259 (begin
260 (unless (and (list? clip) (= 4 (length clip))
261 (every exact-integer? clip))
262 (error "Text clip must contain four device-pixel integers" clip))
263 (list (max (car bounds) (car clip)) (max (cadr bounds) (cadr clip))
264 (min (caddr bounds) (caddr clip)) (min (cadddr bounds) (cadddr clip))))
265 bounds)))
267 (define (replacement-box! canvas x baseline advance size scale color clip)
268 (let* ((margin (if (<= advance (* 3 scale)) 0 scale))
269 (left (+ x margin))
270 (top (- baseline (max 1 (pixel (* size scale 0.75)))))
271 (width (max 1 (- (pixel advance) (* 2 margin))))
272 (height (max 1 (pixel (* size scale 0.75))))
273 (stroke (min scale width height)))
274 (canvas-fill! canvas left top width stroke color clip)
275 (canvas-fill! canvas left (+ top (- height stroke)) width stroke color clip)
276 (canvas-fill! canvas left top stroke height color clip)
277 (canvas-fill! canvas (+ left (- width stroke)) top stroke height color clip)))
279 ;;; Draw UTF-8 text on the primary cell grid. Wider fallback glyphs use
280 ;;; whole cells. x/y are logical pixels,
281 ;;; y is its top, and clip (when supplied) is a device-pixel x0/y0/x1/y1.
282 ;;; Missing glyphs draw visible boxes. Coverage is grayscale, never LCD.
283 (define (draw-text! font canvas x y text size color
284 (keys: (scale 1) (bold? #f) (clip #f)))
285 (check-font font)
286 (check-size size)
287 (unless (and (string? text) (real? x) (real? y)
288 (< (abs x) 1000000000) (< (abs y) 1000000000)
289 (boolean? bold?) (exact-integer? scale) (<= 1 scale 8))
290 (error "Invalid text position, string, weight or scale"))
291 (let* ((metrics (text-metrics font size))
292 (advance (dict-ref metrics advance:))
293 (width (measure-text font text size bold?: bold?))
294 (height (dict-ref metrics height:))
295 (bounds (run-clip x y width height scale clip))
296 (baseline (pixel (* (+ y (dict-ref metrics ascent:)) scale)))
297 (base (cache-base bold? size scale))
298 (face (if bold? (font-state-bold font) (font-state-regular font))))
299 (when (and (< (car bounds) (caddr bounds)) (< (cadr bounds) (cadddr bounds)))
300 (let loop ((characters (string->list text)) (index 0))
301 (unless (null? characters)
302 (let* ((codepoint (char->integer (car characters)))
303 (selected (select-glyph font face bold? codepoint))
304 (selected-face (car selected))
305 (glyph-index (cadr selected))
306 (left (pixel (* (+ x (* index advance)) scale))))
307 (if (= glyph-index 0)
308 (replacement-box! canvas left baseline (* advance scale) size scale color bounds)
309 (let ((glyph (glyph-mask font selected-face bold? size scale glyph-index base)))
310 (when (and (> (dict-ref glyph width:) 0) (> (dict-ref glyph height:) 0))
311 (canvas-mask! canvas (+ left (dict-ref glyph left:))
312 (- baseline (dict-ref glyph top:))
313 (dict-ref glyph coverage:) (dict-ref glyph width:) color bounds))))
314 (loop (cdr characters) (+ index (caddr selected)))))))
315 width))))