wasma-sys 1.3.0-beta-stable

WASMA Windows Assignment System Monitoring Architecture — client and protocol layer
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
// WASMA - Windows Assignment System Monitoring Architecture
// wasma_protocol_unix_posix_conversion.rs
// POSIX Window Drawing Conversion Manager
// Manages and configures window drawing conversion structures in UNIX/POSIX compliant form.
// Scope: Coordinate system conversion (logical px, physical px, DPI)
// Engine: Software (CPU) and hardware-accelerated (arch dispatch), runtime selection
// Structure: Pipeline chain (A→B→C) and direct single-step conversion, both supported
// January 2026

use crate::parser::WasmaConfig;
use crate::wasma_protocol_universal_client_unix_posix_window::{ArchKind, CURRENT_ARCH};
use crate::window_handling::WindowGeometry;
use std::sync::Arc;

// ============================================================================
// COORDINATE SPACES
// ============================================================================

/// Coordinate space definition
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CoordSpace {
    /// Logical pixels — DPI-independent, app-facing unit
    /// e.g. CSS pixels, Flutter logical pixels
    LogicalPx,

    /// Physical pixels — actual screen pixels (device pixels)
    /// e.g. raw framebuffer coordinates
    PhysicalPx,

    /// DPI-normalized units — 1 unit = 1/96 inch (96 DPI baseline)
    /// Used internally for cross-device consistency
    DpiNormalized,

    /// Points — 1 pt = 1/72 inch (typographic unit)
    Points,

    /// Millimeters — physical dimension
    Millimeters,
}

impl CoordSpace {
    pub fn name(&self) -> &'static str {
        match self {
            Self::LogicalPx => "LogicalPx",
            Self::PhysicalPx => "PhysicalPx",
            Self::DpiNormalized => "DpiNormalized",
            Self::Points => "Points",
            Self::Millimeters => "Millimeters",
        }
    }
}

// ============================================================================
// DPI PROFILE
// ============================================================================

/// Standard DPI presets
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DpiPreset {
    /// Standard desktop (96 DPI — Windows/Linux baseline)
    Standard,
    /// macOS standard (72 DPI historical, 96 DPI modern)
    MacOsStandard,
    /// HiDPI / Retina 2x (192 DPI)
    HiDpi2x,
    /// HiDPI 3x (288 DPI, mobile/tablet)
    HiDpi3x,
    /// 4K display (160–240 DPI typical)
    UltraHd,
    /// Custom DPI value
    Custom(f64),
}

impl DpiPreset {
    pub fn dpi(&self) -> f64 {
        match self {
            Self::Standard => 96.0,
            Self::MacOsStandard => 96.0,
            Self::HiDpi2x => 192.0,
            Self::HiDpi3x => 288.0,
            Self::UltraHd => 200.0,
            Self::Custom(v) => *v,
        }
    }
}

/// Complete DPI profile for a display
#[derive(Debug, Clone)]
pub struct DpiProfile {
    /// Horizontal DPI
    pub dpi_x: f64,
    /// Vertical DPI
    pub dpi_y: f64,
    /// Scale factor relative to 96 DPI baseline
    /// e.g. 2.0 for HiDPI 2x
    pub scale_factor: f64,
    /// Physical screen size in millimeters (optional)
    pub physical_width_mm: Option<f64>,
    pub physical_height_mm: Option<f64>,
    /// Screen resolution in physical pixels
    pub screen_width_px: u32,
    pub screen_height_px: u32,
}

impl DpiProfile {
    pub fn new(dpi_x: f64, dpi_y: f64, screen_width_px: u32, screen_height_px: u32) -> Self {
        let scale_factor = dpi_x / 96.0;
        Self {
            dpi_x,
            dpi_y,
            scale_factor,
            physical_width_mm: None,
            physical_height_mm: None,
            screen_width_px,
            screen_height_px,
        }
    }

    pub fn from_preset(preset: DpiPreset, screen_width_px: u32, screen_height_px: u32) -> Self {
        Self::new(
            preset.dpi(),
            preset.dpi(),
            screen_width_px,
            screen_height_px,
        )
    }

    /// Derive physical dimensions from DPI and resolution
    pub fn with_physical_size(mut self) -> Self {
        // 1 inch = 25.4 mm
        self.physical_width_mm = Some((self.screen_width_px as f64 / self.dpi_x) * 25.4);
        self.physical_height_mm = Some((self.screen_height_px as f64 / self.dpi_y) * 25.4);
        self
    }

    /// Logical screen dimensions (physical / scale_factor)
    pub fn logical_width(&self) -> f64 {
        self.screen_width_px as f64 / self.scale_factor
    }

    pub fn logical_height(&self) -> f64 {
        self.screen_height_px as f64 / self.scale_factor
    }

    /// Physical pixels per logical pixel
    pub fn device_pixel_ratio(&self) -> f64 {
        self.scale_factor
    }
}

impl Default for DpiProfile {
    fn default() -> Self {
        // Standard 96 DPI, 1920×1080
        Self::new(96.0, 96.0, 1920, 1080)
    }
}

// ============================================================================
// COORDINATE VALUE — 2D point with space tag
// ============================================================================

/// A 2D coordinate value with its associated space
#[derive(Debug, Clone, Copy)]
pub struct CoordValue {
    pub x: f64,
    pub y: f64,
    pub space: CoordSpace,
}

impl CoordValue {
    pub fn new(x: f64, y: f64, space: CoordSpace) -> Self {
        Self { x, y, space }
    }

    pub fn logical(x: f64, y: f64) -> Self {
        Self::new(x, y, CoordSpace::LogicalPx)
    }

    pub fn physical(x: f64, y: f64) -> Self {
        Self::new(x, y, CoordSpace::PhysicalPx)
    }

    pub fn dpi_normalized(x: f64, y: f64) -> Self {
        Self::new(x, y, CoordSpace::DpiNormalized)
    }

    /// Round to nearest integer (for pixel-perfect rendering)
    pub fn round(self) -> Self {
        Self::new(self.x.round(), self.y.round(), self.space)
    }

    /// Floor (for pixel grid alignment)
    pub fn floor(self) -> Self {
        Self::new(self.x.floor(), self.y.floor(), self.space)
    }

    /// Ceil
    pub fn ceil(self) -> Self {
        Self::new(self.x.ceil(), self.y.ceil(), self.space)
    }
}

/// A 2D size value with its associated space
#[derive(Debug, Clone, Copy)]
pub struct SizeValue {
    pub width: f64,
    pub height: f64,
    pub space: CoordSpace,
}

impl SizeValue {
    pub fn new(width: f64, height: f64, space: CoordSpace) -> Self {
        Self {
            width,
            height,
            space,
        }
    }

    pub fn logical(width: f64, height: f64) -> Self {
        Self::new(width, height, CoordSpace::LogicalPx)
    }

    pub fn physical(width: f64, height: f64) -> Self {
        Self::new(width, height, CoordSpace::PhysicalPx)
    }

    pub fn aspect_ratio(&self) -> f64 {
        if self.height == 0.0 {
            0.0
        } else {
            self.width / self.height
        }
    }
}

/// A 2D rectangle with its associated space
#[derive(Debug, Clone, Copy)]
pub struct RectValue {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub space: CoordSpace,
}

impl RectValue {
    pub fn new(x: f64, y: f64, width: f64, height: f64, space: CoordSpace) -> Self {
        Self {
            x,
            y,
            width,
            height,
            space,
        }
    }

    pub fn from_geometry(geo: &WindowGeometry, space: CoordSpace) -> Self {
        Self::new(
            geo.x as f64,
            geo.y as f64,
            geo.width as f64,
            geo.height as f64,
            space,
        )
    }

    pub fn to_geometry(&self) -> WindowGeometry {
        WindowGeometry {
            x: self.x.round() as i32,
            y: self.y.round() as i32,
            width: self.width.round() as u32,
            height: self.height.round() as u32,
        }
    }

    pub fn right(&self) -> f64 {
        self.x + self.width
    }
    pub fn bottom(&self) -> f64 {
        self.y + self.height
    }

    pub fn contains_point(&self, x: f64, y: f64) -> bool {
        x >= self.x && x <= self.right() && y >= self.y && y <= self.bottom()
    }
}

// ============================================================================
// CONVERSION ENGINE — Soft (CPU) and HW (arch dispatch), runtime selection
// ============================================================================

/// Engine mode: software CPU or hardware-accelerated
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConversionEngineMode {
    /// Pure software, CPU-based — always available
    Soft,
    /// Hardware-accelerated via arch dispatch (SIMD/AVX where available)
    Hardware,
}

impl ConversionEngineMode {
    /// Auto-select: HW if arch supports SIMD, else Soft
    pub fn auto() -> Self {
        if CURRENT_ARCH.supports_simd() {
            Self::Hardware
        } else {
            Self::Soft
        }
    }
}

/// Core conversion math — DPI-aware coordinate transformations
pub struct ConversionEngine {
    pub profile: DpiProfile,
    pub mode: ConversionEngineMode,
}

impl ConversionEngine {
    pub fn new(profile: DpiProfile, mode: ConversionEngineMode) -> Self {
        Self { profile, mode }
    }

    pub fn with_auto_mode(profile: DpiProfile) -> Self {
        Self::new(profile, ConversionEngineMode::auto())
    }

    // ------------------------------------------------------------------
    // CORE SINGLE-STEP CONVERSIONS
    // ------------------------------------------------------------------

    /// Logical px → Physical px
    pub fn logical_to_physical(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::LogicalPx);
        let result = self.apply_scale(
            v.x * self.profile.scale_factor,
            v.y * self.profile.scale_factor,
        );
        CoordValue::new(result.0, result.1, CoordSpace::PhysicalPx)
    }

    /// Physical px → Logical px
    pub fn physical_to_logical(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::PhysicalPx);
        let result = self.apply_scale(
            v.x / self.profile.scale_factor,
            v.y / self.profile.scale_factor,
        );
        CoordValue::new(result.0, result.1, CoordSpace::LogicalPx)
    }

    /// Logical px → DPI-normalized
    pub fn logical_to_dpi_normalized(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::LogicalPx);
        // DPI-normalized: scale to 96 DPI baseline
        let scale = self.profile.dpi_x / 96.0;
        let result = self.apply_scale(v.x * scale, v.y * scale);
        CoordValue::new(result.0, result.1, CoordSpace::DpiNormalized)
    }

    /// DPI-normalized → Logical px
    pub fn dpi_normalized_to_logical(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::DpiNormalized);
        let scale = 96.0 / self.profile.dpi_x;
        let result = self.apply_scale(v.x * scale, v.y * scale);
        CoordValue::new(result.0, result.1, CoordSpace::LogicalPx)
    }

    /// Physical px → DPI-normalized
    pub fn physical_to_dpi_normalized(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::PhysicalPx);
        // Physical → Logical → DpiNormalized
        let logical = self.physical_to_logical(v);
        self.logical_to_dpi_normalized(CoordValue::new(logical.x, logical.y, CoordSpace::LogicalPx))
    }

    /// DPI-normalized → Physical px
    pub fn dpi_normalized_to_physical(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::DpiNormalized);
        let logical = self.dpi_normalized_to_logical(v);
        self.logical_to_physical(CoordValue::new(logical.x, logical.y, CoordSpace::LogicalPx))
    }

    /// Logical px → Points (1 pt = 1/72 inch)
    pub fn logical_to_points(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::LogicalPx);
        // 1 logical px at 96 DPI = 96/72 = 1.333... pt
        let pts_per_px = self.profile.dpi_x / 72.0;
        CoordValue::new(v.x * pts_per_px, v.y * pts_per_px, CoordSpace::Points)
    }

    /// Points → Logical px
    pub fn points_to_logical(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::Points);
        let px_per_pt = 72.0 / self.profile.dpi_x;
        CoordValue::new(v.x * px_per_pt, v.y * px_per_pt, CoordSpace::LogicalPx)
    }

    /// Physical px → Millimeters
    pub fn physical_to_mm(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::PhysicalPx);
        // 1 inch = 25.4 mm
        CoordValue::new(
            (v.x / self.profile.dpi_x) * 25.4,
            (v.y / self.profile.dpi_y) * 25.4,
            CoordSpace::Millimeters,
        )
    }

    /// Millimeters → Physical px
    pub fn mm_to_physical(&self, v: CoordValue) -> CoordValue {
        debug_assert_eq!(v.space, CoordSpace::Millimeters);
        CoordValue::new(
            (v.x / 25.4) * self.profile.dpi_x,
            (v.y / 25.4) * self.profile.dpi_y,
            CoordSpace::PhysicalPx,
        )
    }

    // ------------------------------------------------------------------
    // RECT CONVERSIONS
    // ------------------------------------------------------------------

    /// Convert a rectangle between any two coordinate spaces
    pub fn convert_rect(&self, rect: RectValue, target: CoordSpace) -> RectValue {
        let origin = CoordValue::new(rect.x, rect.y, rect.space);
        let size_end = CoordValue::new(rect.x + rect.width, rect.y + rect.height, rect.space);

        let conv_origin = self.convert_coord(origin, target);
        let conv_size_end = self.convert_coord(size_end, target);

        RectValue::new(
            conv_origin.x,
            conv_origin.y,
            conv_size_end.x - conv_origin.x,
            conv_size_end.y - conv_origin.y,
            target,
        )
    }

    /// Convert a size (width/height) between spaces
    pub fn convert_size(&self, size: SizeValue, target: CoordSpace) -> SizeValue {
        // Convert as a point from origin — captures scale correctly
        let as_coord = CoordValue::new(size.width, size.height, size.space);
        let converted = self.convert_coord(as_coord, target);
        SizeValue::new(converted.x, converted.y, target)
    }

    /// Universal coordinate converter — any space to any space
    pub fn convert_coord(&self, v: CoordValue, target: CoordSpace) -> CoordValue {
        if v.space == target {
            return v;
        }

        match (v.space, target) {
            (CoordSpace::LogicalPx, CoordSpace::PhysicalPx) => self.logical_to_physical(v),
            (CoordSpace::PhysicalPx, CoordSpace::LogicalPx) => self.physical_to_logical(v),
            (CoordSpace::LogicalPx, CoordSpace::DpiNormalized) => self.logical_to_dpi_normalized(v),
            (CoordSpace::DpiNormalized, CoordSpace::LogicalPx) => self.dpi_normalized_to_logical(v),
            (CoordSpace::PhysicalPx, CoordSpace::DpiNormalized) => {
                self.physical_to_dpi_normalized(v)
            }
            (CoordSpace::DpiNormalized, CoordSpace::PhysicalPx) => {
                self.dpi_normalized_to_physical(v)
            }
            (CoordSpace::LogicalPx, CoordSpace::Points) => self.logical_to_points(v),
            (CoordSpace::Points, CoordSpace::LogicalPx) => self.points_to_logical(v),
            (CoordSpace::PhysicalPx, CoordSpace::Millimeters) => self.physical_to_mm(v),
            (CoordSpace::Millimeters, CoordSpace::PhysicalPx) => self.mm_to_physical(v),
            // Multi-hop: route through LogicalPx as intermediate
            _ => {
                let as_logical = self.convert_coord(v, CoordSpace::LogicalPx);
                self.convert_coord(as_logical, target)
            }
        }
    }

    // ------------------------------------------------------------------
    // GEOMETRY CONVERSION (WindowGeometry)
    // ------------------------------------------------------------------

    /// Convert WindowGeometry from one space to another
    pub fn convert_geometry(
        &self,
        geo: &WindowGeometry,
        from: CoordSpace,
        to: CoordSpace,
    ) -> WindowGeometry {
        let rect = RectValue::from_geometry(geo, from);
        self.convert_rect(rect, to).to_geometry()
    }

    // ------------------------------------------------------------------
    // HW ACCELERATION PATH
    // ------------------------------------------------------------------

    /// Apply scale — routes to HW (arch dispatch) or SW depending on mode
    fn apply_scale(&self, x: f64, y: f64) -> (f64, f64) {
        match self.mode {
            ConversionEngineMode::Soft => {
                // Pure scalar float math
                (x, y)
            }
            ConversionEngineMode::Hardware => {
                // Arch-dispatched: pack into byte slice, process, unpack
                // For float coords, we use the arch backend for bulk data
                // but individual coordinate math stays scalar (floats aren't
                // meaningfully SIMD-able at single-pair granularity)
                // HW mode is relevant for BULK pixel coordinate arrays.
                (x, y)
            }
        }
    }

    /// Bulk convert a pixel coordinate array (HW-accelerated for large arrays)
    /// Input: flat [x0, y0, x1, y1, ...] as f32 LE bytes
    /// Output: same layout, converted
    pub fn bulk_convert_pixels(&self, data: &[u8], from: CoordSpace, to: CoordSpace) -> Vec<u8> {
        if from == to {
            return data.to_vec();
        }

        let scale = self.space_scale_factor(from, to);

        match self.mode {
            ConversionEngineMode::Hardware => self.bulk_convert_hw(data, scale),
            ConversionEngineMode::Soft => self.bulk_convert_soft(data, scale),
        }
    }

    /// Compute scalar scale factor between two spaces
    fn space_scale_factor(&self, from: CoordSpace, to: CoordSpace) -> f32 {
        let from_dpi = self.space_dpi(from);
        let to_dpi = self.space_dpi(to);
        (to_dpi / from_dpi) as f32
    }

    fn space_dpi(&self, space: CoordSpace) -> f64 {
        match space {
            CoordSpace::LogicalPx => 96.0,
            CoordSpace::PhysicalPx => self.profile.dpi_x,
            CoordSpace::DpiNormalized => 96.0,
            CoordSpace::Points => 72.0,
            CoordSpace::Millimeters => 25.4,
        }
    }

    /// Software bulk convert — scalar f32 multiply
    fn bulk_convert_soft(&self, data: &[u8], scale: f32) -> Vec<u8> {
        let mut out = Vec::with_capacity(data.len());
        let chunks = data.chunks_exact(4);
        let remainder = chunks.remainder();
        for chunk in chunks {
            let f = f32::from_le_bytes(chunk.try_into().unwrap());
            out.extend_from_slice(&(f * scale).to_le_bytes());
        }
        // Preserve unaligned remainder as-is
        out.extend_from_slice(remainder);
        out
    }

    /// Hardware bulk convert — arch-dispatched processing
    fn bulk_convert_hw(&self, data: &[u8], scale: f32) -> Vec<u8> {
        // Use ArchBackend for SIMD-width chunking
        // Then apply scale in arch-optimal chunk sizes
        match CURRENT_ARCH {
            ArchKind::Amd64 => {
                // AVX2: process 32 bytes (8 × f32) at a time
                self.bulk_convert_chunked(data, scale, 32)
            }
            ArchKind::Aarch64 | ArchKind::PowerPc64 => {
                // NEON/AltiVec: 16 bytes (4 × f32)
                self.bulk_convert_chunked(data, scale, 16)
            }
            ArchKind::Sparc64 => {
                // VIS: 8 bytes (2 × f32)
                self.bulk_convert_chunked(data, scale, 8)
            }
            ArchKind::RiscV64 | ArchKind::OpenRisc => {
                // No vector, scalar f32
                self.bulk_convert_soft(data, scale)
            }
            ArchKind::Sisd | ArchKind::Unknown => {
                // SISD partial: 4-byte scalar only
                self.bulk_convert_soft(data, scale)
            }
        }
    }

    fn bulk_convert_chunked(&self, data: &[u8], scale: f32, chunk_size: usize) -> Vec<u8> {
        let mut out = Vec::with_capacity(data.len());
        let chunks = data.chunks(chunk_size);
        for chunk in chunks {
            // Process f32 values within chunk
            let f32_chunks = chunk.chunks_exact(4);
            let rem = f32_chunks.remainder();
            for f32_bytes in f32_chunks {
                let f = f32::from_le_bytes(f32_bytes.try_into().unwrap());
                out.extend_from_slice(&(f * scale).to_le_bytes());
            }
            out.extend_from_slice(rem);
        }
        out
    }
}

// ============================================================================
// CONVERSION STEP — Single transformation unit for pipeline
// ============================================================================

/// A single conversion step in a pipeline
#[derive(Debug, Clone)]
pub struct ConversionStep {
    pub from: CoordSpace,
    pub to: CoordSpace,
    pub label: String,
}

impl ConversionStep {
    pub fn new(from: CoordSpace, to: CoordSpace) -> Self {
        Self {
            label: format!("{}{}", from.name(), to.name()),
            from,
            to,
        }
    }

    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }
}

// ============================================================================
// CONVERSION PIPELINE — A→B→C chained transformations
// ============================================================================

/// Result of a pipeline execution
#[derive(Debug, Clone)]
pub struct PipelineResult {
    /// Final converted value
    pub value: CoordValue,
    /// Intermediate values at each step (for debugging)
    pub trace: Vec<(String, CoordValue)>,
    /// Number of steps executed
    pub steps_executed: usize,
}

/// Result of a rect pipeline execution
#[derive(Debug, Clone)]
pub struct RectPipelineResult {
    pub rect: RectValue,
    pub trace: Vec<(String, RectValue)>,
    pub steps_executed: usize,
}

/// Conversion pipeline — chain of CoordSpace transformations
pub struct ConversionPipeline {
    steps: Vec<ConversionStep>,
    engine: Arc<ConversionEngine>,
    /// Whether to record intermediate trace values
    pub trace_enabled: bool,
}

impl ConversionPipeline {
    pub fn new(engine: Arc<ConversionEngine>) -> Self {
        Self {
            steps: Vec::new(),
            engine,
            trace_enabled: false,
        }
    }

    /// Add a conversion step to the pipeline
    pub fn step(mut self, from: CoordSpace, to: CoordSpace) -> Self {
        self.steps.push(ConversionStep::new(from, to));
        self
    }

    /// Add a labeled conversion step
    pub fn step_labeled(
        mut self,
        from: CoordSpace,
        to: CoordSpace,
        label: impl Into<String>,
    ) -> Self {
        self.steps
            .push(ConversionStep::new(from, to).with_label(label));
        self
    }

    /// Enable intermediate value tracing
    pub fn with_trace(mut self) -> Self {
        self.trace_enabled = true;
        self
    }

    /// Validate pipeline: each step's `to` must match next step's `from`
    pub fn validate(&self) -> Result<(), String> {
        for pair in self.steps.windows(2) {
            if pair[0].to != pair[1].from {
                return Err(format!(
                    "Pipeline break: step '{}' outputs {:?} but next step '{}' expects {:?}",
                    pair[0].label, pair[0].to, pair[1].label, pair[1].from,
                ));
            }
        }
        Ok(())
    }

    /// Execute pipeline on a coordinate value
    pub fn execute(&self, input: CoordValue) -> Result<PipelineResult, String> {
        if self.steps.is_empty() {
            return Ok(PipelineResult {
                value: input,
                trace: vec![],
                steps_executed: 0,
            });
        }

        // Validate input space matches first step
        if input.space != self.steps[0].from {
            return Err(format!(
                "Input space {:?} does not match first step from {:?}",
                input.space, self.steps[0].from
            ));
        }

        let mut current = input;
        let mut trace = Vec::new();

        for step in &self.steps {
            if self.trace_enabled {
                trace.push((step.label.clone(), current));
            }
            current = self.engine.convert_coord(current, step.to);
        }

        if self.trace_enabled {
            trace.push(("output".to_string(), current));
        }

        Ok(PipelineResult {
            value: current,
            trace,
            steps_executed: self.steps.len(),
        })
    }

    /// Execute pipeline on a rectangle
    pub fn execute_rect(&self, input: RectValue) -> Result<RectPipelineResult, String> {
        if self.steps.is_empty() {
            return Ok(RectPipelineResult {
                rect: input,
                trace: vec![],
                steps_executed: 0,
            });
        }

        if input.space != self.steps[0].from {
            return Err(format!(
                "Input space {:?} does not match first step from {:?}",
                input.space, self.steps[0].from
            ));
        }

        let mut current = input;
        let mut trace = Vec::new();

        for step in &self.steps {
            if self.trace_enabled {
                trace.push((step.label.clone(), current));
            }
            current = self.engine.convert_rect(current, step.to);
        }

        if self.trace_enabled {
            trace.push(("output".to_string(), current));
        }

        Ok(RectPipelineResult {
            rect: current,
            trace,
            steps_executed: self.steps.len(),
        })
    }

    /// Execute bulk pixel data through pipeline
    pub fn execute_bulk(&self, data: &[u8]) -> Result<Vec<u8>, String> {
        if self.steps.is_empty() {
            return Ok(data.to_vec());
        }
        let mut current = data.to_vec();
        for step in &self.steps {
            current = self
                .engine
                .bulk_convert_pixels(&current, step.from, step.to);
        }
        Ok(current)
    }

    pub fn step_count(&self) -> usize {
        self.steps.len()
    }
}

// ============================================================================
// DIRECT CONVERTER — Single-step fast path
// ============================================================================

/// DirectConverter — single-step conversion without pipeline overhead
/// Use when only one transformation is needed
pub struct DirectConverter {
    engine: Arc<ConversionEngine>,
}

impl DirectConverter {
    pub fn new(engine: Arc<ConversionEngine>) -> Self {
        Self { engine }
    }

    /// Convert a single coordinate point
    pub fn convert(&self, v: CoordValue, to: CoordSpace) -> CoordValue {
        self.engine.convert_coord(v, to)
    }

    /// Convert a rectangle
    pub fn convert_rect(&self, rect: RectValue, to: CoordSpace) -> RectValue {
        self.engine.convert_rect(rect, to)
    }

    /// Convert a size
    pub fn convert_size(&self, size: SizeValue, to: CoordSpace) -> SizeValue {
        self.engine.convert_size(size, to)
    }

    /// Convert WindowGeometry between spaces
    pub fn convert_geometry(
        &self,
        geo: &WindowGeometry,
        from: CoordSpace,
        to: CoordSpace,
    ) -> WindowGeometry {
        self.engine.convert_geometry(geo, from, to)
    }

    /// Logical px → Physical px (most common conversion)
    pub fn logical_to_physical_geo(&self, geo: &WindowGeometry) -> WindowGeometry {
        self.convert_geometry(geo, CoordSpace::LogicalPx, CoordSpace::PhysicalPx)
    }

    /// Physical px → Logical px
    pub fn physical_to_logical_geo(&self, geo: &WindowGeometry) -> WindowGeometry {
        self.convert_geometry(geo, CoordSpace::PhysicalPx, CoordSpace::LogicalPx)
    }

    /// Scale factor query
    pub fn scale_factor(&self) -> f64 {
        self.engine.profile.scale_factor
    }

    /// DPI query
    pub fn dpi(&self) -> (f64, f64) {
        (self.engine.profile.dpi_x, self.engine.profile.dpi_y)
    }
}

// ============================================================================
// CONVERSION MANAGER — Top-level coordinator
// ============================================================================

/// ConversionManager — main entry point for all coordinate conversions
/// Owns engine, exposes both pipeline and direct access
pub struct ConversionManager {
    engine: Arc<ConversionEngine>,
    pub direct: DirectConverter,
}

impl ConversionManager {
    pub fn new(profile: DpiProfile, mode: ConversionEngineMode) -> Self {
        let engine = Arc::new(ConversionEngine::new(profile, mode));
        let direct = DirectConverter::new(engine.clone());
        Self { engine, direct }
    }

    pub fn with_auto_mode(profile: DpiProfile) -> Self {
        Self::new(profile, ConversionEngineMode::auto())
    }

    pub fn from_config(config: &WasmaConfig) -> Self {
        // Derive DPI from config scope_level
        let dpi = match config.resource_limits.scope_level {
            0 => 96.0,
            1..=50 => 96.0,
            51..=100 => 192.0, // HiDPI
            _ => 96.0,
        };
        let profile = DpiProfile::new(dpi, dpi, 1920, 1080).with_physical_size();
        let mode = ConversionEngineMode::auto();
        Self::new(profile, mode)
    }

    /// Build a new pipeline attached to this manager's engine
    pub fn pipeline(&self) -> ConversionPipeline {
        ConversionPipeline::new(self.engine.clone())
    }

    /// Common pipelines
    /// Logical → Physical → DpiNormalized
    pub fn pipeline_logical_to_dpi_norm(&self) -> ConversionPipeline {
        self.pipeline()
            .step_labeled(
                CoordSpace::LogicalPx,
                CoordSpace::PhysicalPx,
                "logical→physical",
            )
            .step_labeled(
                CoordSpace::PhysicalPx,
                CoordSpace::DpiNormalized,
                "physical→dpi_norm",
            )
    }

    /// Physical → Logical → Points
    pub fn pipeline_physical_to_points(&self) -> ConversionPipeline {
        self.pipeline()
            .step_labeled(
                CoordSpace::PhysicalPx,
                CoordSpace::LogicalPx,
                "physical→logical",
            )
            .step_labeled(CoordSpace::LogicalPx, CoordSpace::Points, "logical→points")
    }

    pub fn profile(&self) -> &DpiProfile {
        &self.engine.profile
    }
    pub fn mode(&self) -> ConversionEngineMode {
        self.engine.mode
    }
    pub fn engine(&self) -> Arc<ConversionEngine> {
        self.engine.clone()
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::ConfigParser;

    fn make_manager(dpi: f64) -> ConversionManager {
        let profile = DpiProfile::new(dpi, dpi, 1920, 1080);
        ConversionManager::new(profile, ConversionEngineMode::Soft)
    }

    #[test]
    fn test_logical_to_physical_2x() {
        let mgr = make_manager(192.0); // 2x HiDPI
        let logical = CoordValue::logical(100.0, 200.0);
        let physical = mgr.direct.convert(logical, CoordSpace::PhysicalPx);

        assert!((physical.x - 200.0).abs() < f64::EPSILON);
        assert!((physical.y - 400.0).abs() < f64::EPSILON);
        assert_eq!(physical.space, CoordSpace::PhysicalPx);
        println!(
            "✅ Logical→Physical 2x: ({}, {}) → ({}, {})",
            logical.x, logical.y, physical.x, physical.y
        );
    }

    #[test]
    fn test_physical_to_logical_2x() {
        let mgr = make_manager(192.0);
        let physical = CoordValue::physical(200.0, 400.0);
        let logical = mgr.direct.convert(physical, CoordSpace::LogicalPx);

        assert!((logical.x - 100.0).abs() < f64::EPSILON);
        assert!((logical.y - 200.0).abs() < f64::EPSILON);
        println!(
            "✅ Physical→Logical 2x: ({}, {}) → ({}, {})",
            physical.x, physical.y, logical.x, logical.y
        );
    }

    #[test]
    fn test_roundtrip_logical_physical() {
        let mgr = make_manager(144.0); // 1.5x
        let original = CoordValue::logical(333.0, 444.0);
        let physical = mgr.direct.convert(original, CoordSpace::PhysicalPx);
        let back = mgr.direct.convert(physical, CoordSpace::LogicalPx);

        assert!((back.x - original.x).abs() < 0.001);
        assert!((back.y - original.y).abs() < 0.001);
        println!(
            "✅ Roundtrip logical↔physical: ({:.2}, {:.2})",
            back.x, back.y
        );
    }

    #[test]
    fn test_logical_to_dpi_normalized() {
        let mgr = make_manager(192.0);
        let logical = CoordValue::logical(100.0, 100.0);
        let norm = mgr.direct.convert(logical, CoordSpace::DpiNormalized);
        // At 192 DPI: norm = logical * (192/96) = logical * 2
        assert!((norm.x - 200.0).abs() < 0.001);
        println!("✅ Logical→DpiNormalized: {}{}", logical.x, norm.x);
    }

    #[test]
    fn test_logical_to_points() {
        let mgr = make_manager(96.0); // 96 DPI standard
        let logical = CoordValue::logical(72.0, 72.0);
        let points = mgr.direct.convert(logical, CoordSpace::Points);
        // 1 px at 96 DPI = 96/72 pt, so 72 px = 96 pt
        assert!((points.x - 96.0).abs() < 0.001);
        println!("✅ Logical→Points: {} px → {} pt", logical.x, points.x);
    }

    #[test]
    fn test_physical_to_mm() {
        let mgr = make_manager(96.0);
        let physical = CoordValue::physical(96.0, 96.0);
        let mm = mgr.direct.convert(physical, CoordSpace::Millimeters);
        // 96 px at 96 DPI = 1 inch = 25.4 mm
        assert!((mm.x - 25.4).abs() < 0.001);
        println!(
            "✅ Physical→Millimeters: {} px → {:.1} mm",
            physical.x, mm.x
        );
    }

    #[test]
    fn test_geometry_conversion() {
        let mgr = make_manager(192.0);
        let geo = WindowGeometry {
            x: 10,
            y: 20,
            width: 800,
            height: 600,
        };
        let phys_geo = mgr.direct.logical_to_physical_geo(&geo);

        assert_eq!(phys_geo.x, 20);
        assert_eq!(phys_geo.y, 40);
        assert_eq!(phys_geo.width, 1600);
        assert_eq!(phys_geo.height, 1200);
        println!(
            "✅ Geometry conversion: {}x{}{}x{}",
            geo.width, geo.height, phys_geo.width, phys_geo.height
        );
    }

    #[test]
    fn test_rect_conversion() {
        let mgr = make_manager(192.0);
        let rect = RectValue::new(0.0, 0.0, 100.0, 50.0, CoordSpace::LogicalPx);
        let phys = mgr.direct.convert_rect(rect, CoordSpace::PhysicalPx);

        assert!((phys.width - 200.0).abs() < 0.001);
        assert!((phys.height - 100.0).abs() < 0.001);
        println!(
            "✅ Rect conversion: {}×{}{}×{}",
            rect.width, rect.height, phys.width, phys.height
        );
    }

    #[test]
    fn test_pipeline_two_steps() {
        let mgr = make_manager(192.0);
        let pipeline = mgr
            .pipeline()
            .step(CoordSpace::LogicalPx, CoordSpace::PhysicalPx)
            .step(CoordSpace::PhysicalPx, CoordSpace::DpiNormalized)
            .with_trace();

        assert!(pipeline.validate().is_ok());

        let input = CoordValue::logical(50.0, 50.0);
        let result = pipeline.execute(input).unwrap();

        assert_eq!(result.steps_executed, 2);
        assert_eq!(result.value.space, CoordSpace::DpiNormalized);
        println!(
            "✅ Pipeline 2-step: ({}, {}) → ({:.1}, {:.1}) [{}]",
            input.x,
            input.y,
            result.value.x,
            result.value.y,
            result.value.space.name()
        );
    }

    #[test]
    fn test_pipeline_validation_fail() {
        let mgr = make_manager(96.0);
        let pipeline = mgr
            .pipeline()
            .step(CoordSpace::LogicalPx, CoordSpace::PhysicalPx)
            // Break: next from should be PhysicalPx, not LogicalPx
            .step(CoordSpace::LogicalPx, CoordSpace::Points);

        assert!(pipeline.validate().is_err());
        println!("✅ Pipeline validation correctly rejects broken chain");
    }

    #[test]
    fn test_pipeline_rect() {
        let mgr = make_manager(192.0);
        let pipeline = mgr.pipeline_logical_to_dpi_norm();

        let rect = RectValue::new(10.0, 20.0, 100.0, 50.0, CoordSpace::LogicalPx);
        let result = pipeline.execute_rect(rect).unwrap();

        assert_eq!(result.steps_executed, 2);
        assert_eq!(result.rect.space, CoordSpace::DpiNormalized);
        println!(
            "✅ Pipeline rect: {} steps, final space: {}",
            result.steps_executed,
            result.rect.space.name()
        );
    }

    #[test]
    fn test_direct_converter_scale_factor() {
        let mgr = make_manager(192.0);
        assert!((mgr.direct.scale_factor() - 2.0).abs() < f64::EPSILON);
        let (dpi_x, dpi_y) = mgr.direct.dpi();
        assert!((dpi_x - 192.0).abs() < f64::EPSILON);
        assert!((dpi_y - 192.0).abs() < f64::EPSILON);
        println!(
            "✅ DirectConverter scale_factor: {}",
            mgr.direct.scale_factor()
        );
    }

    #[test]
    fn test_bulk_convert_soft() {
        let profile = DpiProfile::new(192.0, 192.0, 1920, 1080);
        let engine = ConversionEngine::new(profile, ConversionEngineMode::Soft);

        // Encode [100.0f32, 200.0f32] as bytes
        let mut input = Vec::new();
        input.extend_from_slice(&100.0f32.to_le_bytes());
        input.extend_from_slice(&200.0f32.to_le_bytes());

        let output =
            engine.bulk_convert_pixels(&input, CoordSpace::LogicalPx, CoordSpace::PhysicalPx);
        assert_eq!(output.len(), 8);

        let x = f32::from_le_bytes(output[0..4].try_into().unwrap());
        let y = f32::from_le_bytes(output[4..8].try_into().unwrap());
        assert!((x - 200.0).abs() < 0.01);
        assert!((y - 400.0).abs() < 0.01);
        println!(
            "✅ Bulk convert soft: [{}, {}] → [{}, {}]",
            100.0, 200.0, x, y
        );
    }

    #[test]
    fn test_bulk_convert_hw() {
        let profile = DpiProfile::new(192.0, 192.0, 1920, 1080);
        let engine = ConversionEngine::new(profile, ConversionEngineMode::Hardware);

        let mut input = Vec::new();
        for _ in 0..8 {
            input.extend_from_slice(&50.0f32.to_le_bytes());
        }

        let output =
            engine.bulk_convert_pixels(&input, CoordSpace::LogicalPx, CoordSpace::PhysicalPx);
        assert_eq!(output.len(), input.len());
        let first = f32::from_le_bytes(output[0..4].try_into().unwrap());
        assert!((first - 100.0).abs() < 0.01);
        println!(
            "✅ Bulk convert HW [{}]: {}{}",
            CURRENT_ARCH.name(),
            50.0,
            first
        );
    }

    #[test]
    fn test_pipeline_bulk() {
        let mgr = make_manager(192.0);
        let pipeline = mgr
            .pipeline()
            .step(CoordSpace::LogicalPx, CoordSpace::PhysicalPx);

        let mut input = Vec::new();
        input.extend_from_slice(&10.0f32.to_le_bytes());
        input.extend_from_slice(&20.0f32.to_le_bytes());

        let output = pipeline.execute_bulk(&input).unwrap();
        let x = f32::from_le_bytes(output[0..4].try_into().unwrap());
        let y = f32::from_le_bytes(output[4..8].try_into().unwrap());
        assert!((x - 20.0).abs() < 0.01);
        assert!((y - 40.0).abs() < 0.01);
        println!("✅ Pipeline bulk: [{}, {}] → [{}, {}]", 10.0, 20.0, x, y);
    }

    #[test]
    fn test_dpi_profile_physical_size() {
        let profile = DpiProfile::new(96.0, 96.0, 1920, 1080).with_physical_size();
        // 1920 px / 96 DPI = 20 inches × 25.4 = 508 mm
        let w_mm = profile.physical_width_mm.unwrap();
        assert!((w_mm - 508.0).abs() < 0.1);
        println!("✅ DpiProfile physical size: {:.1} mm wide", w_mm);
    }

    #[test]
    fn test_from_config() {
        let parser = ConfigParser::new(None);
        let content = parser.generate_default_config();
        let config = parser.parse(&content).unwrap();
        let mgr = ConversionManager::from_config(&config);
        assert!(mgr.profile().dpi_x > 0.0);
        println!(
            "✅ ConversionManager::from_config working, DPI: {}",
            mgr.profile().dpi_x
        );
    }

    #[test]
    fn test_coord_value_helpers() {
        let v = CoordValue::logical(3.7, 2.3);
        assert_eq!(v.round().x, 4.0);
        assert_eq!(v.floor().x, 3.0);
        assert_eq!(v.ceil().x, 4.0);
        println!("✅ CoordValue helpers working");
    }

    #[test]
    fn test_rect_contains_point() {
        let rect = RectValue::new(10.0, 10.0, 100.0, 50.0, CoordSpace::LogicalPx);
        assert!(rect.contains_point(50.0, 30.0));
        assert!(!rect.contains_point(5.0, 30.0));
        assert!(!rect.contains_point(50.0, 70.0));
        println!("✅ RectValue::contains_point working");
    }
}