stet-pdf-reader 0.8.1

Pure-Rust PDF parser and renderer — no C dependencies, prepress-grade CMYK and spot colour, plus a read-only structural API
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
// stet-pdf-reader
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Color space resolution from PDF page resources.

use std::sync::Arc;

use crate::error::PdfError;
use crate::objects::{PdfDict, PdfObj};
use crate::resolver::Resolver;
use crate::resources::function::PdfFunction;

use super::graphics_state::ColorSpaceRef;
use stet_graphics::color::{CieAParams, CieAbcParams, DeviceColor};
use stet_graphics::device::{ImageColorSpace, TintLookupTable};
use stet_graphics::icc::{IccCache, ProfileHash};

/// Resolved color space with enough info to convert color values.
#[derive(Clone, Debug)]
pub enum ResolvedColorSpace {
    DeviceGray,
    DeviceRGB,
    DeviceCMYK,
    ICCBased {
        n: u32,
        /// Raw ICC profile bytes (None if extraction failed).
        profile_data: Option<Arc<Vec<u8>>>,
        /// Alternate color space from stream dict (used when ICC transform fails).
        alternate: Option<Box<ResolvedColorSpace>>,
        /// Pre-computed ICC profile hash (avoids re-hashing per color conversion).
        profile_hash: Option<stet_graphics::icc::ProfileHash>,
    },
    Indexed {
        base: Box<ResolvedColorSpace>,
        hival: u32,
        lookup: Vec<u8>,
    },
    Separation {
        name: Vec<u8>,
        alt: Box<ResolvedColorSpace>,
        tint_fn: Option<PdfFunction>,
    },
    DeviceN {
        names: Vec<Vec<u8>>,
        alt: Box<ResolvedColorSpace>,
        tint_fn: Option<PdfFunction>,
    },
    CalGray {
        params: CieAParams,
    },
    CalRGB {
        params: CieAbcParams,
    },
    Lab {
        white_point: [f64; 3],
        range: [f64; 4], // [a_min, a_max, b_min, b_max]
    },
    Pattern,
}

impl ResolvedColorSpace {
    /// True if this is a Separation color space with the special "None" colorant.
    /// Per PDF spec 4.5.5, "None" produces no visible marks on the page.
    pub fn is_none_colorant(&self) -> bool {
        matches!(self, Self::Separation { name, .. } if name == b"None")
    }

    /// Number of color components.
    pub fn num_components(&self) -> usize {
        match self {
            Self::DeviceGray => 1,
            Self::DeviceRGB => 3,
            Self::DeviceCMYK => 4,
            Self::ICCBased { n, .. } => *n as usize,
            Self::Indexed { .. } => 1,
            Self::Separation { .. } => 1,
            Self::DeviceN { names, .. } => names.len(),
            Self::CalGray { .. } => 1,
            Self::CalRGB { .. } => 3,
            Self::Lab { .. } => 3,
            Self::Pattern => 0,
        }
    }
}

/// Compute the CMYK painted_channels bitmask for overprint simulation.
///
/// Returns which CMYK process color channels are affected by painting in this color space:
/// - DeviceCMYK: all 4 channels (OPM filtering happens at render time)
/// - Separation: the single named channel (Cyan/Magenta/Yellow/Black/All/None)
/// - DeviceN: union of named channels
/// - ICCBased with 4 components: treated as DeviceCMYK
/// - Other (Gray/RGB/CalGray/CalRGB/Lab/Pattern): 0 (no CMYK overprint)
pub fn painted_channels_for_cs(cs: &ResolvedColorSpace) -> u8 {
    use stet_graphics::device::{CMYK_ALL, cmyk_channel_for_name};
    match cs {
        ResolvedColorSpace::DeviceCMYK => CMYK_ALL,
        ResolvedColorSpace::ICCBased { n: 4, .. } => CMYK_ALL,
        ResolvedColorSpace::Separation { name, .. } => cmyk_channel_for_name(name),
        ResolvedColorSpace::DeviceN { names, .. } => names
            .iter()
            .fold(0u8, |acc, n| acc | cmyk_channel_for_name(n)),
        ResolvedColorSpace::Indexed { base, .. } => painted_channels_for_cs(base),
        _ => 0,
    }
}

/// Resolve a color space name or array from resources.
pub fn resolve_color_space(
    cs_ref: &ColorSpaceRef,
    resources: &PdfDict,
    resolver: &Resolver,
) -> Result<ResolvedColorSpace, PdfError> {
    match cs_ref {
        ColorSpaceRef::DeviceGray => Ok(ResolvedColorSpace::DeviceGray),
        ColorSpaceRef::DeviceRGB => Ok(ResolvedColorSpace::DeviceRGB),
        ColorSpaceRef::DeviceCMYK => Ok(ResolvedColorSpace::DeviceCMYK),
        ColorSpaceRef::Named(name) => resolve_named_color_space(name, resources, resolver),
    }
}

/// Resolve a named color space from the ColorSpace resource dict.
fn resolve_named_color_space(
    name: &[u8],
    resources: &PdfDict,
    resolver: &Resolver,
) -> Result<ResolvedColorSpace, PdfError> {
    // Check simple device names first
    match name {
        b"DeviceGray" | b"G" => return Ok(ResolvedColorSpace::DeviceGray),
        b"DeviceRGB" | b"RGB" => return Ok(ResolvedColorSpace::DeviceRGB),
        b"DeviceCMYK" | b"CMYK" => return Ok(ResolvedColorSpace::DeviceCMYK),
        b"Pattern" => return Ok(ResolvedColorSpace::Pattern),
        _ => {}
    }

    // Look up in resources ColorSpace dict (may be an indirect reference)
    let cs_dict = resources.get(b"ColorSpace").and_then(|obj| match obj {
        PdfObj::Dict(_) => Some(obj.as_dict().unwrap().clone()),
        PdfObj::Ref(n, g) => resolver.resolve(*n, *g).ok()?.as_dict().cloned(),
        _ => None,
    });
    let cs_obj = cs_dict.as_ref().and_then(|d| d.get(name)).ok_or_else(|| {
        PdfError::Other(format!(
            "color space /{} not found in resources",
            String::from_utf8_lossy(name)
        ))
    })?;

    resolve_color_space_obj(cs_obj, resolver)
}

/// Maximum recursion depth for color space resolution. Guards against PDFs
/// with self-referential color space definitions (e.g., an Indexed space
/// whose base points back to itself via an indirect reference — seen in
/// Acrobat Distiller 4.0 output).
const MAX_CS_DEPTH: u32 = 16;

/// Resolve a color space from a PdfObj (name or array).
pub fn resolve_color_space_obj(
    obj: &PdfObj,
    resolver: &Resolver,
) -> Result<ResolvedColorSpace, PdfError> {
    resolve_color_space_obj_depth(obj, resolver, 0)
}

fn resolve_color_space_obj_depth(
    obj: &PdfObj,
    resolver: &Resolver,
    depth: u32,
) -> Result<ResolvedColorSpace, PdfError> {
    if depth >= MAX_CS_DEPTH {
        return Err(PdfError::Other(
            "color space recursion limit exceeded".into(),
        ));
    }
    let obj = resolver.deref(obj)?;
    match &obj {
        PdfObj::Name(name) => match name.as_slice() {
            b"DeviceGray" | b"G" => Ok(ResolvedColorSpace::DeviceGray),
            b"DeviceRGB" | b"RGB" => Ok(ResolvedColorSpace::DeviceRGB),
            b"DeviceCMYK" | b"CMYK" => Ok(ResolvedColorSpace::DeviceCMYK),
            b"Pattern" => Ok(ResolvedColorSpace::Pattern),
            _ => Err(PdfError::Other(format!(
                "unknown color space name: /{}",
                String::from_utf8_lossy(name)
            ))),
        },
        PdfObj::Array(arr) if !arr.is_empty() => {
            // Deref array[0] in case it's an indirect reference to a name
            // (e.g., [7 0 R] where obj 7 = /Pattern).
            let first = resolver.deref(&arr[0])?;
            let cs_name = first
                .as_name()
                .ok_or(PdfError::Other("color space array[0] is not a name".into()))?;
            match cs_name {
                b"DeviceGray" => Ok(ResolvedColorSpace::DeviceGray),
                b"DeviceRGB" => Ok(ResolvedColorSpace::DeviceRGB),
                b"DeviceCMYK" => Ok(ResolvedColorSpace::DeviceCMYK),
                b"ICCBased" => resolve_icc_based(&arr[1..], resolver, depth + 1),
                b"Indexed" | b"I" => resolve_indexed(&arr[1..], resolver, depth + 1),
                b"Separation" => resolve_separation(&arr[1..], resolver, depth + 1),
                b"DeviceN" => resolve_devicen(&arr[1..], resolver, depth + 1),
                b"CalGray" => resolve_cal_gray(&arr[1..], resolver),
                b"CalRGB" => resolve_cal_rgb(&arr[1..], resolver),
                b"Lab" => resolve_lab(&arr[1..], resolver),
                b"Pattern" => Ok(ResolvedColorSpace::Pattern),
                _ => Err(PdfError::Other(format!(
                    "unsupported color space: /{}",
                    String::from_utf8_lossy(cs_name)
                ))),
            }
        }
        _ => Err(PdfError::Other(format!(
            "cannot resolve color space from: {obj:?}"
        ))),
    }
}

fn resolve_icc_based(
    args: &[PdfObj],
    resolver: &Resolver,
    depth: u32,
) -> Result<ResolvedColorSpace, PdfError> {
    if args.is_empty() {
        return Err(PdfError::Other("ICCBased missing stream ref".into()));
    }
    let stream_obj = resolver.deref(&args[0])?;
    let dict = stream_obj.as_dict().ok_or(PdfError::Other(
        "ICCBased stream is not a dict/stream".into(),
    ))?;
    let n = dict
        .get_int(b"N")
        .ok_or(PdfError::Other("ICCBased missing /N".into()))? as u32;

    // Extract ICC profile bytes from the stream (use original ref for encryption)
    let profile_data = resolver
        .stream_data_from_obj(&args[0])
        .ok()
        .filter(|d| !d.is_empty())
        .map(Arc::new);

    // Parse /Alternate color space (used as fallback when ICC transform fails)
    let alternate = dict
        .get(b"Alternate")
        .and_then(|obj| resolve_color_space_obj_depth(obj, resolver, depth).ok())
        .or_else(|| icc_alternate_from_header(profile_data.as_deref(), n))
        .map(Box::new);

    // Pre-compute profile hash to avoid re-hashing per color conversion
    let profile_hash = profile_data
        .as_deref()
        .map(|data| IccCache::hash_profile(data));

    Ok(ResolvedColorSpace::ICCBased {
        n,
        profile_data,
        alternate,
        profile_hash,
    })
}

/// Infer an alternate color space from the ICC profile header when /Alternate is absent.
/// Reads the data color space signature at offset 16-19 in the ICC header.
fn icc_alternate_from_header(data: Option<&Vec<u8>>, _n: u32) -> Option<ResolvedColorSpace> {
    let data = data?;
    if data.len() < 20 {
        return None;
    }
    match &data[16..20] {
        b"Lab " => Some(ResolvedColorSpace::Lab {
            // Default D50 white point, full a*/b* range
            white_point: [0.9505, 1.0, 1.089],
            range: [-128.0, 127.0, -128.0, 127.0],
        }),
        _ => None, // RGB/CMYK/Gray already handled correctly by n-based fallback
    }
}

fn resolve_indexed(
    args: &[PdfObj],
    resolver: &Resolver,
    depth: u32,
) -> Result<ResolvedColorSpace, PdfError> {
    if args.len() < 3 {
        return Err(PdfError::Other("Indexed color space needs 3 args".into()));
    }
    let base = resolve_color_space_obj_depth(&args[0], resolver, depth)?;
    let hival = args[1]
        .as_int()
        .ok_or(PdfError::Other("Indexed hival not int".into()))? as u32;

    let lookup_obj = resolver.deref(&args[2])?;
    let lookup = match &lookup_obj {
        PdfObj::Str(s) => s.clone(),
        PdfObj::Stream { .. } => resolver.stream_data_from_obj(&args[2])?,
        PdfObj::Dict(_) => {
            // Dict without Stream variant — try reading stream data directly
            resolver.stream_data_from_obj(&args[2])?
        }
        PdfObj::Null => {
            // Malformed PDF: null lookup table. Use empty data (all indices → black).
            Vec::new()
        }
        _ => {
            return Err(PdfError::Other(
                "Indexed lookup not string or stream".into(),
            ));
        }
    };

    Ok(ResolvedColorSpace::Indexed {
        base: Box::new(base),
        hival,
        lookup,
    })
}

fn resolve_separation(
    args: &[PdfObj],
    resolver: &Resolver,
    depth: u32,
) -> Result<ResolvedColorSpace, PdfError> {
    if args.len() < 2 {
        return Err(PdfError::Other("Separation needs at least 2 args".into()));
    }
    let name = args[0]
        .as_name()
        .ok_or(PdfError::Other("Separation name not a name".into()))?
        .to_vec();
    let alt = resolve_color_space_obj_depth(&args[1], resolver, depth)
        .or_else(|_| fallback_alternate(args, resolver))?;
    let tint_fn = if args.len() >= 3 {
        PdfFunction::parse(&args[2], resolver).ok()
    } else {
        None
    };
    Ok(ResolvedColorSpace::Separation {
        name,
        alt: Box::new(alt),
        tint_fn,
    })
}

fn resolve_devicen(
    args: &[PdfObj],
    resolver: &Resolver,
    depth: u32,
) -> Result<ResolvedColorSpace, PdfError> {
    // DeviceN array: [names alternateSpace tintTransform]
    if args.len() < 2 {
        return Err(PdfError::Other("DeviceN needs at least 2 args".into()));
    }
    let names_obj = resolver.deref(&args[0])?;
    let names = match &names_obj {
        PdfObj::Array(arr) => arr
            .iter()
            .filter_map(|o| o.as_name().map(|n| n.to_vec()))
            .collect(),
        _ => return Err(PdfError::Other("DeviceN names not an array".into())),
    };
    let alt = resolve_color_space_obj_depth(&args[1], resolver, depth)
        .or_else(|_| fallback_alternate(args, resolver))?;
    let tint_fn = if args.len() >= 3 {
        PdfFunction::parse(&args[2], resolver).ok()
    } else {
        None
    };
    Ok(ResolvedColorSpace::DeviceN {
        names,
        alt: Box::new(alt),
        tint_fn,
    })
}

/// Fallback alternate color space for broken Separation/DeviceN definitions
/// where the alternate space name is invalid (e.g., same as the colorant name).
///
/// Uses DeviceGray as a safe default — the tint function won't be used since
/// it targets a different number of components, so the Separation evaluator
/// falls back to a simple gray: tint 0 = white, tint 1 = black.
fn fallback_alternate(
    _args: &[PdfObj],
    _resolver: &Resolver,
) -> Result<ResolvedColorSpace, PdfError> {
    Ok(ResolvedColorSpace::DeviceGray)
}

fn resolve_cal_gray(args: &[PdfObj], resolver: &Resolver) -> Result<ResolvedColorSpace, PdfError> {
    let dict = if !args.is_empty() {
        let obj = resolver.deref(&args[0])?;
        obj.as_dict().cloned()
    } else {
        None
    };
    let dict = dict.as_ref();

    let white_point = parse_triple(dict, b"WhitePoint").unwrap_or([0.9505, 1.0, 1.089]);
    let gamma = dict.and_then(|d| d.get_f64(b"Gamma")).unwrap_or(1.0);

    // CalGray maps to CIEBasedA:
    // DecodeA = x^gamma, MatrixA = WhitePoint (so gray=1 → white point XYZ)
    let decode_a = if (gamma - 1.0).abs() > 1e-6 {
        Some((0..256).map(|i| (i as f64 / 255.0).powf(gamma)).collect())
    } else {
        None
    };

    let params = CieAParams {
        white_point,
        matrix_a: white_point, // full intensity = white point
        decode_a,
        // MatrixA produces LMN values that can exceed 1.0 (e.g. D65 Z=1.089).
        // Set RangeLMN upper bounds to the white point so values aren't clamped.
        range_lmn: [
            0.0,
            white_point[0].max(1.0),
            0.0,
            white_point[1].max(1.0),
            0.0,
            white_point[2].max(1.0),
        ],
        ..Default::default()
    };

    Ok(ResolvedColorSpace::CalGray { params })
}

fn resolve_cal_rgb(args: &[PdfObj], resolver: &Resolver) -> Result<ResolvedColorSpace, PdfError> {
    let dict = if !args.is_empty() {
        let obj = resolver.deref(&args[0])?;
        obj.as_dict().cloned()
    } else {
        None
    };
    let dict = dict.as_ref();

    let white_point = parse_triple(dict, b"WhitePoint").unwrap_or([0.9505, 1.0, 1.089]);
    let gamma = parse_triple(dict, b"Gamma").unwrap_or([1.0, 1.0, 1.0]);

    // Matrix is a 9-element array [Xa Ya Za Xb Yb Zb Xc Yc Zc]
    // PDF spec: column i is [Xi Yi Zi] — same as CIEBasedABC column-major convention
    let matrix = dict
        .and_then(|d| d.get_array(b"Matrix"))
        .map(|arr| {
            let v: Vec<f64> = arr.iter().filter_map(|o| o.as_f64()).collect();
            if v.len() >= 9 {
                [v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]]
            } else {
                [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
            }
        })
        .unwrap_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);

    let decode_abc = if gamma.iter().any(|&g| (g - 1.0).abs() > 1e-6) {
        Some([
            (0..256)
                .map(|i| (i as f64 / 255.0).powf(gamma[0]))
                .collect(),
            (0..256)
                .map(|i| (i as f64 / 255.0).powf(gamma[1]))
                .collect(),
            (0..256)
                .map(|i| (i as f64 / 255.0).powf(gamma[2]))
                .collect(),
        ])
    } else {
        None
    };

    let params = CieAbcParams {
        white_point,
        matrix_abc: matrix,
        decode_abc,
        // MatrixABC produces XYZ values that can exceed 1.0 (e.g. D65 Z=1.089).
        // Set RangeLMN upper bounds to the white point so values aren't clamped.
        range_lmn: [
            0.0,
            white_point[0].max(1.0),
            0.0,
            white_point[1].max(1.0),
            0.0,
            white_point[2].max(1.0),
        ],
        ..Default::default()
    };

    Ok(ResolvedColorSpace::CalRGB { params })
}

fn resolve_lab(args: &[PdfObj], resolver: &Resolver) -> Result<ResolvedColorSpace, PdfError> {
    let dict = if !args.is_empty() {
        let obj = resolver.deref(&args[0])?;
        obj.as_dict().cloned()
    } else {
        None
    };
    let dict = dict.as_ref();

    let white_point = parse_triple(dict, b"WhitePoint").unwrap_or([0.9505, 1.0, 1.089]);
    let range = dict
        .and_then(|d| d.get_array(b"Range"))
        .map(|arr| {
            let v: Vec<f64> = arr.iter().filter_map(|o| o.as_f64()).collect();
            if v.len() >= 4 {
                [v[0], v[1], v[2], v[3]]
            } else {
                [-100.0, 100.0, -100.0, 100.0]
            }
        })
        .unwrap_or([-100.0, 100.0, -100.0, 100.0]);

    Ok(ResolvedColorSpace::Lab { white_point, range })
}

fn parse_triple(dict: Option<&PdfDict>, key: &[u8]) -> Option<[f64; 3]> {
    dict?.get_array(key).and_then(|arr| {
        let v: Vec<f64> = arr.iter().filter_map(|o| o.as_f64()).collect();
        if v.len() >= 3 {
            Some([v[0], v[1], v[2]])
        } else {
            None
        }
    })
}

/// Convert color components to DeviceColor based on resolved color space.
pub fn components_to_device_color(cs: &ResolvedColorSpace, components: &[f64]) -> DeviceColor {
    components_to_device_color_icc(cs, components, None)
}

/// Process-only CMYK contribution for a Separation colorant. Returns
/// `Some((c, m, y, k))` with the tint placed on the named process channel
/// (or `(0, 0, 0, 0)` for a pure spot colorant so the overprint tracker
/// writes zero to its plates instead of the spot's alt-CMYK tint).
fn separation_process_cmyk(name: &[u8], tint: f64) -> Option<(f64, f64, f64, f64)> {
    use stet_graphics::device::{CMYK_C, CMYK_K, CMYK_M, CMYK_Y, cmyk_channel_for_name};
    let tint = tint.clamp(0.0, 1.0);
    match cmyk_channel_for_name(name) {
        CMYK_C => Some((tint, 0.0, 0.0, 0.0)),
        CMYK_M => Some((0.0, tint, 0.0, 0.0)),
        CMYK_Y => Some((0.0, 0.0, tint, 0.0)),
        CMYK_K => Some((0.0, 0.0, 0.0, tint)),
        0 => Some((0.0, 0.0, 0.0, 0.0)),
        _ => None,
    }
}

/// Process-only CMYK contribution for a DeviceN paint. Each component whose
/// colorant name maps to a process channel (C/M/Y/K/All) adds its tint to
/// that plate via subtractive (multiplicative-complement) stacking; spot
/// colorants contribute nothing to the process buffer.
#[allow(non_snake_case)]
fn deviceN_process_cmyk(names: &[Vec<u8>], tints: &[f64]) -> Option<(f64, f64, f64, f64)> {
    if names.len() != tints.len() {
        return None;
    }
    let mut c_compl = 1.0f64;
    let mut m_compl = 1.0f64;
    let mut y_compl = 1.0f64;
    let mut k_compl = 1.0f64;
    for (name, &tint) in names.iter().zip(tints.iter()) {
        let t = tint.clamp(0.0, 1.0);
        match name.as_slice() {
            b"Cyan" => c_compl *= 1.0 - t,
            b"Magenta" => m_compl *= 1.0 - t,
            b"Yellow" => y_compl *= 1.0 - t,
            b"Black" => k_compl *= 1.0 - t,
            b"All" => {
                let mult = 1.0 - t;
                c_compl *= mult;
                m_compl *= mult;
                y_compl *= mult;
                k_compl *= mult;
            }
            _ => {} // spot colorant — no process contribution
        }
    }
    Some((1.0 - c_compl, 1.0 - m_compl, 1.0 - y_compl, 1.0 - k_compl))
}

/// Convert color components to DeviceColor, with optional ICC profile
/// support. Equivalent to
/// [`components_to_device_color_icc_with_intent`] with the default
/// Perceptual intent — preserved for callers (shading rasterization,
/// recursive base/alt colour spaces) where the gstate intent isn't
/// readily threadable.
pub fn components_to_device_color_icc(
    cs: &ResolvedColorSpace,
    components: &[f64],
    icc_cache: Option<&mut IccCache>,
) -> DeviceColor {
    components_to_device_color_icc_with_intent(cs, components, icc_cache, 0)
}

/// Convert color components to DeviceColor with an explicit ICC
/// rendering intent. The `intent` byte mirrors the encoding on
/// [`crate::content::graphics_state::PdfGraphicsState::rendering_intent`]
/// (0=Perceptual, 1=RelCol, 2=Saturation, 3=AbsCol). Used by the main
/// content interpreter so PDF/X rendering picks the per-intent ICC chain
/// stored on `IccCache` (built in step 2 of the GWG 16.1 plan); for
/// `intent == 0` (the default) this is byte-for-byte identical to
/// [`components_to_device_color_icc`].
pub fn components_to_device_color_icc_with_intent(
    cs: &ResolvedColorSpace,
    components: &[f64],
    mut icc_cache: Option<&mut IccCache>,
    intent: u8,
) -> DeviceColor {
    match cs {
        ResolvedColorSpace::DeviceGray => {
            let g = components.first().copied().unwrap_or(0.0);
            DeviceColor::from_gray(g)
        }
        ResolvedColorSpace::DeviceRGB => {
            let r = components.first().copied().unwrap_or(0.0);
            let g = components.get(1).copied().unwrap_or(0.0);
            let b = components.get(2).copied().unwrap_or(0.0);
            DeviceColor::from_rgb(r, g, b)
        }
        ResolvedColorSpace::DeviceCMYK => {
            let c = components.first().copied().unwrap_or(0.0);
            let m = components.get(1).copied().unwrap_or(0.0);
            let y = components.get(2).copied().unwrap_or(0.0);
            let k = components.get(3).copied().unwrap_or(0.0);
            if let Some(cache) = icc_cache {
                DeviceColor::from_cmyk_icc(c, m, y, k, cache)
            } else {
                DeviceColor::from_cmyk(c, m, y, k)
            }
        }
        ResolvedColorSpace::ICCBased {
            n,
            profile_data,
            alternate,
            profile_hash,
        } => {
            // Try ICC profile conversion first, using pre-computed hash to avoid
            // re-hashing the profile data on every color conversion.
            let hash = profile_hash.or_else(|| {
                icc_cache.as_deref_mut().and_then(|cache| {
                    profile_data
                        .as_deref()
                        .and_then(|d| cache.register_profile_with_n(d, Some(*n)))
                })
            });
            if let Some(cache) = icc_cache.as_deref_mut()
                && let Some(hash) = hash
            {
                // Ensure the profile is registered (first time only)
                if !cache.has_profile(&hash) {
                    if let Some(data) = profile_data {
                        cache.register_profile_with_n(data, Some(*n));
                    }
                }
                let intent_enum = stet_graphics::icc::intent_from_pdf_byte(intent);
                if let Some((r, g, b)) =
                    cache.convert_color_with_intent(&hash, components, intent_enum)
                {
                    // For 4-component (CMYK) ICC profiles, preserve the
                    // source CMYK values in native_cmyk for overprint simulation.
                    if *n == 4 {
                        let c = components.first().copied().unwrap_or(0.0);
                        let m = components.get(1).copied().unwrap_or(0.0);
                        let y = components.get(2).copied().unwrap_or(0.0);
                        let k = components.get(3).copied().unwrap_or(0.0);
                        return DeviceColor {
                            r,
                            g,
                            b,
                            native_cmyk: Some((c, m, y, k)),
                            process_cmyk: None,
                        };
                    }
                    // For 3-component (RGB) ICC profiles in a PDF/X
                    // proofing context, also stash the chain's
                    // intermediate OutputIntent CMYK as `native_cmyk`.
                    // The renderer's `cmyk_group_blend` gate
                    // (`group_content_is_native_cmyk`) requires every
                    // fill / stroke in a `/CS DeviceCMYK` group to carry
                    // a `native_cmyk` value before it'll switch the
                    // group's blend math from sRGB to CMYK; without this
                    // GWG 16.1's ICCBasedRGB swatches blend in sRGB and
                    // their separable-mode X markers stay visible.
                    if *n == 3
                        && let Some(cmyk) = cache.convert_to_oi_cmyk(&hash, components, intent_enum)
                    {
                        return DeviceColor {
                            r,
                            g,
                            b,
                            native_cmyk: Some((cmyk[0], cmyk[1], cmyk[2], cmyk[3])),
                            process_cmyk: None,
                        };
                    }
                    return DeviceColor::from_rgb(r, g, b);
                }
            }
            // Fall back to alternate color space if available (handles Lab, XYZ, etc.)
            if let Some(alt) = alternate {
                return components_to_device_color_icc_with_intent(
                    alt, components, icc_cache, intent,
                );
            }
            // Last resort: device space based on component count
            match n {
                1 => {
                    let g = components.first().copied().unwrap_or(0.0);
                    DeviceColor::from_gray(g)
                }
                3 => {
                    let r = components.first().copied().unwrap_or(0.0);
                    let g = components.get(1).copied().unwrap_or(0.0);
                    let b = components.get(2).copied().unwrap_or(0.0);
                    DeviceColor::from_rgb(r, g, b)
                }
                4 => {
                    let c = components.first().copied().unwrap_or(0.0);
                    let m = components.get(1).copied().unwrap_or(0.0);
                    let y = components.get(2).copied().unwrap_or(0.0);
                    let k = components.get(3).copied().unwrap_or(0.0);
                    DeviceColor::from_cmyk(c, m, y, k)
                }
                _ => DeviceColor::black(),
            }
        }
        ResolvedColorSpace::Indexed {
            base,
            hival,
            lookup,
        } => {
            let raw = components.first().copied().unwrap_or(0.0).round();
            let idx = (raw as i64).clamp(0, *hival as i64) as usize;
            let n = base.num_components();
            let offset = idx * n;
            let mut base_components = Vec::with_capacity(n);
            for i in 0..n {
                let byte = lookup.get(offset + i).copied().unwrap_or(0);
                base_components.push(byte as f64 / 255.0);
            }
            components_to_device_color_icc_with_intent(base, &base_components, icc_cache, intent)
        }
        ResolvedColorSpace::Separation {
            alt, tint_fn, name, ..
        } => {
            // The special colorant name "None" produces no visible marks (PDF spec 4.5.5).
            // Return white here; callers should also set alpha=0 for true transparency.
            if name == b"None" {
                return DeviceColor::from_gray(1.0);
            }
            let tint = components.first().copied().unwrap_or(0.0);
            let mut color = if let Some(func) = tint_fn {
                let alt_components = func.evaluate(&[tint]);
                components_to_device_color_icc_with_intent(alt, &alt_components, icc_cache, intent)
            } else {
                // Fallback without tint function
                match alt.as_ref() {
                    ResolvedColorSpace::DeviceGray => DeviceColor::from_gray(1.0 - tint),
                    ResolvedColorSpace::DeviceCMYK => DeviceColor::from_cmyk(0.0, 0.0, 0.0, tint),
                    _ => DeviceColor::from_gray(1.0 - tint),
                }
            };
            // For CMYK process colorants (Cyan/Magenta/Yellow/Black), ensure
            // native_cmyk is set even when the alternate space is non-CMYK
            // (e.g. ICCBased RGB). Without this, overprint simulation uses
            // the (1-r, 1-g, 1-b, 0) fallback which puts Black ink into C+M+Y
            // instead of K, making Separation /Black strokes invisible when
            // painted_channels = CMYK_K.
            if color.native_cmyk.is_none() {
                use stet_graphics::device::{
                    CMYK_C, CMYK_K, CMYK_M, CMYK_Y, cmyk_channel_for_name,
                };
                let ch = cmyk_channel_for_name(name);
                if ch != 0 {
                    let (c, m, y, k) = match ch {
                        CMYK_C => (tint, 0.0, 0.0, 0.0),
                        CMYK_M => (0.0, tint, 0.0, 0.0),
                        CMYK_Y => (0.0, 0.0, tint, 0.0),
                        CMYK_K => (0.0, 0.0, 0.0, tint),
                        _ => (0.0, 0.0, 0.0, 0.0),
                    };
                    color.native_cmyk = Some((c, m, y, k));
                }
            }
            // Process-only contribution: for a process colorant the tint maps
            // directly to that process channel; for a pure spot the process
            // contribution is zero (the alt-CMYK is spot-derived and must not
            // leak into the process-CMYK tracker).
            color.process_cmyk = separation_process_cmyk(name, tint);
            color
        }
        ResolvedColorSpace::DeviceN {
            names,
            alt,
            tint_fn,
            ..
        } => {
            let mut color = if let Some(func) = tint_fn {
                let alt_components = func.evaluate(components);
                components_to_device_color_icc_with_intent(alt, &alt_components, icc_cache, intent)
            } else {
                // Fallback: use first component as gray
                let v = components.first().copied().unwrap_or(0.0);
                DeviceColor::from_gray(1.0 - v)
            };
            color.process_cmyk = deviceN_process_cmyk(names, components);
            color
        }
        ResolvedColorSpace::CalGray { params } => {
            let a = components.first().copied().unwrap_or(0.0);
            DeviceColor::from_cie_a(a, params)
        }
        ResolvedColorSpace::CalRGB { params } => {
            let a = components.first().copied().unwrap_or(0.0);
            let b = components.get(1).copied().unwrap_or(0.0);
            let c = components.get(2).copied().unwrap_or(0.0);
            DeviceColor::from_cie_abc(a, b, c, params)
        }
        ResolvedColorSpace::Lab { white_point, range } => {
            let mut color = lab_to_device_color(components, white_point, range);
            // Populate `native_cmyk` from the OI's `Lab → CMYK` direct sampler
            // when proofing is enabled. The sRGB pixmap value still comes from
            // the perceptual `from_lab → from_xyz` path (Lab is perceptually
            // uniform — the displayed colour shouldn't change), but band
            // renderers reading the parallel CMYK buffer for a CMYK-group
            // composite-back now see Acrobat's ACE-style Lab → OI CMYK rather
            // than the sRGB-derived approximation. GWG 22.1's ColorBurn form
            // over a Lab BG is the canonical surfacing case.
            if let Some(cache) = icc_cache.as_deref() {
                let intent_enum = stet_graphics::icc::intent_from_pdf_byte(intent);
                let l_star = components.first().copied().unwrap_or(0.0);
                let a_star = components.get(1).copied().unwrap_or(0.0);
                let b_star = components.get(2).copied().unwrap_or(0.0);
                if let Some(cmyk) =
                    cache.convert_lab_to_oi_cmyk(l_star, a_star, b_star, intent_enum)
                {
                    color.native_cmyk = Some((cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
                }
            }
            color
        }
        ResolvedColorSpace::Pattern => DeviceColor::black(),
    }
}

/// Convert a ResolvedColorSpace to ImageColorSpace for image rendering.
pub fn to_image_color_space(cs: &ResolvedColorSpace) -> ImageColorSpace {
    match cs {
        ResolvedColorSpace::DeviceGray => ImageColorSpace::DeviceGray,
        ResolvedColorSpace::DeviceRGB => ImageColorSpace::DeviceRGB,
        ResolvedColorSpace::DeviceCMYK => ImageColorSpace::DeviceCMYK,
        ResolvedColorSpace::ICCBased {
            n,
            profile_data,
            profile_hash,
            alternate,
        } => {
            // When an ICC profile is available, the rasterizer transforms
            // samples through it directly — keep ImageColorSpace::ICCBased so
            // that path runs.  Only fall back to the declared alternate (Lab /
            // CalRGB / CalGray / device) when no profile bytes are present.
            if let (Some(data), Some(hash)) = (profile_data, profile_hash) {
                return ImageColorSpace::ICCBased {
                    n: *n,
                    profile_hash: *hash,
                    profile_data: data.clone(),
                };
            }
            if let Some(alt) = alternate {
                match alt.as_ref() {
                    ResolvedColorSpace::Lab { .. }
                    | ResolvedColorSpace::CalRGB { .. }
                    | ResolvedColorSpace::CalGray { .. } => return to_image_color_space(alt),
                    _ => {}
                }
            }
            match n {
                1 => ImageColorSpace::DeviceGray,
                3 => ImageColorSpace::DeviceRGB,
                4 => ImageColorSpace::DeviceCMYK,
                _ => ImageColorSpace::DeviceRGB,
            }
        }
        ResolvedColorSpace::Indexed {
            base,
            hival,
            lookup,
        } => ImageColorSpace::Indexed {
            base: Box::new(to_image_color_space(base)),
            hival: *hival,
            lookup: lookup.clone(),
        },
        ResolvedColorSpace::Separation { name, alt, tint_fn } => {
            if let Some(func) = tint_fn {
                build_1d_tint_image_cs(func, alt, name.clone())
            } else {
                ImageColorSpace::DeviceGray
            }
        }
        ResolvedColorSpace::DeviceN {
            names,
            alt,
            tint_fn,
        } => {
            if let Some(func) = tint_fn {
                build_nd_tint_image_cs(func, alt, names.clone())
            } else {
                ImageColorSpace::DeviceGray
            }
        }
        ResolvedColorSpace::CalGray { params } => ImageColorSpace::CIEBasedA {
            params: std::sync::Arc::new(params.clone()),
        },
        ResolvedColorSpace::CalRGB { params } => ImageColorSpace::CIEBasedABC {
            params: std::sync::Arc::new(params.clone()),
        },
        ResolvedColorSpace::Lab { white_point, range } => ImageColorSpace::Lab {
            white_point: *white_point,
            range: *range,
        },
        ResolvedColorSpace::Pattern => ImageColorSpace::DeviceRGB,
    }
}

/// Register an ICC profile and return its hash (for use in color conversions).
pub fn register_icc_profile(
    cs: &ResolvedColorSpace,
    icc_cache: &mut IccCache,
) -> Option<ProfileHash> {
    match cs {
        ResolvedColorSpace::ICCBased {
            n, profile_data, ..
        } => {
            let data = profile_data.as_ref()?;
            icc_cache.register_profile_with_n(data, Some(*n))
        }
        _ => None,
    }
}

fn lab_to_device_color(
    components: &[f64],
    _white_point: &[f64; 3],
    range: &[f64; 4],
) -> DeviceColor {
    let l_star = components.first().copied().unwrap_or(0.0);
    let a_star = components.get(1).copied().unwrap_or(0.0);
    let b_star = components.get(2).copied().unwrap_or(0.0);
    DeviceColor::from_lab(l_star, a_star, b_star, range)
}

/// Check if a color space requires CIE→RGB conversion (Lab, CalRGB, CalGray).
/// The tint table stores pre-converted RGB values for these spaces.
fn is_cie_space(cs: &ResolvedColorSpace) -> bool {
    match cs {
        ResolvedColorSpace::Lab { .. }
        | ResolvedColorSpace::CalRGB { .. }
        | ResolvedColorSpace::CalGray { .. } => true,
        // ICCBased profiles that wrap a CIE alternate (e.g. Lab) need CIE conversion too
        ResolvedColorSpace::ICCBased {
            alternate: Some(alt),
            ..
        } => is_cie_space(alt),
        _ => false,
    }
}

/// Convert tint function output through a CIE alternate space to RGB,
/// pushing 3 f32 values (r, g, b) into `data`.
fn push_cie_converted(alt: &ResolvedColorSpace, out: &[f64], data: &mut Vec<f32>) {
    let color = components_to_device_color_icc(alt, out, None);
    data.push(color.r as f32);
    data.push(color.g as f32);
    data.push(color.b as f32);
}

/// Collapse the tint table's alt color space to a device-only ImageColorSpace.
/// The tint table stores the raw tint-function output components; at rasterize
/// time `alt_comps_to_rgb` interprets them.  That function only knows Device*
/// variants, so any ICCBased alt must be flattened to the matching device
/// space (which matches the old parse-time behaviour).
fn tint_alt_device_cs(alt: &ResolvedColorSpace) -> ImageColorSpace {
    match alt {
        ResolvedColorSpace::ICCBased { n, .. } => match n {
            1 => ImageColorSpace::DeviceGray,
            4 => ImageColorSpace::DeviceCMYK,
            _ => ImageColorSpace::DeviceRGB,
        },
        _ => to_image_color_space(alt),
    }
}

/// Build a 1D TintLookupTable for Separation image color space.
fn build_1d_tint_image_cs(
    func: &PdfFunction,
    alt: &ResolvedColorSpace,
    name: Vec<u8>,
) -> ImageColorSpace {
    let cie = is_cie_space(alt);
    let (alt_cs, n_out) = if cie {
        (ImageColorSpace::DeviceRGB, 3)
    } else {
        (tint_alt_device_cs(alt), alt.num_components())
    };
    let samples = 256u32;
    let mut data = Vec::with_capacity(samples as usize * n_out);
    for i in 0..samples {
        let t = i as f64 / 255.0;
        let out = func.evaluate(&[t]);
        if cie {
            push_cie_converted(alt, &out, &mut data);
        } else {
            for j in 0..n_out {
                data.push(out.get(j).copied().unwrap_or(0.0) as f32);
            }
        }
    }
    let table = TintLookupTable {
        num_inputs: 1,
        num_outputs: n_out as u32,
        samples_per_dim: samples,
        data,
    };
    ImageColorSpace::Separation {
        name,
        alt_space: Box::new(alt_cs),
        tint_table: Arc::new(table),
    }
}

/// Build an N-D TintLookupTable for DeviceN image color space.
fn build_nd_tint_image_cs(
    func: &PdfFunction,
    alt: &ResolvedColorSpace,
    names: Vec<Vec<u8>>,
) -> ImageColorSpace {
    let n_inputs = names.len();
    let cie = is_cie_space(alt);
    let (alt_cs, n_out) = if cie {
        (ImageColorSpace::DeviceRGB, 3)
    } else {
        (tint_alt_device_cs(alt), alt.num_components())
    };
    // Use fewer samples per dimension for higher-dimensional spaces.
    // Total table entries = spd^n_inputs × n_out, so balance quality vs memory.
    // These tables are used for fills/strokes; images with ≥2 inputs bypass
    // the table via direct per-pixel function evaluation (see mod.rs).
    let spd = match n_inputs {
        1 => 256u32,
        2 => 64,
        3 => 17,
        _ => 9,
    };
    let total: usize = (spd as usize).pow(n_inputs as u32);
    let mut data = Vec::with_capacity(total * n_out);
    let mut inputs = vec![0.0f64; n_inputs];
    for idx in 0..total {
        // Convert linear index to multi-dimensional coordinates
        let mut rem = idx;
        for d in (0..n_inputs).rev() {
            inputs[d] = (rem % spd as usize) as f64 / (spd - 1) as f64;
            rem /= spd as usize;
        }
        let out = func.evaluate(&inputs);
        if cie {
            push_cie_converted(alt, &out, &mut data);
        } else {
            for j in 0..n_out {
                data.push(out.get(j).copied().unwrap_or(0.0) as f32);
            }
        }
    }
    let table = TintLookupTable {
        num_inputs: n_inputs as u32,
        num_outputs: n_out as u32,
        samples_per_dim: spd,
        data,
    };
    ImageColorSpace::DeviceN {
        names,
        alt_space: Box::new(alt_cs),
        tint_table: Arc::new(table),
    }
}

/// Build a round-tripable [`IccColor`] for the current fill/stroke
/// when the resolved color space is an `ICCBased` profile with an
/// embedded ICC stream. Returns `None` for device color spaces,
/// Separation/DeviceN, CIE-only spaces, or ICCBased entries whose
/// profile bytes are missing (extraction failure at parse time).
pub fn build_icc_color(
    cs: &ResolvedColorSpace,
    components: &[f64],
) -> Option<stet_graphics::device::IccColor> {
    use stet_graphics::device::{IccColor, IccColorSpace};
    match cs {
        ResolvedColorSpace::ICCBased {
            n,
            profile_data: Some(data),
            profile_hash: Some(hash),
            ..
        } => Some(IccColor {
            components: components.to_vec(),
            color_space: IccColorSpace {
                n: *n,
                profile_data: Arc::clone(data),
                profile_hash: *hash,
            },
        }),
        _ => None,
    }
}

/// Pick a `SimpleColorSpace` to use as the round-trip alternate space for a
/// Separation/DeviceN paint. The alt's number of components determines the
/// tint table's output width.
fn simple_alt_for_spot(
    alt: &ResolvedColorSpace,
) -> (stet_graphics::device::SimpleColorSpace, usize) {
    use stet_graphics::device::SimpleColorSpace;
    if is_cie_space(alt) {
        return (SimpleColorSpace::DeviceRGB, 3);
    }
    match alt {
        ResolvedColorSpace::DeviceGray => (SimpleColorSpace::DeviceGray, 1),
        ResolvedColorSpace::DeviceRGB => (SimpleColorSpace::DeviceRGB, 3),
        ResolvedColorSpace::DeviceCMYK => (SimpleColorSpace::DeviceCMYK, 4),
        ResolvedColorSpace::ICCBased { n, .. } => match *n {
            1 => (SimpleColorSpace::DeviceGray, 1),
            4 => (SimpleColorSpace::DeviceCMYK, 4),
            _ => (SimpleColorSpace::DeviceRGB, 3),
        },
        _ => (SimpleColorSpace::DeviceRGB, 3),
    }
}

/// Sample a tint function into a `TintLookupTable` whose outputs match the
/// requested `SimpleColorSpace`. CIE alternate spaces produce RGB samples
/// via `push_cie_converted`; device alternates pass tint outputs through
/// directly.
fn sample_tint_table(
    func: &PdfFunction,
    n_inputs: usize,
    alt: &ResolvedColorSpace,
    n_out: usize,
) -> TintLookupTable {
    let cie = is_cie_space(alt);
    let spd = if n_inputs == 1 {
        256u32
    } else {
        match n_inputs {
            2 => 64,
            3 => 17,
            _ => 9,
        }
    };
    let total: usize = (spd as usize).pow(n_inputs as u32);
    let mut data = Vec::with_capacity(total * n_out);
    let mut inputs = vec![0.0f64; n_inputs];
    for idx in 0..total {
        let mut rem = idx;
        for d in (0..n_inputs).rev() {
            inputs[d] = (rem % spd as usize) as f64 / (spd - 1) as f64;
            rem /= spd as usize;
        }
        let out = func.evaluate(&inputs);
        if cie {
            push_cie_converted(alt, &out, &mut data);
        } else {
            for j in 0..n_out {
                data.push(out.get(j).copied().unwrap_or(0.0) as f32);
            }
        }
    }
    TintLookupTable {
        num_inputs: n_inputs as u32,
        num_outputs: n_out as u32,
        samples_per_dim: spd,
        data,
    }
}

/// Cache key for a spot/DeviceN tint table. Identifies the colorspace by
/// its canonical name(s); within a page the same name always resolves to
/// the same tint function, so a single sampled table can serve every paint.
fn spot_tint_cache_key(cs: &ResolvedColorSpace) -> Option<Vec<u8>> {
    match cs {
        ResolvedColorSpace::Separation { name, .. } => {
            let mut k = b"S:".to_vec();
            k.extend(name);
            Some(k)
        }
        ResolvedColorSpace::DeviceN { names, .. } => {
            let mut k = b"N:".to_vec();
            for (i, n) in names.iter().enumerate() {
                if i > 0 {
                    k.push(b'|');
                }
                k.extend(n);
            }
            Some(k)
        }
        _ => None,
    }
}

/// Build a `SpotColor` for a Separation/DeviceN paint, capturing both the
/// tint values from the current `sc`/`scn` operands and a pre-sampled tint
/// table so the PDF writer can round-trip the color space faithfully.
/// Returns `None` for non-spot color spaces or when the tint function is
/// missing.
///
/// `cache` is consulted before sampling — every spot paint with the same
/// colorspace name shares one `Arc<TintLookupTable>`, so a page that paints
/// the same Separation color hundreds of times does not re-evaluate the
/// tint function each time.
pub fn build_spot_color(
    cs: &ResolvedColorSpace,
    tint_values: &[f64],
    cache: &mut std::collections::HashMap<Vec<u8>, Arc<stet_graphics::device::TintLookupTable>>,
) -> Option<stet_graphics::device::SpotColor> {
    use stet_graphics::device::{SpotColor, SpotColorSpace};
    let key = spot_tint_cache_key(cs)?;
    match cs {
        ResolvedColorSpace::Separation { name, alt, tint_fn } => {
            let table = if let Some(t) = cache.get(&key) {
                Arc::clone(t)
            } else {
                let func = tint_fn.as_ref()?;
                let (_, n_out) = simple_alt_for_spot(alt);
                let t = Arc::new(sample_tint_table(func, 1, alt, n_out));
                cache.insert(key, Arc::clone(&t));
                t
            };
            let (simple_alt, _) = simple_alt_for_spot(alt);
            Some(SpotColor {
                tint_values: tint_values.to_vec(),
                color_space: SpotColorSpace::Separation {
                    name: name.clone(),
                    alt: simple_alt,
                    tint_table: table,
                },
            })
        }
        ResolvedColorSpace::DeviceN {
            names,
            alt,
            tint_fn,
        } => {
            let table = if let Some(t) = cache.get(&key) {
                Arc::clone(t)
            } else {
                let func = tint_fn.as_ref()?;
                let (_, n_out) = simple_alt_for_spot(alt);
                let t = Arc::new(sample_tint_table(func, names.len(), alt, n_out));
                cache.insert(key, Arc::clone(&t));
                t
            };
            let (simple_alt, _) = simple_alt_for_spot(alt);
            Some(SpotColor {
                tint_values: tint_values.to_vec(),
                color_space: SpotColorSpace::DeviceN {
                    names: names.clone(),
                    alt: simple_alt,
                    tint_table: table,
                },
            })
        }
        _ => None,
    }
}

/// Convert tinting function output components (f64, 0..1) to (R, G, B) bytes
/// through the given alternative color space.
pub fn alt_comps_to_rgb_f64(comps: &[f64], alt: &ResolvedColorSpace) -> (u8, u8, u8) {
    match alt {
        ResolvedColorSpace::DeviceGray => {
            let g = (comps.first().copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
            (g, g, g)
        }
        ResolvedColorSpace::DeviceRGB => {
            let r = (comps.first().copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
            let g = (comps.get(1).copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
            let b = (comps.get(2).copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
            (r, g, b)
        }
        ResolvedColorSpace::DeviceCMYK => {
            let c = comps.first().copied().unwrap_or(0.0).clamp(0.0, 1.0);
            let m = comps.get(1).copied().unwrap_or(0.0).clamp(0.0, 1.0);
            let y = comps.get(2).copied().unwrap_or(0.0).clamp(0.0, 1.0);
            let k = comps.get(3).copied().unwrap_or(0.0).clamp(0.0, 1.0);
            let r = ((1.0 - (c + k).min(1.0)) * 255.0 + 0.5) as u8;
            let g = ((1.0 - (m + k).min(1.0)) * 255.0 + 0.5) as u8;
            let b = ((1.0 - (y + k).min(1.0)) * 255.0 + 0.5) as u8;
            (r, g, b)
        }
        _ => (0, 0, 0),
    }
}