wasma-sys 1.3.0-beta-stable2

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
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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
// WASMA - Windows Assignment System Monitoring Architecture
// wasma_client_unix_posix_raw_window.rs
// Raw POSIX Window Management Client
// Window management through raw POSIX fd, rendering delegated to WindowClient
// UClientEngine trait'ini implement eder (raw_app ile paralel)
// Ocak 2026

use std::collections::HashMap;
use std::os::unix::io::RawFd;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};

use crate::parser::WasmaConfig;
use crate::uclient::SectionMemory;
use crate::wasma_client_unix_posix_raw_app::{posix, RawAppSource, UClientEngine};
use crate::window_client::WindowClient;
use crate::window_handling::{WindowGeometry, WindowState, WindowType};

// ============================================================================
// POSIX WINDOW CONTROL PROTOCOL
// ============================================================================
// Communication protocol over POSIX fd for WASMA window management.
// Each command has 16 byte fixed header + variable length data.
//
// Başlık yapısı:
//   [0..4]   magic: 0x57 0x41 0x57 0x4D ("WAWM")
//   [4..8]   command: RawWindowCommand (u32 LE)
//   [8..12]  window_id: u32 LE
//   [12..16] payload_len: u32 LE (sonraki byte sayısı)
//
// Yanıt yapısı:
//   [0..4]   magic: 0x57 0x52 0x53 0x50 ("WRSP")
//   [4..8]   status: RawWindowStatus (u32 LE)
//   [8..12]  window_id: u32 LE
//   [12..16] payload_len: u32 LE

pub const WASMA_CMD_MAGIC: [u8; 4] = [0x57, 0x41, 0x57, 0x4D]; // "WAWM"
pub const WASMA_RSP_MAGIC: [u8; 4] = [0x57, 0x52, 0x53, 0x50]; // "WRSP"
pub const WASMA_HDR_SIZE: usize = 16;

/// Pencere yönetimi komutları
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RawWindowCommand {
    CreateWindow = 0x01,
    DestroyWindow = 0x02,
    SetGeometry = 0x03,
    GetGeometry = 0x04,
    SetState = 0x05,
    GetState = 0x06,
    SetFocus = 0x07,
    GetFocus = 0x08,
    SetTitle = 0x09,
    SetParent = 0x0A,
    ListWindows = 0x0B,
    SetVisible = 0x0C,
    SetType = 0x0D,
    Ping = 0xFF,
}

impl RawWindowCommand {
    pub fn from_u32(v: u32) -> Option<Self> {
        match v {
            0x01 => Some(Self::CreateWindow),
            0x02 => Some(Self::DestroyWindow),
            0x03 => Some(Self::SetGeometry),
            0x04 => Some(Self::GetGeometry),
            0x05 => Some(Self::SetState),
            0x06 => Some(Self::GetState),
            0x07 => Some(Self::SetFocus),
            0x08 => Some(Self::GetFocus),
            0x09 => Some(Self::SetTitle),
            0x0A => Some(Self::SetParent),
            0x0B => Some(Self::ListWindows),
            0x0C => Some(Self::SetVisible),
            0x0D => Some(Self::SetType),
            0xFF => Some(Self::Ping),
            _ => None,
        }
    }

    pub fn to_u32(self) -> u32 {
        self as u32
    }
}

/// Yanıt durum kodları
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RawWindowStatus {
    Ok = 0x00,
    ErrNotFound = 0x01,
    ErrInvalidParam = 0x02,
    ErrPermission = 0x03,
    ErrInternal = 0x04,
    Pong = 0xFF,
}

impl RawWindowStatus {
    pub fn from_u32(v: u32) -> Self {
        match v {
            0x00 => Self::Ok,
            0x01 => Self::ErrNotFound,
            0x02 => Self::ErrInvalidParam,
            0x03 => Self::ErrPermission,
            0x04 => Self::ErrInternal,
            0xFF => Self::Pong,
            _ => Self::ErrInternal,
        }
    }
}

// ============================================================================
// POSIX PENCERE FD YÖNETİCİSİ
// ============================================================================

/// POSIX fd üzerinden pencere kontrol kanalı
pub struct RawWindowFd {
    /// Kontrol kanalı fd'si (komut gönder / yanıt al)
    ctrl_fd: Option<RawFd>,
    /// Kaynak tanımı
    source: RawAppSource,
    /// Bağlı mı?
    connected: bool,
}

impl RawWindowFd {
    pub fn new(source: RawAppSource) -> Self {
        Self {
            ctrl_fd: None,
            source,
            connected: false,
        }
    }

    /// Kontrol kanalını aç
    pub fn connect(&mut self) -> Result<(), std::io::Error> {
        if self.connected {
            return Ok(());
        }

        let fd = match &self.source {
            RawAppSource::UnixSocket(path) => self.open_unix_socket(path)?,
            RawAppSource::TcpSocket { ip, port } => self.open_tcp(ip, *port)?,
            RawAppSource::NamedPipe(path) => posix::posix_open(path, libc::O_RDWR)?,
            RawAppSource::CharDevice(path) => posix::posix_open(path, libc::O_RDWR)?,
            RawAppSource::Stdin => 0,
        };

        self.ctrl_fd = Some(fd);
        self.connected = true;
        println!("🔗 RawWindowFd: Connected → {}", self.source.display_name());
        Ok(())
    }

    fn open_unix_socket(&self, path: &str) -> Result<RawFd, std::io::Error> {
        use std::os::unix::io::AsRawFd;
        use std::os::unix::net::UnixStream;
        let stream = UnixStream::connect(path)?;
        let fd = stream.as_raw_fd();
        let _ = std::mem::ManuallyDrop::new(stream);
        Ok(fd)
    }

    fn open_tcp(&self, ip: &str, port: u16) -> Result<RawFd, std::io::Error> {
        use std::net::TcpStream;
        use std::os::unix::io::AsRawFd;
        let stream = TcpStream::connect(format!("{}:{}", ip, port))?;
        let fd = stream.as_raw_fd();
        let _ = std::mem::ManuallyDrop::new(stream);
        Ok(fd)
    }

    /// 16 byte komut başlığı yazar
    fn write_header(
        &self,
        fd: RawFd,
        cmd: RawWindowCommand,
        window_id: u32,
        payload_len: u32,
    ) -> Result<(), std::io::Error> {
        let mut hdr = [0u8; WASMA_HDR_SIZE];
        hdr[0..4].copy_from_slice(&WASMA_CMD_MAGIC);
        hdr[4..8].copy_from_slice(&cmd.to_u32().to_le_bytes());
        hdr[8..12].copy_from_slice(&window_id.to_le_bytes());
        hdr[12..16].copy_from_slice(&payload_len.to_le_bytes());

        let mut written = 0;
        while written < WASMA_HDR_SIZE {
            let n = unsafe {
                libc::write(
                    fd,
                    hdr[written..].as_ptr() as *const libc::c_void,
                    WASMA_HDR_SIZE - written,
                )
            };
            match n {
                -1 => return Err(std::io::Error::last_os_error()),
                0 => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::WriteZero,
                        "write() sıfır byte yazdı",
                    ))
                }
                n => written += n as usize,
            }
        }
        Ok(())
    }

    /// payload byte'larını yazar
    fn write_payload(&self, fd: RawFd, payload: &[u8]) -> Result<(), std::io::Error> {
        let mut written = 0;
        while written < payload.len() {
            let n = unsafe {
                libc::write(
                    fd,
                    payload[written..].as_ptr() as *const libc::c_void,
                    payload.len() - written,
                )
            };
            match n {
                -1 => return Err(std::io::Error::last_os_error()),
                0 => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::WriteZero,
                        "write() sıfır byte yazdı",
                    ))
                }
                n => written += n as usize,
            }
        }
        Ok(())
    }

    /// Reads response header: (status, window_id, payload_len)
    fn read_response_header(
        &self,
        fd: RawFd,
    ) -> Result<(RawWindowStatus, u32, u32), std::io::Error> {
        let mut hdr = [0u8; WASMA_HDR_SIZE];
        posix::posix_read_exact(fd, &mut hdr)?;

        if hdr[0..4] != WASMA_RSP_MAGIC {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Geçersiz yanıt magic: {:?}", &hdr[0..4]),
            ));
        }

        let status = RawWindowStatus::from_u32(u32::from_le_bytes(hdr[4..8].try_into().unwrap()));
        let window_id = u32::from_le_bytes(hdr[8..12].try_into().unwrap());
        let payload_len = u32::from_le_bytes(hdr[12..16].try_into().unwrap());

        Ok((status, window_id, payload_len))
    }

    /// Komut gönder + yanıt al
    pub fn send_command(
        &self,
        cmd: RawWindowCommand,
        window_id: u32,
        payload: &[u8],
    ) -> Result<(RawWindowStatus, Vec<u8>), std::io::Error> {
        let fd = self.ctrl_fd.ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "Kontrol kanalı açık değil",
            )
        })?;

        // Komut yaz
        self.write_header(fd, cmd, window_id, payload.len() as u32)?;
        if !payload.is_empty() {
            self.write_payload(fd, payload)?;
        }

        // Yanıt oku
        let (status, _resp_wid, payload_len) = self.read_response_header(fd)?;
        let mut resp_payload = vec![0u8; payload_len as usize];
        if payload_len > 0 {
            posix::posix_read_exact(fd, &mut resp_payload)?;
        }

        Ok((status, resp_payload))
    }

    pub fn is_connected(&self) -> bool {
        self.connected
    }
}

impl Drop for RawWindowFd {
    fn drop(&mut self) {
        if let Some(fd) = self.ctrl_fd.take() {
            if fd != 0 {
                let _ = posix::posix_close(fd);
            }
        }
    }
}

// ============================================================================
// RAW PENCERE KAYDEDICI - Yerel pencere durumu
// ============================================================================

/// Yerel pencere kaydı — sunucuya gerek kalmadan hızlı sorgu
#[derive(Debug, Clone)]
pub struct RawWindowRecord {
    pub id: u64,
    pub title: String,
    pub app_id: String,
    pub geometry: WindowGeometry,
    pub state: WindowState,
    pub window_type: WindowType,
    pub visible: bool,
    pub focused: bool,
    pub parent_id: Option<u64>,
    pub children: Vec<u64>,
    pub created_at: SystemTime,
    pub last_modified: SystemTime,
}

impl RawWindowRecord {
    pub fn new(id: u64, title: impl Into<String>, app_id: impl Into<String>) -> Self {
        let now = SystemTime::now();
        Self {
            id,
            title: title.into(),
            app_id: app_id.into(),
            geometry: WindowGeometry {
                x: 0,
                y: 0,
                width: 800,
                height: 600,
            },
            state: WindowState::Normal,
            window_type: WindowType::Normal,
            visible: true,
            focused: false,
            parent_id: None,
            children: Vec::new(),
            created_at: now,
            last_modified: now,
        }
    }

    /// Kaydı günceller ve last_modified'ı tazeler
    pub fn touch(&mut self) {
        self.last_modified = SystemTime::now();
    }
}

// ============================================================================
// GEOMETRY CODEC - WindowGeometry ↔ byte dizisi dönüşümü
// ============================================================================

pub mod geometry_codec {
    use crate::window_handling::WindowGeometry;

    pub const GEOMETRY_SIZE: usize = 16; // 4 × i32/u32 LE

    pub fn encode(g: &WindowGeometry) -> [u8; GEOMETRY_SIZE] {
        let mut buf = [0u8; GEOMETRY_SIZE];
        buf[0..4].copy_from_slice(&g.x.to_le_bytes());
        buf[4..8].copy_from_slice(&g.y.to_le_bytes());
        buf[8..12].copy_from_slice(&g.width.to_le_bytes());
        buf[12..16].copy_from_slice(&g.height.to_le_bytes());
        buf
    }

    pub fn decode(buf: &[u8]) -> Option<WindowGeometry> {
        if buf.len() < GEOMETRY_SIZE {
            return None;
        }
        Some(WindowGeometry {
            x: i32::from_le_bytes(buf[0..4].try_into().ok()?),
            y: i32::from_le_bytes(buf[4..8].try_into().ok()?),
            width: u32::from_le_bytes(buf[8..12].try_into().ok()?),
            height: u32::from_le_bytes(buf[12..16].try_into().ok()?),
        })
    }
}

/// WindowState ↔ u8 dönüşümü
pub mod state_codec {
    use crate::window_handling::WindowState;

    pub fn encode(s: &WindowState) -> u8 {
        match s {
            WindowState::Normal => 0x00,
            WindowState::Minimized => 0x01,
            WindowState::Maximized => 0x02,
            WindowState::Fullscreen => 0x03,
            WindowState::Hidden => 0x04,
        }
    }

    pub fn decode(v: u8) -> WindowState {
        match v {
            0x00 => WindowState::Normal,
            0x01 => WindowState::Minimized,
            0x02 => WindowState::Maximized,
            0x03 => WindowState::Fullscreen,
            0x04 => WindowState::Hidden,
            _ => WindowState::Normal,
        }
    }
}

// ============================================================================
// RAW WINDOW CLIENT - Ana yapı
// ============================================================================

/// RawWindowClient
///
/// Pencere yönetimini POSIX fd üzerinden raw olarak yürütür.
/// Rendering tamamen WindowClient'a devredilir.
/// UClientEngine trait'ini implement eder → raw_app ile simetrik.
///
/// Katman hiyerarşisi:
///   WasmaCore
///     └── WindowHandler          (üst seviye yönetim)
///           └── WindowClient     (rendering + viewport)
///                 └── RawWindowClient  ← BU MODÜL (raw POSIX yönetim)
pub struct RawWindowClient {
    config: Arc<WasmaConfig>,

    /// POSIX kontrol kanalı
    fd_manager: RawWindowFd,

    /// Yerel pencere kaydedici (hızlı sorgu için)
    window_registry: Arc<Mutex<HashMap<u64, RawWindowRecord>>>,

    /// Pencere ID sayacı
    next_id: Arc<Mutex<u64>>,

    /// Rendering için WindowClient referansı
    /// None ise rendering atlanır (sadece yönetim modu)
    window_client: Option<Arc<Mutex<WindowClient>>>,

    /// Motor aktif mi?
    active: bool,

    /// SectionMemory — UClientEngine uyumluluğu için
    memory: SectionMemory,
}

impl RawWindowClient {
    pub fn new(config: WasmaConfig) -> Self {
        let level = config.resource_limits.scope_level;
        let source = RawAppSource::UnixSocket("/run/wasma/window.sock".to_string());

        Self {
            fd_manager: RawWindowFd::new(source),
            window_registry: Arc::new(Mutex::new(HashMap::new())),
            next_id: Arc::new(Mutex::new(1)),
            window_client: None,
            active: false,
            memory: SectionMemory::new(level),
            config: Arc::new(config),
        }
    }

    pub fn from_config(config: Arc<WasmaConfig>) -> Self {
        let level = config.resource_limits.scope_level;
        let source = RawAppSource::UnixSocket("/run/wasma/window.sock".to_string());

        Self {
            fd_manager: RawWindowFd::new(source),
            window_registry: Arc::new(Mutex::new(HashMap::new())),
            next_id: Arc::new(Mutex::new(1)),
            window_client: None,
            active: false,
            memory: SectionMemory::new(level),
            config,
        }
    }

    /// WindowClient'ı bağlar (rendering için)
    pub fn attach_window_client(&mut self, wc: Arc<Mutex<WindowClient>>) {
        self.window_client = Some(wc);
        println!("🔗 RawWindowClient: WindowClient attached (rendering delegated)");
    }

    /// Özel kaynak adresi ayarlar
    pub fn with_source(mut self, source: RawAppSource) -> Self {
        self.fd_manager = RawWindowFd::new(source);
        self
    }

    /// Sonraki pencere ID'sini üretir
    fn next_window_id(&self) -> u64 {
        let mut id = self.next_id.lock().unwrap();
        let current = *id;
        *id += 1;
        current
    }

    // -------------------------------------------------------------------------
    // PENCERE YÖNETİM İŞLEMLERİ
    // -------------------------------------------------------------------------

    /// Create new window
    pub fn create_window(
        &self,
        title: impl Into<String>,
        app_id: impl Into<String>,
        geometry: WindowGeometry,
        window_type: WindowType,
    ) -> Result<u64, String> {
        let title = title.into();
        let app_id = app_id.into();
        let window_id = self.next_window_id();

        // Payload: geometry(16) + title_len(2) + title + appid_len(2) + appid + type(1)
        let title_bytes = title.as_bytes();
        let app_id_bytes = app_id.as_bytes();
        let mut payload = Vec::with_capacity(
            geometry_codec::GEOMETRY_SIZE + 2 + title_bytes.len() + 2 + app_id_bytes.len() + 1,
        );

        payload.extend_from_slice(&geometry_codec::encode(&geometry));
        payload.extend_from_slice(&(title_bytes.len() as u16).to_le_bytes());
        payload.extend_from_slice(title_bytes);
        payload.extend_from_slice(&(app_id_bytes.len() as u16).to_le_bytes());
        payload.extend_from_slice(app_id_bytes);
        payload.push(state_codec::encode(&WindowState::Normal));

        // fd bağlı değilse yerel modda çalış
        let remote_ok = if self.fd_manager.is_connected() {
            match self.fd_manager.send_command(
                RawWindowCommand::CreateWindow,
                window_id as u32,
                &payload,
            ) {
                Ok((RawWindowStatus::Ok, _)) => true,
                Ok((status, _)) => {
                    eprintln!("⚠️  CreateWindow server error: {:?}", status);
                    false
                }
                Err(e) => {
                    eprintln!("⚠️  CreateWindow communication error: {}", e);
                    false
                }
            }
        } else {
            true // connectionless mode: only local registration
        };

        if remote_ok {
            // Yerel kayıt
            let mut record = RawWindowRecord::new(window_id, &title, &app_id);
            record.geometry = geometry;
            record.window_type = window_type;

            let mut registry = self.window_registry.lock().unwrap();
            registry.insert(window_id, record);

            println!(
                "🪟 RawWindowClient: Window {} created [{}x{} @ ({},{})]",
                window_id, geometry.width, geometry.height, geometry.x, geometry.y
            );
            Ok(window_id)
        } else {
            Err(format!("Window {} could not be created", window_id))
        }
    }

    /// Pencereyi kapat ve kaynakları serbest bırak
    pub fn destroy_window(&self, window_id: u64) -> Result<(), String> {
        // Önce çocuk pencereleri kapat
        let children: Vec<u64> = {
            let registry = self.window_registry.lock().unwrap();
            registry
                .get(&window_id)
                .map(|r| r.children.clone())
                .unwrap_or_default()
        };
        for child_id in children {
            self.destroy_window(child_id)?;
        }

        // Ebeveynden çıkar
        let parent_id = {
            let registry = self.window_registry.lock().unwrap();
            registry.get(&window_id).and_then(|r| r.parent_id)
        };
        if let Some(pid) = parent_id {
            let mut registry = self.window_registry.lock().unwrap();
            if let Some(parent) = registry.get_mut(&pid) {
                parent.children.retain(|&id| id != window_id);
                parent.touch();
            }
        }

        // Sunucuya bildir
        if self.fd_manager.is_connected() {
            let _ = self.fd_manager.send_command(
                RawWindowCommand::DestroyWindow,
                window_id as u32,
                &[],
            );
        }

        // Yerel kayıttan sil
        let mut registry = self.window_registry.lock().unwrap();
        if registry.remove(&window_id).is_some() {
            println!("🗑️  RawWindowClient: Window {} closed", window_id);
            Ok(())
        } else {
            Err(format!("Pencere {} bulunamadı", window_id))
        }
    }

    /// Pencere geometrisini ayarla
    pub fn set_geometry(&self, window_id: u64, geometry: WindowGeometry) -> Result<(), String> {
        let payload = geometry_codec::encode(&geometry);

        if self.fd_manager.is_connected() {
            match self.fd_manager.send_command(
                RawWindowCommand::SetGeometry,
                window_id as u32,
                &payload,
            ) {
                Ok((RawWindowStatus::Ok, _)) => {}
                Ok((status, _)) => return Err(format!("SetGeometry hatası: {:?}", status)),
                Err(e) => return Err(format!("SetGeometry iletişim hatası: {}", e)),
            }
        }

        let mut registry = self.window_registry.lock().unwrap();
        match registry.get_mut(&window_id) {
            Some(record) => {
                record.geometry = geometry;
                record.touch();
                println!(
                    "📐 Window {} geometry updated: {}x{} @ ({},{})",
                    window_id, geometry.width, geometry.height, geometry.x, geometry.y
                );

                // WindowClient'a bildir (rendering yeniden hesaplanır)
                if let Some(ref wc) = self.window_client {
                    let mut client = wc.lock().unwrap();
                    client.resize(geometry.width, geometry.height);
                }
                Ok(())
            }
            None => Err(format!("Pencere {} bulunamadı", window_id)),
        }
    }

    /// Pencere geometrisini sorgula
    pub fn get_geometry(&self, window_id: u64) -> Result<WindowGeometry, String> {
        // Önce yerel kayıta bak (önbellekleme)
        {
            let registry = self.window_registry.lock().unwrap();
            if let Some(record) = registry.get(&window_id) {
                return Ok(record.geometry);
            }
        }

        // Yerel kayıt yok, sunucuya sor
        if self.fd_manager.is_connected() {
            match self
                .fd_manager
                .send_command(RawWindowCommand::GetGeometry, window_id as u32, &[])
            {
                Ok((RawWindowStatus::Ok, payload)) => geometry_codec::decode(&payload)
                    .ok_or_else(|| "Geometry decode hatası".to_string()),
                Ok((status, _)) => Err(format!("GetGeometry sunucu hatası: {:?}", status)),
                Err(e) => Err(format!("GetGeometry iletişim hatası: {}", e)),
            }
        } else {
            Err(format!("Pencere {} bulunamadı", window_id))
        }
    }

    /// Pencere durumunu ayarla (minimize, maximize, fullscreen, hidden, normal)
    pub fn set_state(&self, window_id: u64, state: WindowState) -> Result<(), String> {
        let payload = [state_codec::encode(&state)];

        if self.fd_manager.is_connected() {
            match self.fd_manager.send_command(
                RawWindowCommand::SetState,
                window_id as u32,
                &payload,
            ) {
                Ok((RawWindowStatus::Ok, _)) => {}
                Ok((status, _)) => return Err(format!("SetState hatası: {:?}", status)),
                Err(e) => return Err(format!("SetState iletişim hatası: {}", e)),
            }
        }

        let mut registry = self.window_registry.lock().unwrap();
        match registry.get_mut(&window_id) {
            Some(record) => {
                record.state = state.clone();
                record.touch();
                println!("🔄 Window {} state: {:?}", window_id, state);
                Ok(())
            }
            None => Err(format!("Pencere {} bulunamadı", window_id)),
        }
    }

    /// Pencere durumunu sorgula
    pub fn get_state(&self, window_id: u64) -> Result<WindowState, String> {
        let registry = self.window_registry.lock().unwrap();
        match registry.get(&window_id) {
            Some(record) => Ok(record.state.clone()),
            None => Err(format!("Pencere {} bulunamadı", window_id)),
        }
    }

    /// Fokus ayarla
    pub fn set_focus(&self, window_id: u64) -> Result<(), String> {
        // Önce tüm pencerelerin fokusunu kaldır
        {
            let mut registry = self.window_registry.lock().unwrap();
            for record in registry.values_mut() {
                record.focused = false;
            }
        }

        if self.fd_manager.is_connected() {
            let _ = self
                .fd_manager
                .send_command(RawWindowCommand::SetFocus, window_id as u32, &[]);
        }

        let mut registry = self.window_registry.lock().unwrap();
        match registry.get_mut(&window_id) {
            Some(record) => {
                record.focused = true;
                record.touch();
                println!("👁️  Window {} focused", window_id);
                Ok(())
            }
            None => Err(format!("Pencere {} bulunamadı", window_id)),
        }
    }

    /// Fokuslu pencereyi sorgula
    pub fn get_focused_window(&self) -> Option<u64> {
        let registry = self.window_registry.lock().unwrap();
        registry.values().find(|r| r.focused).map(|r| r.id)
    }

    /// Başlık ayarla
    pub fn set_title(&self, window_id: u64, title: impl Into<String>) -> Result<(), String> {
        let title = title.into();
        let title_bytes = title.as_bytes();

        if self.fd_manager.is_connected() {
            let mut payload = Vec::with_capacity(2 + title_bytes.len());
            payload.extend_from_slice(&(title_bytes.len() as u16).to_le_bytes());
            payload.extend_from_slice(title_bytes);
            let _ = self.fd_manager.send_command(
                RawWindowCommand::SetTitle,
                window_id as u32,
                &payload,
            );
        }

        let mut registry = self.window_registry.lock().unwrap();
        match registry.get_mut(&window_id) {
            Some(record) => {
                record.title = title.clone();
                record.touch();
                println!("📝 Window {} title: \"{}\"", window_id, title);
                Ok(())
            }
            None => Err(format!("Pencere {} bulunamadı", window_id)),
        }
    }

    /// Görünürlük ayarla
    pub fn set_visible(&self, window_id: u64, visible: bool) -> Result<(), String> {
        if self.fd_manager.is_connected() {
            let _ = self.fd_manager.send_command(
                RawWindowCommand::SetVisible,
                window_id as u32,
                &[visible as u8],
            );
        }

        let mut registry = self.window_registry.lock().unwrap();
        match registry.get_mut(&window_id) {
            Some(record) => {
                record.visible = visible;
                record.touch();
                println!("👀 Window {} visibility: {}", window_id, visible);
                Ok(())
            }
            None => Err(format!("Pencere {} bulunamadı", window_id)),
        }
    }

    /// Establish parent-child relationship
    pub fn set_parent(&self, child_id: u64, parent_id: u64) -> Result<(), String> {
        // parent var mı kontrol et
        {
            let registry = self.window_registry.lock().unwrap();
            if !registry.contains_key(&parent_id) {
                return Err(format!("Ebeveyn pencere {} bulunamadı", parent_id));
            }
        }

        if self.fd_manager.is_connected() {
            let payload = (parent_id as u32).to_le_bytes();
            let _ = self.fd_manager.send_command(
                RawWindowCommand::SetParent,
                child_id as u32,
                &payload,
            );
        }

        let mut registry = self.window_registry.lock().unwrap();

        // Çocukta parent_id ayarla
        if let Some(child) = registry.get_mut(&child_id) {
            child.parent_id = Some(parent_id);
            child.touch();
        } else {
            return Err(format!("Çocuk pencere {} bulunamadı", child_id));
        }

        // Ebeveynde children listesine ekle
        if let Some(parent) = registry.get_mut(&parent_id) {
            if !parent.children.contains(&child_id) {
                parent.children.push(child_id);
            }
            parent.touch();
        }

        println!("👨‍👧 Window {} → parent {}", child_id, parent_id);
        Ok(())
    }

    /// Tüm pencereleri listele
    pub fn list_windows(&self) -> Vec<RawWindowRecord> {
        let registry = self.window_registry.lock().unwrap();
        let mut windows: Vec<RawWindowRecord> = registry.values().cloned().collect();
        windows.sort_by_key(|w| w.id);
        windows
    }

    /// Tek pencere kaydını sorgula
    pub fn get_window(&self, window_id: u64) -> Option<RawWindowRecord> {
        let registry = self.window_registry.lock().unwrap();
        registry.get(&window_id).cloned()
    }

    /// Rendering tetikle — WindowClient'a devredilir
/// Rendering tetikle — wsdg-open modeli: uygulama kendi render eder
pub fn render_frame(&self, window_id: u64, _stream_id: u8, data: &[u8]) -> Result<(), String> {
    {
        let registry = self.window_registry.lock().unwrap();
        match registry.get(&window_id) {
            Some(record) => {
                if !record.visible || record.state == WindowState::Hidden {
                    return Ok(());
                }
            }
            None => return Err(format!("Window {} not found", window_id)),
        }
    }

    // wsdg-open modeli: spawned app renders itself
    // WindowClient no longer handles rendering
    self.dispatch_data(data);
    Ok(())
}
    /// Ping — bağlantı sağlık kontrolü
    pub fn ping(&self) -> Result<Duration, String> {
        if !self.fd_manager.is_connected() {
            return Err("No connection".to_string());
        }

        let start = std::time::Instant::now();
        match self.fd_manager.send_command(RawWindowCommand::Ping, 0, &[]) {
            Ok((RawWindowStatus::Pong, _)) => Ok(start.elapsed()),
            Ok((status, _)) => Err(format!("Ping hatası: {:?}", status)),
            Err(e) => Err(format!("Ping iletişim hatası: {}", e)),
        }
    }
}

// ============================================================================
// UCLİENT ENGINE TRAIT İMPLEMENTASYONU (raw_app ile paralel)
// ============================================================================

impl UClientEngine for RawWindowClient {
    fn start_engine(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        println!("🔌 RawWindowClient: Opening control channel...");

        // fd kanalını bağla (hata olursa yerel modda devam et)
        if let Err(e) = self.fd_manager.connect() {
            eprintln!("⚠️  Server connection failed, running in local mode: {}", e);
        }

        self.active = true;
        println!("🟢 WASMA RawWindowClient: Engine Started");
        println!(
            "🎨 Renderer: {} (delegated to WindowClient)",
            self.config.resource_limits.renderer
        );
        println!("📡 Mode: Window Management Engine");

        // Olay döngüsü — sunucu gönderilen pencere olaylarını işler
        if self.fd_manager.is_connected() {
            let fd = self.fd_manager.ctrl_fd.unwrap();
            let mut event_buf = vec![0u8; WASMA_HDR_SIZE + 256];

            loop {
                // Olaya hazır mı? (50ms timeout)
                match posix::posix_poll_readable(fd, 50) {
                    Ok(false) => {
                        if !self.active {
                            break;
                        }
                        continue;
                    }
                    Ok(true) => {}
                    Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                    Err(e) => {
                        eprintln!("⚠️  Poll error: {}", e);
                        break;
                    }
                }

                // Başlık oku
                match posix::posix_read(fd, &mut event_buf[..WASMA_HDR_SIZE]) {
                    Ok(0) => {
                        println!("📭 Server connection closed.");
                        break;
                    }
                    Ok(n) if n < WASMA_HDR_SIZE => {
                        eprintln!("⚠️  Short header: {} bytes", n);
                        continue;
                    }
                    Ok(_) => {
                        // Olay işle (ileride pencere olayları burada dispatch edilecek)
                        self.handle_server_event(&event_buf[..WASMA_HDR_SIZE]);
                    }
                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
                    Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                    Err(e) => {
                        eprintln!("⚠️  Read error: {}", e);
                        break;
                    }
                }
            }
        }

        self.active = false;
        Ok(())
    }

    fn dispatch_data(&self, data: &[u8]) {
        // Raw window modunda dispatch: focused pencereye render et
        if let Some(focused_id) = self.get_focused_window() {
            let _ = self.render_frame(focused_id, 0, data);
        }
    }

    fn memory_usage(&self) -> (usize, usize, usize) {
        (
            self.memory.raw_storage.len(),
            self.memory.cell_count,
            self.memory.cell_size,
        )
    }

    fn get_config(&self) -> &WasmaConfig {
        &self.config
    }

    fn shutdown(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.active = false;

        // Tüm pencereleri kapat
        let ids: Vec<u64> = {
            let registry = self.window_registry.lock().unwrap();
            registry.keys().cloned().collect()
        };
        for id in ids {
            let _ = self.destroy_window(id);
        }

        println!("🛑 RawWindowClient shutdown");
        Ok(())
    }

    fn is_active(&self) -> bool {
        self.active
    }
}

// ============================================================================
// ÖZEL YARDIMCI METODLAR
// ============================================================================

impl RawWindowClient {
    /// Sunucudan gelen olay başlığını işler
    fn handle_server_event(&self, hdr: &[u8]) {
        if hdr.len() < WASMA_HDR_SIZE {
            return;
        }
        // Magic kontrolü
        if hdr[0..4] != WASMA_RSP_MAGIC {
            return;
        }
        let status =
            RawWindowStatus::from_u32(u32::from_le_bytes(hdr[4..8].try_into().unwrap_or([0; 4])));
        let window_id = u32::from_le_bytes(hdr[8..12].try_into().unwrap_or([0; 4]));

        println!(
            "📨 Server event: window_id={} status={:?}",
            window_id, status
        );
        // Gelecekte: FocusChanged, GeometryChanged, CloseRequest vb. olaylar işlenecek
    }
}

// ============================================================================
// BUILDER
// ============================================================================

pub struct RawWindowClientBuilder {
    config: Option<WasmaConfig>,
    source: Option<RawAppSource>,
    window_client: Option<Arc<Mutex<WindowClient>>>,
}

impl RawWindowClientBuilder {
    pub fn new() -> Self {
        Self {
            config: None,
            source: None,
            window_client: None,
        }
    }

    pub fn with_config(mut self, config: WasmaConfig) -> Self {
        self.config = Some(config);
        self
    }

    pub fn with_source(mut self, source: RawAppSource) -> Self {
        self.source = Some(source);
        self
    }

    pub fn with_window_client(mut self, wc: Arc<Mutex<WindowClient>>) -> Self {
        self.window_client = Some(wc);
        self
    }

    pub fn build(self) -> Result<RawWindowClient, String> {
        let config = self.config.ok_or("Config required")?;
        let mut client = RawWindowClient::new(config);

        if let Some(source) = self.source {
            client.fd_manager = RawWindowFd::new(source);
        }

        if let Some(wc) = self.window_client {
            client.attach_window_client(wc);
        }

        Ok(client)
    }
}

impl Default for RawWindowClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// TESTLER
// ============================================================================

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

    fn make_config() -> WasmaConfig {
        let parser = ConfigParser::new(None);
        let content = parser.generate_default_config();
        parser.parse(&content).unwrap()
    }

    #[test]
    fn test_create_and_destroy_window() {
        let config = make_config();
        let client = RawWindowClient::new(config);

        let geo = WindowGeometry {
            x: 100,
            y: 200,
            width: 1280,
            height: 720,
        };
        let id = client
            .create_window("Test Penceresi", "test.app", geo, WindowType::Normal)
            .unwrap();

        assert!(client.get_window(id).is_some());
        let record = client.get_window(id).unwrap();
        assert_eq!(record.geometry.width, 1280);
        assert_eq!(record.geometry.height, 720);
        assert_eq!(record.title, "Test Penceresi");

        client.destroy_window(id).unwrap();
        assert!(client.get_window(id).is_none());

        println!("✅ Window create and destroy working");
    }

    #[test]
    fn test_set_and_get_geometry() {
        let config = make_config();
        let client = RawWindowClient::new(config);

        let id = client
            .create_window(
                "Geo Test",
                "geo.app",
                WindowGeometry {
                    x: 0,
                    y: 0,
                    width: 800,
                    height: 600,
                },
                WindowType::Normal,
            )
            .unwrap();

        let new_geo = WindowGeometry {
            x: 50,
            y: 75,
            width: 1920,
            height: 1080,
        };
        client.set_geometry(id, new_geo).unwrap();

        let fetched = client.get_geometry(id).unwrap();
        assert_eq!(fetched.width, 1920);
        assert_eq!(fetched.height, 1080);
        assert_eq!(fetched.x, 50);
        assert_eq!(fetched.y, 75);

        println!("✅ Geometry management working");
    }

    #[test]
    fn test_window_state_transitions() {
        let config = make_config();
        let client = RawWindowClient::new(config);

        let id = client
            .create_window(
                "State Test",
                "state.app",
                WindowGeometry {
                    x: 0,
                    y: 0,
                    width: 800,
                    height: 600,
                },
                WindowType::Normal,
            )
            .unwrap();

        for state in [
            WindowState::Minimized,
            WindowState::Maximized,
            WindowState::Fullscreen,
            WindowState::Hidden,
            WindowState::Normal,
        ] {
            client.set_state(id, state.clone()).unwrap();
            assert_eq!(client.get_state(id).unwrap(), state);
        }

        println!("✅ Window state transitions working");
    }

    #[test]
    fn test_focus_management() {
        let config = make_config();
        let client = RawWindowClient::new(config);

        let geo = WindowGeometry {
            x: 0,
            y: 0,
            width: 800,
            height: 600,
        };
        let id1 = client
            .create_window("Win1", "app1", geo, WindowType::Normal)
            .unwrap();
        let id2 = client
            .create_window("Win2", "app2", geo, WindowType::Normal)
            .unwrap();

        client.set_focus(id1).unwrap();
        assert_eq!(client.get_focused_window(), Some(id1));
        assert!(!client.get_window(id2).unwrap().focused);

        client.set_focus(id2).unwrap();
        assert_eq!(client.get_focused_window(), Some(id2));
        assert!(!client.get_window(id1).unwrap().focused);

        println!("✅ Focus management working");
    }

    #[test]
    fn test_parent_child_relationship() {
        let config = make_config();
        let client = RawWindowClient::new(config);

        let geo = WindowGeometry {
            x: 0,
            y: 0,
            width: 800,
            height: 600,
        };
        let parent_id = client
            .create_window("Parent", "parent.app", geo, WindowType::Normal)
            .unwrap();
        let child_id = client
            .create_window("Child", "child.app", geo, WindowType::Dialog)
            .unwrap();

        client.set_parent(child_id, parent_id).unwrap();

        let parent = client.get_window(parent_id).unwrap();
        assert!(parent.children.contains(&child_id));

        let child = client.get_window(child_id).unwrap();
        assert_eq!(child.parent_id, Some(parent_id));

        // Parent kapatılınca çocuk da kapanır
        client.destroy_window(parent_id).unwrap();
        assert!(client.get_window(parent_id).is_none());
        assert!(client.get_window(child_id).is_none());

        println!("✅ Parent-child relationship working");
    }

    #[test]
    fn test_geometry_codec() {
        let geo = WindowGeometry {
            x: -100,
            y: 200,
            width: 1920,
            height: 1080,
        };
        let encoded = geometry_codec::encode(&geo);
        let decoded = geometry_codec::decode(&encoded).unwrap();

        assert_eq!(decoded.x, geo.x);
        assert_eq!(decoded.y, geo.y);
        assert_eq!(decoded.width, geo.width);
        assert_eq!(decoded.height, geo.height);

        println!("✅ Geometry codec working");
    }

    #[test]
    fn test_state_codec() {
        for state in [
            WindowState::Normal,
            WindowState::Minimized,
            WindowState::Maximized,
            WindowState::Fullscreen,
            WindowState::Hidden,
        ] {
            let encoded = state_codec::encode(&state);
            let decoded = state_codec::decode(encoded);
            assert_eq!(decoded, state);
        }
        println!("✅ State codec working");
    }

    #[test]
    fn test_list_windows() {
        let config = make_config();
        let client = RawWindowClient::new(config);

        let geo = WindowGeometry {
            x: 0,
            y: 0,
            width: 800,
            height: 600,
        };
        let _id1 = client
            .create_window("W1", "a1", geo, WindowType::Normal)
            .unwrap();
        let _id2 = client
            .create_window("W2", "a2", geo, WindowType::Normal)
            .unwrap();
        let _id3 = client
            .create_window("W3", "a3", geo, WindowType::Utility)
            .unwrap();

        let windows = client.list_windows();
        assert_eq!(windows.len(), 3);
        // ID sırasına göre sıralanmış olmalı
        assert!(windows[0].id < windows[1].id);
        assert!(windows[1].id < windows[2].id);

        println!("✅ Window listing working: {} windows", windows.len());
    }

    #[test]
    fn test_uclient_engine_trait_object() {
        let config = make_config();
        let client: Box<dyn UClientEngine> = Box::new(RawWindowClient::new(config));
        assert!(!client.is_active());
        println!("✅ UClientEngine trait object (RawWindowClient) working");
    }

    #[test]
    fn test_visibility() {
        let config = make_config();
        let client = RawWindowClient::new(config);

        let geo = WindowGeometry {
            x: 0,
            y: 0,
            width: 800,
            height: 600,
        };
        let id = client
            .create_window("Vis Test", "vis.app", geo, WindowType::Normal)
            .unwrap();

        assert!(client.get_window(id).unwrap().visible);

        client.set_visible(id, false).unwrap();
        assert!(!client.get_window(id).unwrap().visible);

        client.set_visible(id, true).unwrap();
        assert!(client.get_window(id).unwrap().visible);

        println!("✅ Visibility management working");
    }
}