elibc 0.2.0

edos kernel libc
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
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
use alloc::vec::Vec;
use spin::Mutex;
use thiserror::Error;
// Re-export noto-sans-mono-bitmap types for user programs
pub use noto_sans_mono_bitmap::{FontWeight, RasterHeight};
use noto_sans_mono_bitmap::{get_raster, get_raster_width};

use crate::{
    io::{IoError, ioctl as fd_ioctl, open},
    math::isqrt,
    sys::{Errno, IOCTL_ARG_IN, IOCTL_ARG_OUT},
};

/// Graphics operation error type
#[derive(Debug, Error, Clone, Copy)]
pub enum GraphicsError {
    #[error("Invalid argument or coordinates")]
    InvalidInput,
    #[error("Out of memory")]
    OutOfMemory,
    #[error("Bad address/fault")]
    Fault,
    #[error("Unknown graphics error")]
    Unknown,
    #[error("Invalid color value")]
    InvalidColor,
    #[error("Coordinates out of bounds")]
    OutOfBounds,
    #[error("Unsupported character")]
    UnsupportedCharacter,
    #[error("Text rendering error")]
    TextError,
}

impl From<Errno> for GraphicsError {
    fn from(errno: Errno) -> Self {
        match errno {
            Errno::EINVAL => GraphicsError::InvalidInput,
            Errno::ENOMEM => GraphicsError::OutOfMemory,
            Errno::EFAULT => GraphicsError::Fault,
            Errno::UNKNOWN => GraphicsError::Unknown,
            Errno::Clear => GraphicsError::Unknown,
            _ => GraphicsError::Unknown,
        }
    }
}

impl From<IoError> for GraphicsError {
    fn from(err: IoError) -> Self {
        match err {
            IoError::InvalidInput => GraphicsError::InvalidInput,
            IoError::OutOfMemory => GraphicsError::OutOfMemory,
            IoError::Fault => GraphicsError::Fault,
            IoError::Unknown | IoError::Interrupted => GraphicsError::Unknown,
        }
    }
}

const FB_IOCTL_DRAW_RECT: u64 = 0x4642_0001;
const FB_IOCTL_RENDER: u64 = 0x4642_0002;
const FB_IOCTL_DRAW: u64 = 0x4642_0003;
const FB_IOCTL_SCREEN_INFO: u64 = 0x4642_0004;

#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct FramebufferRect {
    x: u64,
    y: u64,
    width: u64,
    height: u64,
    color: u32,
    _padding: u32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct FramebufferDraw {
    x: u64,
    y: u64,
    width: u64,
    height: u64,
    pixel_count: u64,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
struct FramebufferInfo {
    width: u32,
    height: u32,
}

static FRAMEBUFFER_FD: Mutex<Option<u64>> = Mutex::new(None);

fn framebuffer_fd() -> GraphicsResult<u64> {
    let mut guard = FRAMEBUFFER_FD.lock();
    if let Some(fd) = *guard {
        return Ok(fd);
    }

    match open("/dev/fb", 0) {
        Ok(fd) => {
            *guard = Some(fd);
            Ok(fd)
        }
        Err(err) => Err(GraphicsError::from(err)),
    }
}

fn framebuffer_ioctl_raw(
    request: u64,
    arg: u64,
    arg_len: usize,
    flags: u64,
) -> GraphicsResult<u64> {
    let fd = framebuffer_fd()?;
    fd_ioctl(fd, request, arg, arg_len, flags).map_err(GraphicsError::from)
}

pub type GraphicsResult<T> = Result<T, GraphicsError>;

/// Type-safe color representation (RGB format)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Color(u32);

impl Color {
    /// Create a new color from RGB components
    #[inline]
    pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
        Self(((r as u32) << 16) | ((g as u32) << 8) | (b as u32))
    }

    /// Get the raw u32 value
    pub const fn raw(self) -> u32 {
        self.0
    }

    /// Extract red component
    pub const fn red(self) -> u8 {
        ((self.0 >> 16) & 0xFF) as u8
    }

    /// Extract green component
    pub const fn green(self) -> u8 {
        ((self.0 >> 8) & 0xFF) as u8
    }

    /// Extract blue component
    pub const fn blue(self) -> u8 {
        (self.0 & 0xFF) as u8
    }

    // Common color constants
    pub const BLACK: Color = Color::from_rgb(0, 0, 0);
    pub const WHITE: Color = Color::from_rgb(255, 255, 255);
    pub const RED: Color = Color::from_rgb(255, 0, 0);
    pub const GREEN: Color = Color::from_rgb(0, 255, 0);
    pub const BLUE: Color = Color::from_rgb(0, 0, 255);
    pub const YELLOW: Color = Color::from_rgb(255, 255, 0);
    pub const CYAN: Color = Color::from_rgb(0, 255, 255);
    pub const MAGENTA: Color = Color::from_rgb(255, 0, 255);
}

impl From<u32> for Color {
    fn from(value: u32) -> Self {
        Self(value)
    }
}

impl From<Color> for u32 {
    fn from(color: Color) -> Self {
        color.0
    }
}

/// Rectangle structure for specifying regions
#[derive(Debug, Clone, Copy)]
pub struct Rect {
    pub x: u64,
    pub y: u64,
    pub width: u64,
    pub height: u64,
}

impl Rect {
    pub const fn new(x: u64, y: u64, width: u64, height: u64) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }
}

/// Text styling configuration
#[derive(Debug, Clone, Copy)]
pub struct TextStyle {
    pub font_weight: FontWeight,
    pub font_size: RasterHeight,
    pub foreground: Color,
    pub background: Option<Color>,
}

impl TextStyle {
    /// Create a new text style with default settings
    pub const fn new(foreground: Color) -> Self {
        Self {
            font_weight: noto_sans_mono_bitmap::FontWeight::Regular,
            font_size: noto_sans_mono_bitmap::RasterHeight::Size24,
            foreground,
            background: None,
        }
    }

    /// Set the font weight
    pub const fn with_weight(mut self, weight: FontWeight) -> Self {
        self.font_weight = weight;
        self
    }

    /// Set the font size
    pub const fn with_size(mut self, size: RasterHeight) -> Self {
        self.font_size = size;
        self
    }

    /// Set the background color (for opaque text rendering)
    pub const fn with_background(mut self, background: Color) -> Self {
        self.background = Some(background);
        self
    }
}

impl Default for TextStyle {
    fn default() -> Self {
        Self::new(Color::WHITE)
    }
}

/// Text rendering metrics and character information
#[derive(Debug, Clone, Copy)]
pub struct TextMetrics {
    pub char_width: u64,
    pub char_height: u64,
    pub line_height: u64,
    pub baseline: u64,
}

impl TextMetrics {
    /// Get text metrics for a specific font size
    pub fn for_size(size: RasterHeight) -> Self {
        let char_width = get_raster_width(noto_sans_mono_bitmap::FontWeight::Regular, size) as u64;
        let char_height = size as u64;
        let line_height = char_height + 2; // Add small spacing between lines
        let baseline = (char_height * 3) / 4; // Approximate baseline position

        Self {
            char_width,
            char_height,
            line_height,
            baseline,
        }
    }

    /// Calculate the bounds of a text string
    pub fn measure_string(&self, text: &str) -> Rect {
        let lines: Vec<&str> = text.lines().collect();
        let max_width = lines
            .iter()
            .map(|line| line.chars().count() as u64 * self.char_width)
            .max()
            .unwrap_or(0);
        let height = lines.len() as u64 * self.line_height;

        Rect::new(0, 0, max_width, height)
    }
}

/// Render a character at the specified position using bitmap font
#[inline]
fn render_character_at(
    pixels: &mut [u32],
    buffer_width: u64,
    buffer_height: u64,
    x: u64,
    y: u64,
    character: char,
    style: &TextStyle,
) -> GraphicsResult<()> {
    // Get the rasterized character data
    let raster = match get_raster(character, style.font_weight, style.font_size) {
        Some(raster) => raster,
        None => return Err(GraphicsError::UnsupportedCharacter),
    };

    let char_width = raster.width() as u64;
    let char_height = raster.height() as u64;

    // Check bounds
    if x + char_width > buffer_width || y + char_height > buffer_height {
        return Err(GraphicsError::OutOfBounds);
    }

    let raster_data = raster.raster();

    // Render each pixel of the character
    for char_y in 0..char_height {
        for char_x in 0..char_width {
            let pixel_x = x + char_x;
            let pixel_y = y + char_y;
            let buffer_index = (pixel_y * buffer_width + pixel_x) as usize;

            if buffer_index >= pixels.len() {
                continue;
            }

            // Get the intensity from the bitmap (0-255)
            let intensity = raster_data[char_y as usize][char_x as usize];

            if intensity == 0 {
                // Transparent pixel - only render background if specified
                if let Some(bg_color) = style.background {
                    pixels[buffer_index] = bg_color.raw();
                }
            } else {
                // Blend foreground based on intensity
                let current_color = Color::from(pixels[buffer_index]);
                let blended_color =
                    blend_text_pixel(current_color, style.foreground, intensity, style.background);
                pixels[buffer_index] = blended_color.raw();
            }
        }
    }

    Ok(())
}

/// Blend a text pixel with the background based on bitmap intensity
#[inline]
fn blend_text_pixel(
    background: Color,
    foreground: Color,
    intensity: u8,
    explicit_bg: Option<Color>,
) -> Color {
    // Use explicit background if provided, otherwise use current pixel
    let bg_color = explicit_bg.unwrap_or(background);

    if intensity == 255 {
        // Fully opaque - use foreground color
        foreground
    } else if intensity == 0 {
        // Fully transparent - use background color
        bg_color
    } else {
        // Blend based on intensity
        let alpha = intensity as u32;
        let inv_alpha = 255 - alpha;

        let r = (foreground.red() as u32 * alpha + bg_color.red() as u32 * inv_alpha) / 255;
        let g = (foreground.green() as u32 * alpha + bg_color.green() as u32 * inv_alpha) / 255;
        let b = (foreground.blue() as u32 * alpha + bg_color.blue() as u32 * inv_alpha) / 255;

        Color::from_rgb(r as u8, g as u8, b as u8)
    }
}

/// Render a string at the specified position
fn render_string_at(
    pixels: &mut [u32],
    buffer_width: u64,
    buffer_height: u64,
    x: u64,
    y: u64,
    text: &str,
    style: &TextStyle,
) -> GraphicsResult<()> {
    let metrics = TextMetrics::for_size(style.font_size);
    let mut current_x = x;
    let mut current_y = y;

    for character in text.chars() {
        if character == '\n' {
            // Move to next line
            current_x = x;
            current_y += metrics.line_height;
            continue;
        }

        if character == '\r' {
            // Carriage return - just reset x position
            current_x = x;
            continue;
        }

        // Check if character would fit horizontally
        if current_x + metrics.char_width > buffer_width {
            // Word wrapping - move to next line
            current_x = x;
            current_y += metrics.line_height;
        }

        // Check if we're still within vertical bounds
        if current_y + metrics.char_height > buffer_height {
            break; // Stop rendering if we're out of vertical space
        }

        // Render the character
        render_character_at(
            pixels,
            buffer_width,
            buffer_height,
            current_x,
            current_y,
            character,
            style,
        )?;

        // Move to next character position
        current_x += metrics.char_width;
    }

    Ok(())
}

/// Render multi-line text with word wrapping
fn render_text_wrapped(
    pixels: &mut [u32],
    buffer_width: u64,
    buffer_height: u64,
    x: u64,
    y: u64,
    text: &str,
    style: &TextStyle,
    wrap_width: u64,
) -> GraphicsResult<()> {
    let metrics = TextMetrics::for_size(style.font_size);
    let mut current_x = x;
    let mut current_y = y;

    let words: Vec<&str> = text.split_whitespace().collect();

    for word in words {
        let word_width = word.chars().count() as u64 * metrics.char_width;

        // Check if word fits on current line
        if current_x != x && current_x + word_width > x + wrap_width {
            // Move to next line
            current_x = x;
            current_y += metrics.line_height;
        }

        // Check vertical bounds
        if current_y + metrics.char_height > buffer_height {
            break;
        }

        // Render the word
        render_string_at(
            pixels,
            buffer_width,
            buffer_height,
            current_x,
            current_y,
            word,
            style,
        )?;

        // Move past the word and add space
        current_x += word_width + metrics.char_width; // Add space width
    }

    Ok(())
}

/// Texture struct for pixel buffer operations
#[derive(Debug, Clone)]
pub struct Texture {
    pub pixels: Vec<u32>,
    pub width: u64,
    pub height: u64,
}

impl Texture {
    /// Create a new empty texture with specified dimensions
    pub fn new(width: u64, height: u64) -> GraphicsResult<Self> {
        if width == 0 || height == 0 {
            return Err(GraphicsError::InvalidInput);
        }

        let pixel_count = width
            .checked_mul(height)
            .ok_or(GraphicsError::InvalidInput)? as usize;

        let pixels = alloc::vec![0; pixel_count];

        Ok(Self {
            pixels,
            width,
            height,
        })
    }

    /// Create a texture from existing pixel buffer
    pub fn from_buffer(width: u64, height: u64, pixels: Vec<u32>) -> GraphicsResult<Self> {
        if width == 0 || height == 0 {
            return Err(GraphicsError::InvalidInput);
        }

        let expected_len = width
            .checked_mul(height)
            .ok_or(GraphicsError::InvalidInput)? as usize;

        if pixels.len() != expected_len {
            return Err(GraphicsError::InvalidInput);
        }

        Ok(Self {
            pixels,
            width,
            height,
        })
    }

    /// Set a pixel at the given coordinates
    pub fn set_pixel(&mut self, x: u64, y: u64, color: Color) -> GraphicsResult<()> {
        if x >= self.width || y >= self.height {
            return Err(GraphicsError::OutOfBounds);
        }

        let index = (y * self.width + x) as usize;
        if index >= self.pixels.len() {
            return Err(GraphicsError::OutOfBounds);
        }

        self.pixels[index] = color.raw();
        Ok(())
    }

    /// Get a pixel color at the given coordinates
    pub fn get_pixel(&self, x: u64, y: u64) -> GraphicsResult<Color> {
        if x >= self.width || y >= self.height {
            return Err(GraphicsError::OutOfBounds);
        }

        let index = (y * self.width + x) as usize;
        if index >= self.pixels.len() {
            return Err(GraphicsError::OutOfBounds);
        }

        Ok(Color::from(self.pixels[index]))
    }

    /// Fill a rectangular area with a color
    pub fn fill_rect(
        &mut self,
        x: u64,
        y: u64,
        width: u64,
        height: u64,
        color: Color,
    ) -> GraphicsResult<()> {
        if x >= self.width || y >= self.height {
            return Err(GraphicsError::OutOfBounds);
        }

        let end_x = (x + width).min(self.width);
        let end_y = (y + height).min(self.height);

        for py in y..end_y {
            for px in x..end_x {
                self.set_pixel(px, py, color)?;
            }
        }
        Ok(())
    }

    /// Fill the entire texture with a color
    pub fn fill(&mut self, color: Color) {
        let raw_color = color.raw();
        for pixel in &mut self.pixels {
            *pixel = raw_color;
        }
    }

    /// Clear the texture (set all pixels to black)
    pub fn clear(&mut self) {
        self.fill(Color::BLACK);
    }

    /// Render a character at the specified position
    pub fn draw_char(
        &mut self,
        x: u64,
        y: u64,
        character: char,
        style: &TextStyle,
    ) -> GraphicsResult<()> {
        render_character_at(
            &mut self.pixels,
            self.width,
            self.height,
            x,
            y,
            character,
            style,
        )
    }

    /// Render text at the specified position
    pub fn draw_text(
        &mut self,
        x: u64,
        y: u64,
        text: &str,
        style: &TextStyle,
    ) -> GraphicsResult<()> {
        render_string_at(&mut self.pixels, self.width, self.height, x, y, text, style)
    }

    /// Render text with word wrapping within the specified width
    pub fn draw_text_wrapped(
        &mut self,
        x: u64,
        y: u64,
        text: &str,
        style: &TextStyle,
        wrap_width: u64,
    ) -> GraphicsResult<()> {
        render_text_wrapped(
            &mut self.pixels,
            self.width,
            self.height,
            x,
            y,
            text,
            style,
            wrap_width,
        )
    }

    /// Get text metrics for a given style
    pub fn text_metrics(style: &TextStyle) -> TextMetrics {
        TextMetrics::for_size(style.font_size)
    }

    /// Measure the bounds of text without rendering it
    pub fn measure_text(text: &str, style: &TextStyle) -> Rect {
        let metrics = TextMetrics::for_size(style.font_size);
        metrics.measure_string(text)
    }
}

/// Blending modes for texture operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlendMode {
    /// Replace destination with source
    Replace,
    /// Blend based on RGB intensity (lighter colors have more influence)
    IntensityBlend,
    /// Add source to destination
    Add,
    /// Multiply source with destination
    Multiply,
}

impl BlendMode {
    /// Apply blending between source and destination colors
    pub fn blend(self, src: Color, dst: Color) -> Color {
        match self {
            BlendMode::Replace => src,
            BlendMode::IntensityBlend => {
                // Calculate intensity (brightness) of source color
                let src_intensity = (src.red() as u32 + src.green() as u32 + src.blue() as u32) / 3;
                let dst_intensity = (dst.red() as u32 + dst.green() as u32 + dst.blue() as u32) / 3;

                // Blend factor based on relative intensities (0-255)
                let total_intensity = src_intensity + dst_intensity;
                if total_intensity == 0 {
                    Color::from_rgb(0, 0, 0)
                } else {
                    let src_factor = (src_intensity * 255) / total_intensity;
                    let dst_factor = 255 - src_factor;

                    let r = (src.red() as u32 * src_factor + dst.red() as u32 * dst_factor) / 255;
                    let g =
                        (src.green() as u32 * src_factor + dst.green() as u32 * dst_factor) / 255;
                    let b = (src.blue() as u32 * src_factor + dst.blue() as u32 * dst_factor) / 255;

                    Color::from_rgb(r as u8, g as u8, b as u8)
                }
            }
            BlendMode::Add => {
                let r = (src.red() as u32 + dst.red() as u32).min(255);
                let g = (src.green() as u32 + dst.green() as u32).min(255);
                let b = (src.blue() as u32 + dst.blue() as u32).min(255);

                Color::from_rgb(r as u8, g as u8, b as u8)
            }
            BlendMode::Multiply => {
                let r = (src.red() as u32 * dst.red() as u32) / 255;
                let g = (src.green() as u32 * dst.green() as u32) / 255;
                let b = (src.blue() as u32 * dst.blue() as u32) / 255;

                Color::from_rgb(r as u8, g as u8, b as u8)
            }
        }
    }
}

/// Draw a rectangle directly to the screen
pub fn draw_rect(x: u64, y: u64, width: u64, height: u64, color: Color) -> GraphicsResult<()> {
    if width == 0 || height == 0 {
        return Err(GraphicsError::InvalidInput);
    }

    let mut rect = FramebufferRect {
        x,
        y,
        width,
        height,
        color: color.raw(),
        _padding: 0,
    };

    framebuffer_ioctl_raw(
        FB_IOCTL_DRAW_RECT,
        (&mut rect as *mut FramebufferRect) as u64,
        core::mem::size_of::<FramebufferRect>(),
        IOCTL_ARG_IN,
    )?;

    Ok(())
}

/// Render all pending draw operations to the screen
pub fn render() -> GraphicsResult<()> {
    framebuffer_ioctl_raw(FB_IOCTL_RENDER, 0, 0, 0)?;
    Ok(())
}

/// Get screen information
pub fn screen_info() -> GraphicsResult<ScreenInfo> {
    let mut info = FramebufferInfo::default();
    framebuffer_ioctl_raw(
        FB_IOCTL_SCREEN_INFO,
        (&mut info as *mut FramebufferInfo) as u64,
        core::mem::size_of::<FramebufferInfo>(),
        IOCTL_ARG_OUT,
    )?;

    Ok(ScreenInfo {
        width: info.width as usize,
        height: info.height as usize,
    })
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct ScreenInfo {
    pub width: usize,
    pub height: usize,
}

#[derive(Debug, Clone)]
pub struct DrawRequest {
    pub pixels: Vec<u32>,
    pub x: u64,
    pub y: u64,
    pub width: u64,
    pub height: u64,
}

impl DrawRequest {
    /// Create a new DrawRequest with specified dimensions at origin (0,0)
    pub fn new(width: u64, height: u64) -> GraphicsResult<Self> {
        if width == 0 || height == 0 {
            return Err(GraphicsError::InvalidInput);
        }

        let pixel_count = width
            .checked_mul(height)
            .ok_or(GraphicsError::InvalidInput)? as usize;

        let pixels = alloc::vec![0; pixel_count];

        Ok(Self {
            pixels,
            x: 0,
            y: 0,
            width,
            height,
        })
    }

    /// Set the position where this DrawRequest will be drawn
    pub fn with_position(mut self, x: u64, y: u64) -> Self {
        self.x = x;
        self.y = y;
        self
    }

    /// Set a pixel at the given coordinates within this DrawRequest
    pub fn set_pixel(&mut self, x: u64, y: u64, color: Color) -> GraphicsResult<()> {
        if x >= self.width || y >= self.height {
            return Err(GraphicsError::OutOfBounds);
        }

        let index = (y * self.width + x) as usize;
        if index >= self.pixels.len() {
            return Err(GraphicsError::OutOfBounds);
        }

        self.pixels[index] = color.raw();
        Ok(())
    }

    /// Get a pixel color at the given coordinates
    pub fn get_pixel(&self, x: u64, y: u64) -> GraphicsResult<Color> {
        if x >= self.width || y >= self.height {
            return Err(GraphicsError::OutOfBounds);
        }

        let index = (y * self.width + x) as usize;
        if index >= self.pixels.len() {
            return Err(GraphicsError::OutOfBounds);
        }

        Ok(Color::from(self.pixels[index]))
    }

    /// Fill a rectangular area with a color
    pub fn fill_rect(
        &mut self,
        x: u64,
        y: u64,
        width: u64,
        height: u64,
        color: Color,
    ) -> GraphicsResult<()> {
        if x >= self.width || y >= self.height {
            return Err(GraphicsError::OutOfBounds);
        }

        let end_x = (x + width).min(self.width);
        let end_y = (y + height).min(self.height);

        for py in y..end_y {
            for px in x..end_x {
                self.set_pixel(px, py, color)?;
            }
        }
        Ok(())
    }

    /// Fill the entire DrawRequest with a color
    pub fn fill(&mut self, color: Color) {
        let raw_color = color.raw();
        for pixel in &mut self.pixels {
            *pixel = raw_color;
        }
    }

    /// Clear the DrawRequest (set all pixels to black)
    pub fn clear(&mut self) {
        self.fill(Color::BLACK);
    }

    /// Draw a line from (x1, y1) to (x2, y2) using Bresenham's algorithm
    pub fn draw_line(
        &mut self,
        x1: u64,
        y1: u64,
        x2: u64,
        y2: u64,
        color: Color,
    ) -> GraphicsResult<()> {
        let mut x1 = x1 as i64;
        let mut y1 = y1 as i64;
        let x2 = x2 as i64;
        let y2 = y2 as i64;

        let dx = (x2 - x1).abs();
        let dy = (y2 - y1).abs();
        let sx = if x1 < x2 { 1 } else { -1 };
        let sy = if y1 < y2 { 1 } else { -1 };
        let mut err = dx - dy;

        loop {
            if x1 >= 0 && y1 >= 0 && x1 < self.width as i64 && y1 < self.height as i64 {
                self.set_pixel(x1 as u64, y1 as u64, color)?;
            }

            if x1 == x2 && y1 == y2 {
                break;
            }

            let e2 = 2 * err;
            if e2 > -dy {
                err -= dy;
                x1 += sx;
            }
            if e2 < dx {
                err += dx;
                y1 += sy;
            }
        }
        Ok(())
    }

    /// Draw a circle outline at (cx, cy) with given radius
    pub fn draw_circle(
        &mut self,
        cx: u64,
        cy: u64,
        radius: u64,
        color: Color,
    ) -> GraphicsResult<()> {
        let cx = cx as i64;
        let cy = cy as i64;
        let radius = radius as i64;

        let mut x = radius;
        let mut y = 0i64;
        let mut err = 0i64;

        while x >= y {
            // Plot 8 octants
            let points = [
                (cx + x, cy + y),
                (cx + y, cy + x),
                (cx - y, cy + x),
                (cx - x, cy + y),
                (cx - x, cy - y),
                (cx - y, cy - x),
                (cx + y, cy - x),
                (cx + x, cy - y),
            ];

            for (px, py) in points.iter() {
                if *px >= 0 && *py >= 0 && (*px as u64) < self.width && (*py as u64) < self.height {
                    self.set_pixel(*px as u64, *py as u64, color)?;
                }
            }

            if err <= 0 {
                y += 1;
                err += 2 * y + 1;
            }
            if err > 0 {
                x -= 1;
                err -= 2 * x + 1;
            }
        }
        Ok(())
    }

    /// Fill a circle at (cx, cy) with given radius
    pub fn fill_circle(
        &mut self,
        cx: u64,
        cy: u64,
        radius: u64,
        color: Color,
    ) -> GraphicsResult<()> {
        let cx = cx as i64;
        let cy = cy as i64;
        let radius = radius as i64;

        for y in (cy - radius)..=(cy + radius) {
            if y < 0 || y >= self.height as i64 {
                continue;
            }

            let dy = y - cy;
            let dy_squared = dy * dy;
            let under_sqrt = radius * radius - dy_squared;

            if under_sqrt < 0 {
                continue;
            }

            let dx = isqrt(under_sqrt as u64) as i64;

            let start = (cx - dx).max(0) as u64;
            let end = (cx + dx).min(self.width as i64 - 1) as u64;

            if start <= end {
                self.fill_rect(start, y as u64, end - start + 1, 1, color)?;
            }
        }
        Ok(())
    }

    /// Blit a texture to this DrawRequest at the specified position
    pub fn blit_texture(
        &mut self,
        texture: &Texture,
        dst_x: u64,
        dst_y: u64,
    ) -> GraphicsResult<()> {
        self.blit_texture_with_blend(texture, None, dst_x, dst_y, BlendMode::Replace)
    }

    /// Blit a texture region to this DrawRequest at the specified position
    pub fn blit_texture_region(
        &mut self,
        texture: &Texture,
        src_rect: Rect,
        dst_x: u64,
        dst_y: u64,
    ) -> GraphicsResult<()> {
        self.blit_texture_with_blend(texture, Some(src_rect), dst_x, dst_y, BlendMode::Replace)
    }

    /// Blit a texture with intensity blending
    pub fn blit_texture_intensity(
        &mut self,
        texture: &Texture,
        dst_x: u64,
        dst_y: u64,
    ) -> GraphicsResult<()> {
        self.blit_texture_with_blend(texture, None, dst_x, dst_y, BlendMode::IntensityBlend)
    }

    /// Blit a texture with custom blending mode
    pub fn blit_texture_with_blend(
        &mut self,
        texture: &Texture,
        src_rect: Option<Rect>,
        dst_x: u64,
        dst_y: u64,
        blend_mode: BlendMode,
    ) -> GraphicsResult<()> {
        // Determine source region
        let (src_x, src_y, src_width, src_height) = match src_rect {
            Some(rect) => (rect.x, rect.y, rect.width, rect.height),
            None => (0, 0, texture.width, texture.height),
        };

        // Bounds check source region
        if src_x >= texture.width || src_y >= texture.height {
            return Err(GraphicsError::OutOfBounds);
        }

        let src_end_x = (src_x + src_width).min(texture.width);
        let src_end_y = (src_y + src_height).min(texture.height);

        // Copy pixels with blending
        for src_py in src_y..src_end_y {
            for src_px in src_x..src_end_x {
                let dst_px = dst_x + (src_px - src_x);
                let dst_py = dst_y + (src_py - src_y);

                // Skip if destination is out of bounds
                if dst_px >= self.width || dst_py >= self.height {
                    continue;
                }

                let src_color = texture.get_pixel(src_px, src_py)?;

                match blend_mode {
                    BlendMode::Replace => {
                        self.set_pixel(dst_px, dst_py, src_color)?;
                    }
                    _ => {
                        let dst_color = self.get_pixel(dst_px, dst_py)?;
                        let blended = blend_mode.blend(src_color, dst_color);
                        self.set_pixel(dst_px, dst_py, blended)?;
                    }
                }
            }
        }

        Ok(())
    }

    /// Blit raw pixel data to this DrawRequest
    pub fn blit_pixels(
        &mut self,
        pixels: &[u32],
        width: u64,
        height: u64,
        dst_x: u64,
        dst_y: u64,
    ) -> GraphicsResult<()> {
        let texture = Texture::from_buffer(width, height, pixels.to_vec())?;
        self.blit_texture(&texture, dst_x, dst_y)
    }

    /// Blit with scaling (simple nearest neighbor)
    pub fn blit_texture_scaled(
        &mut self,
        texture: &Texture,
        src_rect: Option<Rect>,
        dst_rect: Rect,
    ) -> GraphicsResult<()> {
        let (src_x, src_y, src_width, src_height) = match src_rect {
            Some(rect) => (rect.x, rect.y, rect.width, rect.height),
            None => (0, 0, texture.width, texture.height),
        };

        if src_width == 0 || src_height == 0 || dst_rect.width == 0 || dst_rect.height == 0 {
            return Ok(());
        }

        // Simple nearest neighbor scaling
        for dst_py in 0..dst_rect.height {
            for dst_px in 0..dst_rect.width {
                let src_px = src_x + (dst_px * src_width / dst_rect.width);
                let src_py = src_y + (dst_py * src_height / dst_rect.height);

                if src_px < texture.width && src_py < texture.height {
                    let color = texture.get_pixel(src_px, src_py)?;
                    let final_x = dst_rect.x + dst_px;
                    let final_y = dst_rect.y + dst_py;

                    if final_x < self.width && final_y < self.height {
                        self.set_pixel(final_x, final_y, color)?;
                    }
                }
            }
        }

        Ok(())
    }

    /// Draw this request to the screen
    pub fn draw(&self) -> GraphicsResult<()> {
        let pixel_count = self
            .width
            .checked_mul(self.height)
            .ok_or(GraphicsError::InvalidInput)?;

        if pixel_count == 0 {
            return Ok(());
        }

        let header = FramebufferDraw {
            x: self.x,
            y: self.y,
            width: self.width,
            height: self.height,
            pixel_count,
        };

        let header_bytes = core::mem::size_of::<FramebufferDraw>();
        let pixel_bytes = (pixel_count as usize)
            .checked_mul(core::mem::size_of::<u32>())
            .ok_or(GraphicsError::InvalidInput)?;

        let mut buffer = Vec::with_capacity(header_bytes + pixel_bytes);

        buffer.extend_from_slice(unsafe {
            core::slice::from_raw_parts(
                (&header as *const FramebufferDraw) as *const u8,
                header_bytes,
            )
        });
        buffer.extend_from_slice(unsafe {
            core::slice::from_raw_parts(self.pixels.as_ptr() as *const u8, pixel_bytes)
        });

        framebuffer_ioctl_raw(
            FB_IOCTL_DRAW,
            buffer.as_mut_ptr() as u64,
            buffer.len(),
            IOCTL_ARG_IN,
        )?;

        Ok(())
    }

    /// Render a character at the specified position
    pub fn draw_char(
        &mut self,
        x: u64,
        y: u64,
        character: char,
        style: &TextStyle,
    ) -> GraphicsResult<()> {
        render_character_at(
            &mut self.pixels,
            self.width,
            self.height,
            x,
            y,
            character,
            style,
        )
    }

    /// Render text at the specified position
    pub fn draw_text(
        &mut self,
        x: u64,
        y: u64,
        text: &str,
        style: &TextStyle,
    ) -> GraphicsResult<()> {
        render_string_at(&mut self.pixels, self.width, self.height, x, y, text, style)
    }

    /// Render text with word wrapping within the specified width
    pub fn draw_text_wrapped(
        &mut self,
        x: u64,
        y: u64,
        text: &str,
        style: &TextStyle,
        wrap_width: u64,
    ) -> GraphicsResult<()> {
        render_text_wrapped(
            &mut self.pixels,
            self.width,
            self.height,
            x,
            y,
            text,
            style,
            wrap_width,
        )
    }
}

/// Screen management struct providing convenient graphics operations
pub struct Screen {
    info: ScreenInfo,
    back_buffer: Option<DrawRequest>,
    dirty: bool,
}

impl Screen {
    /// Get the global screen instance
    pub fn get() -> GraphicsResult<Self> {
        let info = screen_info()?;
        Ok(Self {
            info,
            back_buffer: None,
            dirty: false,
        })
    }

    /// Get screen width
    pub fn width(&self) -> usize {
        self.info.width
    }

    /// Get screen height
    pub fn height(&self) -> usize {
        self.info.height
    }

    /// Get screen info
    pub fn info(&self) -> &ScreenInfo {
        &self.info
    }

    /// Ensure the back buffer is initialized
    fn ensure_back_buffer(&mut self) -> GraphicsResult<()> {
        if self.back_buffer.is_none() {
            let mut buffer = DrawRequest::new(self.width() as u64, self.height() as u64)?;
            buffer.clear(); // Initialize with black background
            self.back_buffer = Some(buffer);
        }
        Ok(())
    }

    /// Draw a rectangle on the screen
    pub fn draw_rect(
        &mut self,
        x: u64,
        y: u64,
        width: u64,
        height: u64,
        color: Color,
    ) -> GraphicsResult<()> {
        self.ensure_back_buffer()?;

        if let Some(ref mut buffer) = self.back_buffer {
            buffer.fill_rect(x, y, width, height, color)?;
            self.dirty = true;
        }

        Ok(())
    }

    /// Fill the entire screen with a color
    pub fn fill(&mut self, color: Color) -> GraphicsResult<()> {
        self.ensure_back_buffer()?;

        if let Some(ref mut buffer) = self.back_buffer {
            buffer.fill(color);
            self.dirty = true;
        }

        Ok(())
    }

    /// Clear the screen (fill with black)
    pub fn clear(&mut self) -> GraphicsResult<()> {
        self.fill(Color::BLACK)
    }

    /// Render all pending operations
    pub fn render(&mut self) -> GraphicsResult<()> {
        // Only render if we have a dirty back buffer
        if self.dirty
            && let Some(ref buffer) = self.back_buffer
        {
            buffer.draw()?;
            self.dirty = false;
        }

        // Always call the final render syscall to present to screen
        render()
    }

    /// Create a new DrawRequest that fits entirely on screen
    pub fn create_draw_request(&self, width: u64, height: u64) -> GraphicsResult<DrawRequest> {
        if width > self.width() as u64 || height > self.height() as u64 {
            return Err(GraphicsError::OutOfBounds);
        }
        DrawRequest::new(width, height)
    }

    /// Draw a texture directly to the screen at the specified position
    pub fn draw_texture(&self, texture: &Texture, x: u64, y: u64) -> GraphicsResult<()> {
        let mut draw_req = DrawRequest::new(texture.width, texture.height)?;
        draw_req.blit_texture(texture, 0, 0)?;
        draw_req = draw_req.with_position(x, y);
        draw_req.draw()
    }

    /// Draw a texture region directly to the screen
    pub fn draw_texture_region(
        &self,
        texture: &Texture,
        src_rect: Rect,
        x: u64,
        y: u64,
    ) -> GraphicsResult<()> {
        let mut draw_req = DrawRequest::new(src_rect.width, src_rect.height)?;
        draw_req.blit_texture_region(texture, src_rect, 0, 0)?;
        draw_req = draw_req.with_position(x, y);
        draw_req.draw()
    }

    /// Draw a texture with intensity blending directly to the screen
    pub fn draw_texture_intensity(&self, texture: &Texture, x: u64, y: u64) -> GraphicsResult<()> {
        let mut draw_req = DrawRequest::new(texture.width, texture.height)?;
        draw_req.blit_texture_intensity(texture, 0, 0)?;
        draw_req = draw_req.with_position(x, y);
        draw_req.draw()
    }

    /// Draw a texture with scaling directly to the screen
    pub fn draw_texture_scaled(&self, texture: &Texture, dst_rect: Rect) -> GraphicsResult<()> {
        let mut draw_req = DrawRequest::new(dst_rect.width, dst_rect.height)?;
        draw_req.blit_texture_scaled(
            texture,
            None,
            Rect::new(0, 0, dst_rect.width, dst_rect.height),
        )?;
        draw_req = draw_req.with_position(dst_rect.x, dst_rect.y);
        draw_req.draw()
    }

    /// Create a texture from the screen contents (screenshot)
    pub fn capture_region(&self, _region: Rect) -> GraphicsResult<Texture> {
        // This would require a new syscall to read from framebuffer
        // For now, return an error as this functionality isn't implemented
        Err(GraphicsError::Unknown)
    }

    /// Draw text directly to the screen
    pub fn draw_text(
        &mut self,
        x: u64,
        y: u64,
        text: &str,
        style: &TextStyle,
    ) -> GraphicsResult<()> {
        self.ensure_back_buffer()?;

        if let Some(ref mut buffer) = self.back_buffer {
            buffer.draw_text(x, y, text, style)?;
            self.dirty = true;
        }

        Ok(())
    }

    /// Draw text with word wrapping directly to the screen
    pub fn draw_text_wrapped(
        &mut self,
        x: u64,
        y: u64,
        text: &str,
        style: &TextStyle,
        wrap_width: u64,
    ) -> GraphicsResult<()> {
        self.ensure_back_buffer()?;

        if let Some(ref mut buffer) = self.back_buffer {
            buffer.draw_text_wrapped(x, y, text, style, wrap_width)?;
            self.dirty = true;
        }

        Ok(())
    }

    /// Draw a single character directly to the screen
    pub fn draw_char(
        &mut self,
        x: u64,
        y: u64,
        character: char,
        style: &TextStyle,
    ) -> GraphicsResult<()> {
        self.ensure_back_buffer()?;

        if let Some(ref mut buffer) = self.back_buffer {
            buffer.draw_char(x, y, character, style)?;
            self.dirty = true;
        }

        Ok(())
    }
}

/// Get the global screen instance (convenience function)
pub fn screen() -> GraphicsResult<Screen> {
    Screen::get()
}