-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
rasterizer.rs
1978 lines (1744 loc) · 68.8 KB
/
rasterizer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use api::{FontInstanceData, FontInstanceFlags, FontInstanceKey};
use api::{FontInstanceOptions, FontInstancePlatformOptions};
use api::{FontKey, FontRenderMode, FontSize, FontTemplate, FontVariation};
use api::{ColorU, GlyphIndex, GlyphDimensions, SyntheticItalics};
use api::{IdNamespace, BlobImageResources};
use api::channel::crossbeam::{unbounded, Receiver, Sender};
use api::units::*;
use api::ImageFormat;
use crate::platform::font::FontContext;
use crate::profiler::GlyphRasterizeProfiler;
use crate::types::{FastHashMap, FastHashSet};
use crate::telemetry::Telemetry;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use rayon::ThreadPool;
use rayon::prelude::*;
use euclid::approxeq::ApproxEq;
use smallvec::SmallVec;
use std::cmp;
use std::cell::Cell;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops::Deref;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak};
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::sync::atomic::{AtomicBool, Ordering};
pub static GLYPH_FLASHING: AtomicBool = AtomicBool::new(false);
const GLYPH_BATCH_SIZE: usize = 32;
impl FontContexts {
/// Get access to the font context associated to the current thread.
pub fn lock_current_context(&self) -> MutexGuard<FontContext> {
match self.current_worker_id() {
Some(id) => self.lock_context(id),
None => self.lock_any_context(),
}
}
pub(in super) fn current_worker_id(&self) -> Option<usize> {
self.workers.current_thread_index()
}
}
thread_local! {
pub static SEED: Cell<u32> = Cell::new(0);
}
// super simple random to avoid dependency on rand
fn random() -> u32 {
SEED.with(|seed| {
seed.set(seed.get().wrapping_mul(22695477).wrapping_add(1));
seed.get()
})
}
impl GlyphRasterizer {
pub fn request_glyphs<F>(
&mut self,
font: FontInstance,
glyph_keys: &[GlyphKey],
mut handle: F,
)
where F: FnMut(&GlyphKey) -> bool
{
assert!(self.has_font(font.font_key));
let mut batch_size = 0;
// select glyphs that have not been requested yet.
for key in glyph_keys {
if !handle(key) {
continue;
}
// Increment the total number of glyphs that are pending. This is used to determine
// later whether to use worker threads for the remaining glyphs during resolve time.
self.pending_glyph_count += 1;
self.glyph_request_count += 1;
// Find a batch container for the font instance for this glyph. Use get_mut to avoid
// cloning the font instance, since this is the common path.
match self.pending_glyph_requests.get_mut(&font) {
Some(container) => {
container.push(*key);
batch_size = container.len();
}
None => {
// If no batch exists for this font instance, add the glyph to a new one.
self.pending_glyph_requests.insert(
font.clone(),
smallvec![*key],
);
}
}
}
// If the batch for this font instance is big enough, kick off an async
// job to start rasterizing these glyphs on other threads now.
if batch_size >= GLYPH_BATCH_SIZE {
let container = self.pending_glyph_requests.get_mut(&font).unwrap();
let glyphs = mem::replace(container, SmallVec::new());
self.flush_glyph_requests(font, glyphs, true);
}
}
pub fn enable_multithreading(&mut self, enable: bool) {
self.enable_multithreading = enable;
}
/// Internal method to flush a list of glyph requests to a set of worker threads,
/// or process on this thread if there isn't much work to do (in which case the
/// overhead of processing these on a thread is unlikely to be a performance win).
fn flush_glyph_requests(
&mut self,
font: FontInstance,
glyphs: SmallVec<[GlyphKey; 16]>,
use_workers: bool,
) {
let font = Arc::new(font);
let font_contexts = Arc::clone(&self.font_contexts);
self.pending_glyph_jobs += glyphs.len();
self.pending_glyph_count -= glyphs.len();
let can_use_r8_format = self.can_use_r8_format;
// if the number of glyphs is small, do it inline to avoid the threading overhead;
// send the result into glyph_tx so downstream code can't tell the difference.
if let Some(thread) = &self.dedicated_thread {
let tx = self.glyph_tx.clone();
let _ = thread.tx.send(GlyphRasterMsg::Rasterize { font, glyphs, can_use_r8_format, tx });
} else if self.enable_multithreading && use_workers {
// spawn an async task to get off of the render backend thread as early as
// possible and in that task use rayon's fork join dispatch to rasterize the
// glyphs in the thread pool.
profile_scope!("spawning process_glyph jobs");
let tx = self.glyph_tx.clone();
self.workers.spawn(move || {
FontContext::begin_rasterize(&font);
// If the FontContext supports distributing a font across multiple threads,
// then use par_iter so different glyphs of the same font are processed on
// multiple threads.
if FontContext::distribute_across_threads() {
glyphs.par_iter().for_each(|key| {
let mut context = font_contexts.lock_current_context();
let job_font = font.clone();
let job = process_glyph(&mut context, can_use_r8_format, job_font, *key);
tx.send(job).unwrap();
});
} else {
// For FontContexts that prefer to localize a font to a single thread,
// just process all the glyphs on the same worker to avoid contention.
for key in glyphs {
let mut context = font_contexts.lock_current_context();
let job_font = font.clone();
let job = process_glyph(&mut context, can_use_r8_format, job_font, key);
tx.send(job).unwrap();
}
}
FontContext::end_rasterize(&font);
});
} else {
FontContext::begin_rasterize(&font);
for key in glyphs {
let mut context = font_contexts.lock_current_context();
let job_font = font.clone();
let job = process_glyph(&mut context, can_use_r8_format, job_font, key);
self.glyph_tx.send(job).unwrap();
}
FontContext::end_rasterize(&font);
}
}
pub fn resolve_glyphs<F, G>(
&mut self,
mut handle: F,
profile: &mut G,
)
where
F: FnMut(GlyphRasterJob, bool),
G: GlyphRasterizeProfiler,
{
profile.start_time();
let timer_id = Telemetry::start_rasterize_glyphs_time();
// Work around the borrow checker, since we call flush_glyph_requests below
let mut pending_glyph_requests = mem::replace(
&mut self.pending_glyph_requests,
FastHashMap::default(),
);
// If we have a large amount of remaining work to do, spawn to worker threads,
// even if that work is shared among a number of different font instances.
let use_workers = self.pending_glyph_count >= 8;
for (font, pending_glyphs) in pending_glyph_requests.drain() {
self.flush_glyph_requests(
font,
pending_glyphs,
use_workers,
);
}
// Restore this so that we don't heap allocate next frame
self.pending_glyph_requests = pending_glyph_requests;
debug_assert_eq!(self.pending_glyph_count, 0);
debug_assert!(self.pending_glyph_requests.is_empty());
if self.glyph_request_count > 0 {
profile.set(self.glyph_request_count as f64);
self.glyph_request_count = 0;
}
profile_scope!("resolve_glyphs");
// TODO: rather than blocking until all pending glyphs are available
// we could try_recv and steal work from the thread pool to take advantage
// of the fact that this thread is alive and we avoid the added latency
// of blocking it.
let mut jobs = {
profile_scope!("blocking wait on glyph_rx");
self.glyph_rx.iter().take(self.pending_glyph_jobs).collect::<Vec<_>>()
};
assert_eq!(jobs.len(), self.pending_glyph_jobs, "BUG: Didn't receive all pending glyphs!");
self.pending_glyph_jobs = 0;
// Ensure that the glyphs are always processed in the same
// order for a given text run (since iterating a hash set doesn't
// guarantee order). This can show up as very small float inaccuracy
// differences in rasterizers due to the different coordinates
// that text runs get associated with by the texture cache allocator.
jobs.sort_by(|a, b| (*a.font).cmp(&*b.font).then(a.key.cmp(&b.key)));
for job in jobs {
handle(job, self.can_use_r8_format);
}
// Now that we are done with the critical path (rendering the glyphs),
// we can schedule removing the fonts if needed.
self.remove_dead_fonts();
Telemetry::stop_and_accumulate_rasterize_glyphs_time(timer_id);
profile.end_time();
}
}
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct FontTransform {
pub scale_x: f32,
pub skew_x: f32,
pub skew_y: f32,
pub scale_y: f32,
}
// Floats don't impl Hash/Eq/Ord...
impl Eq for FontTransform {}
impl Ord for FontTransform {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.partial_cmp(other).unwrap_or(cmp::Ordering::Equal)
}
}
impl Hash for FontTransform {
fn hash<H: Hasher>(&self, state: &mut H) {
// Note: this is inconsistent with the Eq impl for -0.0 (don't care).
self.scale_x.to_bits().hash(state);
self.skew_x.to_bits().hash(state);
self.skew_y.to_bits().hash(state);
self.scale_y.to_bits().hash(state);
}
}
impl FontTransform {
const QUANTIZE_SCALE: f32 = 1024.0;
pub fn new(scale_x: f32, skew_x: f32, skew_y: f32, scale_y: f32) -> Self {
FontTransform { scale_x, skew_x, skew_y, scale_y }
}
pub fn identity() -> Self {
FontTransform::new(1.0, 0.0, 0.0, 1.0)
}
#[allow(dead_code)]
pub fn is_identity(&self) -> bool {
*self == FontTransform::identity()
}
pub fn quantize(&self) -> Self {
FontTransform::new(
(self.scale_x * Self::QUANTIZE_SCALE).round() / Self::QUANTIZE_SCALE,
(self.skew_x * Self::QUANTIZE_SCALE).round() / Self::QUANTIZE_SCALE,
(self.skew_y * Self::QUANTIZE_SCALE).round() / Self::QUANTIZE_SCALE,
(self.scale_y * Self::QUANTIZE_SCALE).round() / Self::QUANTIZE_SCALE,
)
}
#[allow(dead_code)]
pub fn determinant(&self) -> f64 {
self.scale_x as f64 * self.scale_y as f64 - self.skew_y as f64 * self.skew_x as f64
}
#[allow(dead_code)]
pub fn compute_scale(&self) -> Option<(f64, f64)> {
let det = self.determinant();
if det != 0.0 {
let x_scale = (self.scale_x as f64).hypot(self.skew_y as f64);
let y_scale = det.abs() / x_scale;
Some((x_scale, y_scale))
} else {
None
}
}
#[allow(dead_code)]
pub fn pre_scale(&self, scale_x: f32, scale_y: f32) -> Self {
FontTransform::new(
self.scale_x * scale_x,
self.skew_x * scale_y,
self.skew_y * scale_x,
self.scale_y * scale_y,
)
}
#[allow(dead_code)]
pub fn scale(&self, scale: f32) -> Self { self.pre_scale(scale, scale) }
#[allow(dead_code)]
pub fn invert_scale(&self, x_scale: f64, y_scale: f64) -> Self {
self.pre_scale(x_scale.recip() as f32, y_scale.recip() as f32)
}
pub fn synthesize_italics(&self, angle: SyntheticItalics, size: f64, vertical: bool) -> (Self, (f64, f64)) {
let skew_factor = angle.to_skew();
if vertical {
// origin delta to be applied so that we effectively skew around
// the middle rather than edge of the glyph
let (tx, ty) = (0.0, -size * 0.5 * skew_factor as f64);
(FontTransform::new(
self.scale_x + self.skew_x * skew_factor,
self.skew_x,
self.skew_y + self.scale_y * skew_factor,
self.scale_y,
), (self.scale_x as f64 * tx + self.skew_x as f64 * ty,
self.skew_y as f64 * tx + self.scale_y as f64 * ty))
} else {
(FontTransform::new(
self.scale_x,
self.skew_x - self.scale_x * skew_factor,
self.skew_y,
self.scale_y - self.skew_y * skew_factor,
), (0.0, 0.0))
}
}
pub fn swap_xy(&self) -> Self {
FontTransform::new(self.skew_x, self.scale_x, self.scale_y, self.skew_y)
}
pub fn flip_x(&self) -> Self {
FontTransform::new(-self.scale_x, self.skew_x, -self.skew_y, self.scale_y)
}
pub fn flip_y(&self) -> Self {
FontTransform::new(self.scale_x, -self.skew_x, self.skew_y, -self.scale_y)
}
pub fn transform(&self, point: &LayoutPoint) -> DevicePoint {
DevicePoint::new(
self.scale_x * point.x + self.skew_x * point.y,
self.skew_y * point.x + self.scale_y * point.y,
)
}
pub fn get_subpx_dir(&self) -> SubpixelDirection {
if self.skew_y.approx_eq(&0.0) {
// The X axis is not projected onto the Y axis
SubpixelDirection::Horizontal
} else if self.scale_x.approx_eq(&0.0) {
// The X axis has been swapped with the Y axis
SubpixelDirection::Vertical
} else {
// Use subpixel precision on all axes
SubpixelDirection::Mixed
}
}
}
impl<'a> From<&'a LayoutToWorldTransform> for FontTransform {
fn from(xform: &'a LayoutToWorldTransform) -> Self {
FontTransform::new(xform.m11, xform.m21, xform.m12, xform.m22)
}
}
// Some platforms (i.e. Windows) may have trouble rasterizing glyphs above this size.
// Ensure glyph sizes are reasonably limited to avoid that scenario.
pub const FONT_SIZE_LIMIT: f32 = 320.0;
/// Immutable description of a font instance's shared state.
///
/// `BaseFontInstance` can be identified by a `FontInstanceKey` to avoid hashing it.
#[derive(Clone, Debug, Ord, PartialOrd, MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct BaseFontInstance {
///
pub instance_key: FontInstanceKey,
///
pub font_key: FontKey,
///
pub size: FontSize,
///
pub options: FontInstanceOptions,
///
#[cfg_attr(any(feature = "capture", feature = "replay"), serde(skip))]
pub platform_options: Option<FontInstancePlatformOptions>,
///
pub variations: Vec<FontVariation>,
}
impl BaseFontInstance {
pub fn new(
instance_key: FontInstanceKey,
font_key: FontKey,
size: f32,
options: Option<FontInstanceOptions>,
platform_options: Option<FontInstancePlatformOptions>,
variations: Vec<FontVariation>,
) -> Self {
BaseFontInstance {
instance_key,
font_key,
size: size.into(),
options: options.unwrap_or_default(),
platform_options,
variations,
}
}
}
impl Deref for BaseFontInstance {
type Target = FontInstanceOptions;
fn deref(&self) -> &FontInstanceOptions {
&self.options
}
}
impl Hash for BaseFontInstance {
fn hash<H: Hasher>(&self, state: &mut H) {
// Skip the instance key.
self.font_key.hash(state);
self.size.hash(state);
self.options.hash(state);
self.platform_options.hash(state);
self.variations.hash(state);
}
}
impl PartialEq for BaseFontInstance {
fn eq(&self, other: &BaseFontInstance) -> bool {
// Skip the instance key.
self.font_key == other.font_key &&
self.size == other.size &&
self.options == other.options &&
self.platform_options == other.platform_options &&
self.variations == other.variations
}
}
impl Eq for BaseFontInstance {}
struct MappedFontKey {
font_key: FontKey,
template: FontTemplate,
}
struct FontKeyMapLocked {
namespace: IdNamespace,
next_id: u32,
template_map: FastHashMap<FontTemplate, Arc<MappedFontKey>>,
key_map: FastHashMap<FontKey, Arc<MappedFontKey>>,
}
/// A shared map from fonts key local to a namespace to shared font keys that
/// can be shared across many namespaces. Local keys are tracked in a hashmap
/// that stores a strong reference per mapping so that their count can be
/// tracked. A map of font templates is used to hash font templates to their
/// final shared key. The shared key will stay alive so long as there are
/// any strong references to the mapping entry. Care must be taken when
/// clearing namespaces of shared keys as this may trigger shared font keys
/// to expire which require individual processing. Shared font keys will be
/// created within the provided unique namespace.
#[derive(Clone)]
pub struct FontKeyMap(Arc<RwLock<FontKeyMapLocked>>);
impl FontKeyMap {
pub fn new(namespace: IdNamespace) -> Self {
FontKeyMap(Arc::new(RwLock::new(FontKeyMapLocked {
namespace,
next_id: 1,
template_map: FastHashMap::default(),
key_map: FastHashMap::default(),
})))
}
fn lock(&self) -> RwLockReadGuard<FontKeyMapLocked> {
self.0.read().unwrap()
}
fn lock_mut(&mut self) -> RwLockWriteGuard<FontKeyMapLocked> {
self.0.write().unwrap()
}
pub fn keys(&self) -> Vec<FontKey> {
self.lock().key_map.keys().cloned().collect()
}
pub fn map_key(&self, font_key: &FontKey) -> FontKey {
match self.lock().key_map.get(font_key) {
Some(mapped) => mapped.font_key,
None => *font_key,
}
}
pub fn add_key(&mut self, font_key: &FontKey, template: &FontTemplate) -> Option<FontKey> {
let mut locked = self.lock_mut();
if locked.key_map.contains_key(font_key) {
return None;
}
if let Some(mapped) = locked.template_map.get(template).cloned() {
locked.key_map.insert(*font_key, mapped);
return None;
}
let shared_key = FontKey::new(locked.namespace, locked.next_id);
locked.next_id += 1;
let mapped = Arc::new(MappedFontKey {
font_key: shared_key,
template: template.clone(),
});
locked.template_map.insert(template.clone(), mapped.clone());
locked.key_map.insert(*font_key, mapped);
Some(shared_key)
}
pub fn delete_key(&mut self, font_key: &FontKey) -> Option<FontKey> {
let mut locked = self.lock_mut();
let mapped = match locked.key_map.remove(font_key) {
Some(mapped) => mapped,
None => return Some(*font_key),
};
if Arc::strong_count(&mapped) <= 2 {
// Only the last mapped key and template map point to it.
locked.template_map.remove(&mapped.template);
Some(mapped.font_key)
} else {
None
}
}
pub fn clear_namespace(&mut self, namespace: IdNamespace) -> Vec<FontKey> {
let mut locked = self.lock_mut();
locked.key_map.retain(|key, _| {
if key.0 == namespace {
false
} else {
true
}
});
let mut deleted_keys = Vec::new();
locked.template_map.retain(|_, mapped| {
if Arc::strong_count(mapped) <= 1 {
// Only the template map points to it.
deleted_keys.push(mapped.font_key);
false
} else {
true
}
});
deleted_keys
}
}
type FontTemplateMapLocked = FastHashMap<FontKey, FontTemplate>;
/// A map of font keys to font templates that might hold both namespace-local
/// font templates as well as shared templates.
#[derive(Clone)]
pub struct FontTemplateMap(Arc<RwLock<FontTemplateMapLocked>>);
impl FontTemplateMap {
pub fn new() -> Self {
FontTemplateMap(Arc::new(RwLock::new(FastHashMap::default())))
}
pub fn lock(&self) -> RwLockReadGuard<FontTemplateMapLocked> {
self.0.read().unwrap()
}
fn lock_mut(&mut self) -> RwLockWriteGuard<FontTemplateMapLocked> {
self.0.write().unwrap()
}
pub fn clear(&mut self) {
self.lock_mut().clear();
}
pub fn len(&self) -> usize {
self.lock().len()
}
pub fn has_font(&self, key: &FontKey) -> bool {
self.lock().contains_key(key)
}
pub fn get_font(&self, key: &FontKey) -> Option<FontTemplate> {
self.lock().get(key).cloned()
}
pub fn add_font(&mut self, key: FontKey, template: FontTemplate) -> bool {
self.lock_mut().insert(key, template).is_none()
}
pub fn delete_font(&mut self, key: &FontKey) -> Option<FontTemplate> {
self.lock_mut().remove(key)
}
pub fn delete_fonts(&mut self, keys: &[FontKey]) {
if !keys.is_empty() {
let mut map = self.lock_mut();
for key in keys {
map.remove(key);
}
}
}
pub fn clear_namespace(&mut self, namespace: IdNamespace) -> Vec<FontKey> {
let mut deleted_keys = Vec::new();
self.lock_mut().retain(|key, _| {
if key.0 == namespace {
deleted_keys.push(*key);
false
} else {
true
}
});
deleted_keys
}
}
struct FontInstanceKeyMapLocked {
namespace: IdNamespace,
next_id: u32,
instances: FastHashSet<Arc<BaseFontInstance>>,
key_map: FastHashMap<FontInstanceKey, Weak<BaseFontInstance>>,
}
/// A map of namespace-local font instance keys to shared keys. Weak references
/// are used to track the liveness of each key mapping as other consumers of
/// BaseFontInstance might hold strong references to the entry. A mapping from
/// BaseFontInstance to the shared key is then used to determine which shared
/// key to assign to that instance. When the weak count of the mapping is zero,
/// the entry is allowed to expire. Again, care must be taken when clearing
/// a namespace within the key map as it may cause shared key expirations that
/// require individual processing. Shared instance keys will be created within
/// the provided unique namespace.
#[derive(Clone)]
pub struct FontInstanceKeyMap(Arc<RwLock<FontInstanceKeyMapLocked>>);
impl FontInstanceKeyMap {
pub fn new(namespace: IdNamespace) -> Self {
FontInstanceKeyMap(Arc::new(RwLock::new(FontInstanceKeyMapLocked {
namespace,
next_id: 1,
instances: FastHashSet::default(),
key_map: FastHashMap::default(),
})))
}
fn lock(&self) -> RwLockReadGuard<FontInstanceKeyMapLocked> {
self.0.read().unwrap()
}
fn lock_mut(&mut self) -> RwLockWriteGuard<FontInstanceKeyMapLocked> {
self.0.write().unwrap()
}
pub fn keys(&self) -> Vec<FontInstanceKey> {
self.lock().key_map.keys().cloned().collect()
}
pub fn map_key(&self, key: &FontInstanceKey) -> FontInstanceKey {
match self.lock().key_map.get(key).and_then(|weak| weak.upgrade()) {
Some(mapped) => mapped.instance_key,
None => *key,
}
}
pub fn add_key(&mut self, mut instance: BaseFontInstance) -> Option<Arc<BaseFontInstance>> {
let mut locked = self.lock_mut();
if locked.key_map.contains_key(&instance.instance_key) {
return None;
}
if let Some(weak) = locked.instances.get(&instance).map(|mapped| Arc::downgrade(mapped)) {
locked.key_map.insert(instance.instance_key, weak);
return None;
}
let unmapped_key = instance.instance_key;
instance.instance_key = FontInstanceKey::new(locked.namespace, locked.next_id);
locked.next_id += 1;
let shared_instance = Arc::new(instance);
locked.instances.insert(shared_instance.clone());
locked.key_map.insert(unmapped_key, Arc::downgrade(&shared_instance));
Some(shared_instance)
}
pub fn delete_key(&mut self, key: &FontInstanceKey) -> Option<FontInstanceKey> {
let mut locked = self.lock_mut();
let mapped = match locked.key_map.remove(key).and_then(|weak| weak.upgrade()) {
Some(mapped) => mapped,
None => return Some(*key),
};
if Arc::weak_count(&mapped) == 0 {
// Only the instance set points to it.
locked.instances.remove(&mapped);
Some(mapped.instance_key)
} else {
None
}
}
pub fn clear_namespace(&mut self, namespace: IdNamespace) -> Vec<FontInstanceKey> {
let mut locked = self.lock_mut();
locked.key_map.retain(|key, _| {
if key.0 == namespace {
false
} else {
true
}
});
let mut deleted_keys = Vec::new();
locked.instances.retain(|mapped| {
if Arc::weak_count(mapped) == 0 {
// Only the instance set points to it.
deleted_keys.push(mapped.instance_key);
false
} else {
true
}
});
deleted_keys
}
}
type FontInstanceMapLocked = FastHashMap<FontInstanceKey, Arc<BaseFontInstance>>;
/// A map of font instance data accessed concurrently from multiple threads.
#[derive(Clone)]
pub struct FontInstanceMap(Arc<RwLock<FontInstanceMapLocked>>);
impl FontInstanceMap {
/// Creates an empty shared map.
pub fn new() -> Self {
FontInstanceMap(Arc::new(RwLock::new(FastHashMap::default())))
}
/// Acquires a read lock on the shared map.
pub fn lock(&self) -> RwLockReadGuard<FontInstanceMapLocked> {
self.0.read().unwrap()
}
/// Acquires a read lock on the shared map.
fn lock_mut(&mut self) -> RwLockWriteGuard<FontInstanceMapLocked> {
self.0.write().unwrap()
}
///
pub fn clear(&mut self) {
self.lock_mut().clear();
}
///
pub fn get_font_instance_data(&self, key: FontInstanceKey) -> Option<FontInstanceData> {
match self.lock().get(&key) {
Some(instance) => Some(FontInstanceData {
font_key: instance.font_key,
size: instance.size.into(),
options: Some(FontInstanceOptions {
render_mode: instance.render_mode,
flags: instance.flags,
synthetic_italics: instance.synthetic_italics,
}),
platform_options: instance.platform_options,
variations: instance.variations.clone(),
}),
None => None,
}
}
///
pub fn get_font_instance(&self, instance_key: FontInstanceKey) -> Option<Arc<BaseFontInstance>> {
let instance_map = self.lock();
instance_map.get(&instance_key).cloned()
}
///
pub fn add_font_instance(&mut self, instance: Arc<BaseFontInstance>) {
self.lock_mut().insert(instance.instance_key, instance);
}
///
pub fn delete_font_instance(&mut self, instance_key: FontInstanceKey) {
self.lock_mut().remove(&instance_key);
}
///
pub fn delete_font_instances(&mut self, keys: &[FontInstanceKey]) {
if !keys.is_empty() {
let mut map = self.lock_mut();
for key in keys {
map.remove(key);
}
}
}
///
pub fn clear_namespace(&mut self, namespace: IdNamespace) {
self.lock_mut().retain(|key, _| key.0 != namespace);
}
}
/// Shared font resources that may need to be passed between multiple threads
/// such as font templates and font instances. They are individually protected
/// by locks to ensure safety.
#[derive(Clone)]
pub struct SharedFontResources {
pub templates: FontTemplateMap,
pub instances: FontInstanceMap,
pub font_keys: FontKeyMap,
pub instance_keys: FontInstanceKeyMap,
}
impl SharedFontResources {
pub fn new(namespace: IdNamespace) -> Self {
SharedFontResources {
templates: FontTemplateMap::new(),
instances: FontInstanceMap::new(),
font_keys: FontKeyMap::new(namespace),
instance_keys: FontInstanceKeyMap::new(namespace),
}
}
}
impl BlobImageResources for SharedFontResources {
fn get_font_data(&self, key: FontKey) -> Option<FontTemplate> {
let shared_key = self.font_keys.map_key(&key);
self.templates.get_font(&shared_key)
}
fn get_font_instance_data(&self, key: FontInstanceKey) -> Option<FontInstanceData> {
let shared_key = self.instance_keys.map_key(&key);
self.instances.get_font_instance_data(shared_key)
}
}
/// A mutable font instance description.
///
/// Performance is sensitive to the size of this structure, so it should only contain
/// the fields that we need to modify from the original base font instance.
#[derive(Clone, Debug, Ord, PartialOrd)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct FontInstance {
pub base: Arc<BaseFontInstance>,
pub transform: FontTransform,
pub render_mode: FontRenderMode,
pub flags: FontInstanceFlags,
pub color: ColorU,
// The font size is in *device/raster* pixels, not logical pixels.
// It is stored as an f32 since we need sub-pixel sizes.
pub size: FontSize,
}
impl Hash for FontInstance {
fn hash<H: Hasher>(&self, state: &mut H) {
// Hash only the base instance's key to avoid the cost of hashing
// the rest.
self.base.instance_key.hash(state);
self.transform.hash(state);
self.render_mode.hash(state);
self.flags.hash(state);
self.color.hash(state);
self.size.hash(state);
}
}
impl PartialEq for FontInstance {
fn eq(&self, other: &FontInstance) -> bool {
// Compare only the base instance's key.
self.base.instance_key == other.base.instance_key &&
self.transform == other.transform &&
self.render_mode == other.render_mode &&
self.flags == other.flags &&
self.color == other.color &&
self.size == other.size
}
}
impl Eq for FontInstance {}
impl Deref for FontInstance {
type Target = BaseFontInstance;
fn deref(&self) -> &BaseFontInstance {
self.base.as_ref()
}
}
impl MallocSizeOf for FontInstance {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { 0 }
}
impl FontInstance {
pub fn new(
base: Arc<BaseFontInstance>,
color: ColorU,
render_mode: FontRenderMode,
flags: FontInstanceFlags,
) -> Self {
FontInstance {
transform: FontTransform::identity(),
color,
size: base.size,
base,
render_mode,
flags,
}
}
pub fn from_base(
base: Arc<BaseFontInstance>,
) -> Self {
let color = ColorU::new(0, 0, 0, 255);
let render_mode = base.render_mode;
let flags = base.flags;
Self::new(base, color, render_mode, flags)
}
pub fn use_texture_padding(&self) -> bool {
self.flags.contains(FontInstanceFlags::TEXTURE_PADDING)
}
pub fn use_transform_glyphs(&self) -> bool {
self.flags.contains(FontInstanceFlags::TRANSFORM_GLYPHS)
}
pub fn get_alpha_glyph_format(&self) -> GlyphFormat {
if self.use_transform_glyphs() { GlyphFormat::TransformedAlpha } else { GlyphFormat::Alpha }
}
pub fn get_subpixel_glyph_format(&self) -> GlyphFormat {
if self.use_transform_glyphs() { GlyphFormat::TransformedSubpixel } else { GlyphFormat::Subpixel }
}
pub fn disable_subpixel_aa(&mut self) {
self.render_mode = self.render_mode.limit_by(FontRenderMode::Alpha);
}
pub fn disable_subpixel_position(&mut self) {
self.flags.remove(FontInstanceFlags::SUBPIXEL_POSITION);
}
pub fn use_subpixel_position(&self) -> bool {
self.flags.contains(FontInstanceFlags::SUBPIXEL_POSITION) &&
self.render_mode != FontRenderMode::Mono
}
pub fn get_subpx_dir(&self) -> SubpixelDirection {
if self.use_subpixel_position() {
let mut subpx_dir = self.transform.get_subpx_dir();
if self.flags.contains(FontInstanceFlags::TRANSPOSE) {
subpx_dir = subpx_dir.swap_xy();
}
subpx_dir
} else {
SubpixelDirection::None
}
}
#[allow(dead_code)]
pub fn get_subpx_offset(&self, glyph: &GlyphKey) -> (f64, f64) {
if self.use_subpixel_position() {
let (dx, dy) = glyph.subpixel_offset();
(dx.into(), dy.into())
} else {
(0.0, 0.0)
}
}
#[allow(dead_code)]
pub fn get_glyph_format(&self) -> GlyphFormat {
match self.render_mode {
FontRenderMode::Mono | FontRenderMode::Alpha => self.get_alpha_glyph_format(),
FontRenderMode::Subpixel => self.get_subpixel_glyph_format(),