poster_generator 0.1.2

A poster generation library based on Skia Safe with RTL text support for Arabic, Hebrew, Persian, and Uyghur
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
//! A poster generation library based on Skia Safe.
//!
//! This library provides a flexible way to create poster images with text and image elements,
//! supporting RTL (Right-to-Left) languages like Arabic, Hebrew, Persian, and Uy ghur.
//!
//! # Features
//!
//! - Create customizable poster canvas with configurable width and height
//! - Background elements with colors, images, and rounded corners
//! - Image elements with positioning, scaling (cover/contain/stretch), and rounded corners
//! - Text elements with:
//!   - Multi-line text with automatic word wrapping
//!   - RTL/LTR text direction support
//!   - Custom fonts and styling
//!   - Text backgrounds with padding and border radius
//!   - Z-index layering
//! - Export as PNG file or base64 encoded string
//!
//! # Example
//!
//! ```
//! use poster_generator::{PosterGenerator, TextElement, TextAlignType, TextDirectionType};
//!
//! let mut generator = PosterGenerator::new(800, 600, "#ffffff".to_string());
//!
//! let text = TextElement {
//!     text: "Hello, World!".to_string(),
//!     x: 400.0,
//!     y: 300.0,
//!     font_size: 48.0,
//!     color: "#333333".to_string(),
//!     align: TextAlignType::Center,
//!     font_family: None,
//!     max_width: None,
//!     line_height: 1.5,
//!     max_lines: None,
//!     z_index: Some(1),
//!     bold: true,
//!     prefix: None,
//!     background_color: None,
//!     padding: 0.0,
//!     border_radius: None,
//!     width: None,
//!     height: None,
//!     direction: TextDirectionType::Ltr,
//! };
//!
//! generator.add_text(text);
//! generator.generate_file("output.png").expect("Failed to generate poster");
//! ```

use anyhow::Result;
use base64::{engine::general_purpose, Engine};
use serde::{Deserialize, Serialize};
use std::path::Path;
use skia_safe::{
    Canvas, Color, Data, EncodedImageFormat, Font,
    FontMgr, FontStyle, Image, Paint, Path as SkPath, Point, Rect,
    TextBlob,
    textlayout::{FontCollection, ParagraphBuilder, ParagraphStyle, TextAlign, TextDirection, TextStyle}
};
use thiserror::Error;

/// Custom error type for poster generation.
#[derive(Error, Debug)]
pub enum PosterError {
    /// Error occurred while loading or decoding an image.
    #[error("Failed to load image: {0}")]
    ImageLoadError(String),

    /// Error occurred during the rendering process.
    #[error("Failed to render element: {0}")]
    RenderError(String),

    /// Error occurred while encoding or saving output.
    #[error("Failed to generate output: {0}")]
    OutputError(String),
}

/// Main configuration structure for poster generation.
///
/// # Example
///
/// ```
/// use poster_generator::{PosterConfig, Element, TextElement, TextAlignType, TextDirectionType};
///
/// let config = PosterConfig {
///     width: 800,
///     height: 600,
///     background_color: "#ffffff".to_string(),
///     elements: vec![
///         Element::Text(TextElement {
///             text: "Sample Text".to_string(),
///             x: 400.0,
///             y: 300.0,
///             font_size: 32.0,
///             color: "#000000".to_string(),
///             align: TextAlignType::Center,
///             ..Default::default()
///         }),
///     ],
/// };
/// ```
#[derive(Debug, Deserialize, Serialize)]
pub struct PosterConfig {
    /// Canvas width in pixels.
    pub width: u32,
    /// Canvas height in pixels.
    pub height: u32,
    /// Background color in hex format (e.g., "#ffffff" or "#ffffffff" with alpha).
    pub background_color: String,
    /// List of elements to render on the poster.
    pub elements: Vec<Element>,
}

/// Poster element types.
///
/// Elements are rendered in order of their z-index (lowest to highest).
#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum Element {
    /// Background element (always rendered first).
    #[serde(rename = "background")]
    Background(BackgroundElement),

    /// Image element.
    #[serde(rename = "image")]
    Image(ImageElement),

    /// Text element with RTL support.
    #[serde(rename = "text")]
    Text(TextElement),
}

/// Background element configuration.
///
/// The background element fills the entire canvas and supports both solid colors and images.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct BackgroundElement {
    /// Optional background image path or base64 data URL.
    pub image: Option<String>,
    /// Background color in hex format.
    pub color: String,
    /// Optional border radius for rounded corners.
    pub radius: Option<Radius>,
}

/// Image element configuration.
///
/// Supports various scaling modes and rounded corners.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ImageElement {
    /// Image source: file path or base64 data URL.
    pub src: String,
    /// X-coordinate of the image (top-left corner).
    pub x: f32,
    /// Y-coordinate of the image (top-left corner).
    pub y: f32,
    /// Width of the image container.
    pub width: f32,
    /// Height of the image container.
    pub height: f32,
    /// Optional border radius for rounded corners.
    pub radius: Option<Radius>,
    /// Z-index for layering (higher values are rendered on top).
    pub z_index: Option<i32>,
    /// Image scaling mode.
    #[serde(default = "default_object_fit")]
    pub object_fit: ObjectFit,
}

/// Text element configuration with RTL support.
///
/// Supports multi-line text, custom fonts, and automatic RTL detection for Arabic, Hebrew, and Uyghur scripts.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct TextElement {
    /// Text content to render.
    pub text: String,
    /// X-coordinate of the text anchor point.
    pub x: f32,
    /// Y-coordinate of the text baseline.
    pub y: f32,
    /// Font size in points.
    pub font_size: f32,
    /// Text color in hex format.
    pub color: String,
    /// Text alignment.
    #[serde(default = "default_text_align")]
    pub align: TextAlignType,
    /// Optional font family name from system fonts (e.g., "Arial", "PingFang SC").
    pub font_family: Option<String>,
    /// Optional font file path (e.g., "fonts/custom.ttf", "UKIJBasma.ttf").
    /// Takes priority over font_family if both are specified.
    pub font_file: Option<String>,
    /// Maximum width for text wrapping. If None, text is rendered on a single line.
    pub max_width: Option<f32>,
    /// Line height multiplier (e.g., 1.5 = 150% of font size).
    #[serde(default = "default_line_height")]
    pub line_height: f32,
    /// Maximum number of lines. Text exceeding this will be truncated with ellipsis.
    pub max_lines: Option<u32>,
    /// Z-index for layering.
    pub z_index: Option<i32>,
    /// Whether to use bold font weight.
    #[serde(default = "default_bold")]
    pub bold: bool,
    /// Optional prefix to prepend to the text (e.g., currency symbol).
    pub prefix: Option<String>,
    /// Optional background color for the text box.
    pub background_color: Option<String>,
    /// Padding around the text when background color is set.
    #[serde(default = "default_padding")]
    pub padding: f32,
    /// Optional border radius for the text background.
    pub border_radius: Option<Radius>,
    /// Optional fixed width for the text box.
    pub width: Option<f32>,
    /// Optional fixed height for the text box.
    pub height: Option<f32>,
    /// Text direction (LTR or RTL). Automatically detected if set to LTR.
    #[serde(default = "default_text_direction")]
    pub direction: TextDirectionType,
}

impl Default for TextElement {
    fn default() -> Self {
        Self {
            text: String::new(),
            x: 0.0,
            y: 0.0,
            font_size: 16.0,
            color: "#000000".to_string(),
            align: TextAlignType::Left,
            font_family: None,
            font_file: None,
            max_width: None,
            line_height: 1.5,
            max_lines: None,
            z_index: None,
            bold: false,
            prefix: None,
            background_color: None,
            padding: 0.0,
            border_radius: None,
            width: None,
            height: None,
            direction: TextDirectionType::Ltr,
        }
    }
}

/// Border radius configuration.
///
/// Can be either a single value for all corners or individual values for each corner.
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum Radius {
    /// Single radius value applied to all corners.
    Single(f32),
    /// Individual radius values: [top-left, top-right, bottom-right, bottom-left].
    Multiple([f32; 4]),
}

/// Image scaling mode.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ObjectFit {
    /// Scale and crop the image to fill the container while maintaining aspect ratio.
    Cover,
    /// Scale the image to fit within the container while maintaining aspect ratio.
    Contain,
    /// Stretch the image to fill the container (may distort).
    Stretch,
}

/// Text alignment options.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum TextAlignType {
    /// Align text to the left.
    Left,
    /// Center align text.
    Center,
    /// Align text to the right.
    Right,
}

/// Text direction for bi-directional text support.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum TextDirectionType {
    /// Left-to-right text direction (default). RTL scripts are automatically detected.
    Ltr,
    /// Right-to-left text direction (for Arabic, Hebrew, Uyghur, etc.).
    Rtl,
}

// Utility function to detect RTL/Arabic script text
fn is_rtl_text(text: &str) -> bool {
    // Check for Arabic/Persian/Uyghur/Hebrew Unicode ranges
    text.chars().any(|c| {
        let code = c as u32;
        // Arabic: U+0600-U+06FF
        // Arabic Supplement: U+0750-U+077F
        // Arabic Extended-A: U+08A0-U+08FF
        // Arabic Presentation Forms-A: U+FB50-U+FDFF
        // Arabic Presentation Forms-B: U+FE70-U+FEFF
        // Hebrew: U+0590-U+05FF
        (code >= 0x0600 && code <= 0x06FF) ||
        (code >= 0x0750 && code <= 0x077F) ||
        (code >= 0x08A0 && code <= 0x08FF) ||
        (code >= 0xFB50 && code <= 0xFDFF) ||
        (code >= 0xFE70 && code <= 0xFEFF) ||
        (code >= 0x0590 && code <= 0x05FF)  // Hebrew
    })
}

// Function to load font from file
fn load_font_from_file(font_path: &str, font_size: f32) -> Option<Font> {
    use std::path::Path as StdPath;

    // Try multiple possible paths to handle different working directories
    let paths_to_try = vec![
        font_path.to_string(),           // Original path
        format!("./{}", font_path),      // Current directory
        format!("../{}", font_path),     // Parent directory
    ];

    for try_path in &paths_to_try {
        if !StdPath::new(try_path).exists() {
            continue;
        }

        if let Ok(font_bytes) = std::fs::read(try_path) {
            // Use Skia API: Data::new_copy() -> FontMgr::new_from_data()
            let font_data = Data::new_copy(&font_bytes);
            let font_mgr = FontMgr::new();

            if let Some(typeface) = font_mgr.new_from_data(&font_data, None) {
                return Some(Font::from_typeface(typeface, font_size));
            }
        }
    }

    None
}

// Function to get appropriate font for text with optional font family or font file
fn get_font_for_text_with_family(_text: &str, font_size: f32, bold: bool, font_family: Option<&str>, font_file: Option<&str>) -> Font {
    let font_mgr = FontMgr::default();

    let weight = if bold {
        skia_safe::font_style::Weight::BOLD
    } else {
        skia_safe::font_style::Weight::NORMAL
    };

    let font_style = FontStyle::new(weight, skia_safe::font_style::Width::NORMAL, skia_safe::font_style::Slant::Upright);

    // 1. Priority: User-specified font file
    if let Some(file_path) = font_file {
        if let Some(font) = load_font_from_file(file_path, font_size) {
            return font;
        }
    }

    // 2. Next: User-specified font family
    if let Some(family) = font_family {
        if let Some(typeface) = font_mgr.match_family_style(family, font_style) {
            return Font::new(typeface, font_size);
        }
    }

    // 3. Finally: Simple universal fallback fonts
    let default_fonts = vec![
        "Arial Unicode MS",  // Best Unicode coverage
        "Arial",
        "Helvetica",
        "Times New Roman",
    ];

    for family in default_fonts {
        if let Some(typeface) = font_mgr.match_family_style(family, font_style) {
            return Font::new(typeface, font_size);
        }
    }

    // Fallback to default font
    let font_mgr = FontMgr::default();
    if let Some(typeface) = font_mgr.legacy_make_typeface(None, FontStyle::normal()) {
        Font::new(typeface, font_size)
    } else {
        // Last resort - create a font from system default typeface
        let system_mgr = FontMgr::new();
        if let Some(default_typeface) = system_mgr.legacy_make_typeface(None, FontStyle::normal()) {
            Font::new(default_typeface, font_size)
        } else {
            // Very last resort - use built-in default
            Font::default()
        }
    }
}

// Default values
fn default_object_fit() -> ObjectFit {
    ObjectFit::Cover
}

fn default_text_align() -> TextAlignType {
    TextAlignType::Left
}

fn default_line_height() -> f32 {
    1.5
}

fn default_bold() -> bool {
    false
}

fn default_padding() -> f32 {
    0.0
}

fn default_text_direction() -> TextDirectionType {
    TextDirectionType::Ltr
}

/// Main poster generator.
///
/// This is the primary struct for creating posters. Elements are rendered in z-index order.
///
/// # Example
///
/// ```
/// use poster_generator::{PosterGenerator, TextElement, TextAlignType, TextDirectionType};
///
/// let mut generator = PosterGenerator::new(800, 600, "#f0f0f0".to_string());
///
/// let text = TextElement {
///     text: "مرحبا بالعالم".to_string(), // Arabic: Hello World
///     x: 400.0,
///     y: 300.0,
///     font_size: 48.0,
///     color: "#333333".to_string(),
///     align: TextAlignType::Center,
///     direction: TextDirectionType::Rtl,
///     ..Default::default()
/// };
///
/// generator.add_text(text);
/// let png_data = generator.generate().expect("Failed to generate");
/// ```
pub struct PosterGenerator {
    width: u32,
    height: u32,
    background_color: String,
    elements: Vec<Box<dyn PosterElement>>,
}

// Element trait
trait PosterElement {
    fn z_index(&self) -> i32;
    fn render(&self, canvas: &Canvas) -> Result<()>;
}

// Implement background element
impl PosterElement for BackgroundElement {
    fn z_index(&self) -> i32 {
        -1000 // Background always at the bottom
    }
    
    fn render(&self, canvas: &Canvas) -> Result<()> {
        // Parse color
        let color = parse_color(&self.color);
        
        // Create paint
        let mut paint = Paint::default();
        paint.set_color(color);
        paint.set_anti_alias(true);
        
        // Get canvas dimensions
        let width = canvas.base_layer_size().width;
        let height = canvas.base_layer_size().height;
        
        if let Some(radius) = &self.radius {
            // Draw with rounded corners
            let path = create_rounded_rect_path(0.0, 0.0, width as f32, height as f32, radius);
            canvas.draw_path(&path, &paint);
        } else {
            // Fill the entire canvas
            canvas.clear(color);
        }
        
        // If there's an image, draw it on top
        if let Some(img_path) = &self.image {
            if let Ok(img) = load_image(img_path) {
                // Scale image to fit
                let scaled_img = scale_image(img, width as f32, height as f32, &ObjectFit::Cover)?;
                
                // Create a mask if radius is specified
                if let Some(radius) = &self.radius {
                    canvas.save();

                    // Create clip path
                    let path = create_rounded_rect_path(0.0, 0.0, width as f32, height as f32, radius);
                    canvas.clip_path(&path, None, Some(true));
                    
                    // Draw image
                    canvas.draw_image(scaled_img, Point::new(0.0, 0.0), None);
                    
                    canvas.restore();
                } else {
                    // Draw without mask
                    canvas.draw_image(scaled_img, Point::new(0.0, 0.0), None);
                }
            }
        }
        
        Ok(())
    }
}

// Implement image element
impl PosterElement for ImageElement {
    fn z_index(&self) -> i32 {
        self.z_index.unwrap_or(0)
    }
    
    fn render(&self, canvas: &Canvas) -> Result<()> {
        // Load image
        let img = load_image(&self.src)?;
        
        // Scale image according to object_fit
        let scaled_img = scale_image(
            img,
            self.width,
            self.height,
            &self.object_fit,
        )?;
        
        // Apply radius if specified
        if let Some(radius) = &self.radius {
            canvas.save();
            
            // Create clip path
            let path = create_rounded_rect_path(
                self.x,
                self.y,
                self.width,
                self.height,
                radius,
            );
            canvas.clip_path(&path, None, Some(true));
            
            // Draw image
            canvas.draw_image(scaled_img, Point::new(self.x, self.y), None);
            
            canvas.restore();
        } else {
            // Draw without mask
            canvas.draw_image(scaled_img, Point::new(self.x, self.y), None);
        }
        
        Ok(())
    }
}

// Implement text element
impl PosterElement for TextElement {
    fn z_index(&self) -> i32 {
        self.z_index.unwrap_or(0)
    }
    
    fn render(&self, canvas: &Canvas) -> Result<()> {
        // Parse color
        let color = parse_color(&self.color);
        
        // Prepare full text content
        let full_text = match &self.prefix {
            Some(prefix) => format!("{}{}", prefix, self.text),
            None => self.text.clone(),
        };
        
        // Auto-detect text direction if not explicitly set
        let text_direction = match self.direction {
            TextDirectionType::Rtl => TextDirectionType::Rtl,
            TextDirectionType::Ltr => {
                if is_rtl_text(&full_text) {
                    TextDirectionType::Rtl
                } else {
                    TextDirectionType::Ltr
                }
            }
        };
        
        // Get appropriate font for the text with optional font family and font file
        let font = get_font_for_text_with_family(&full_text, self.font_size, self.bold, self.font_family.as_deref(), self.font_file.as_deref());
        
        // Use TextLayout for proper RTL and complex text rendering
        self.render_with_text_layout(canvas, &full_text, &text_direction, &font, color)?;
        
        Ok(())
    }
}

impl TextElement {
    fn render_with_text_layout(&self, canvas: &Canvas, full_text: &str, text_direction: &TextDirectionType, font: &Font, color: Color) -> Result<()> {
        let mut paint = Paint::default();
        paint.set_color(color);
        paint.set_anti_alias(true);
        
        // For RTL text, we need special handling
        let processed_text = if matches!(text_direction, TextDirectionType::Rtl) {
            // For RTL languages like Uyghur, we need to process the text
            // This is a simplified approach - in a full implementation you'd want
            // proper Unicode Bidirectional Algorithm (BiDi) processing
            self.process_rtl_text(full_text)
        } else {
            full_text.to_string()
        };
        
        // Determine if we have multi-line text
        let has_manual_newlines = processed_text.contains('\n');
        let lines: Vec<String> = if has_manual_newlines && self.max_width.is_some() {
            // Both manual newlines and max_width: split by \n first, then wrap each line
            let max_width = self.max_width.unwrap();
            let mut all_lines = Vec::new();
            for manual_line in processed_text.split('\n') {
                let wrapped_lines = break_text_rtl(manual_line, max_width, font, None);
                all_lines.extend(wrapped_lines);
            }
            // Apply max_lines limit if specified
            if let Some(max) = self.max_lines {
                all_lines.truncate(max as usize);
            }
            all_lines
        } else if has_manual_newlines {
            // Only manual newlines: split by \n
            let mut lines: Vec<String> = processed_text.split('\n').map(|s| s.to_string()).collect();
            // Apply max_lines limit if specified
            if let Some(max) = self.max_lines {
                lines.truncate(max as usize);
            }
            lines
        } else if let Some(max_width) = self.max_width {
            // Only auto word wrap based on max_width
            break_text_rtl(&processed_text, max_width, font, self.max_lines)
        } else {
            // Single line
            vec![processed_text.clone()]
        };

        // Draw background if specified
        if let Some(bg_color_str) = &self.background_color {
            let bg_color = parse_color(bg_color_str);
            let mut bg_paint = Paint::default();
            bg_paint.set_color(bg_color);

            // Get font metrics for accurate vertical positioning
            let (_line_spacing, metrics) = font.metrics();
            let ascent = -metrics.ascent; // ascent is negative in Skia
            let descent = metrics.descent; // descent is positive
            let single_line_height = ascent + descent;

            // Calculate total text dimensions for multi-line text
            let max_line_width = lines.iter()
                .map(|line| measure_text_with_font(line, font).0)
                .max_by(|a, b| a.partial_cmp(b).unwrap())
                .unwrap_or(0.0);

            let total_text_height = if lines.len() > 1 {
                // First line uses single_line_height, subsequent lines use line_height spacing
                single_line_height + (lines.len() - 1) as f32 * self.font_size * self.line_height
            } else {
                single_line_height
            };

            let bg_width = self.width.unwrap_or_else(|| max_line_width + self.padding * 2.0);
            let bg_height = self.height.unwrap_or_else(|| total_text_height + self.padding * 2.0);

            // Adjust x position based on text alignment
            let bg_x = match (self.align, text_direction) {
                (TextAlignType::Left, TextDirectionType::Ltr) => self.x - self.padding,
                (TextAlignType::Right, TextDirectionType::Ltr) => self.x - bg_width + self.padding,
                (TextAlignType::Center, _) => self.x - bg_width / 2.0,
                // For RTL text, reverse alignment
                (TextAlignType::Left, TextDirectionType::Rtl) => self.x - bg_width + self.padding,
                (TextAlignType::Right, TextDirectionType::Rtl) => self.x - self.padding,
            };

            // Position background box so text baseline is vertically centered
            // self.y is the text baseline, ascent goes up, descent goes down
            let bg_y = self.y - ascent - self.padding;

            // Draw background with optional radius
            if let Some(radius) = &self.border_radius {
                let path = create_rounded_rect_path(bg_x, bg_y, bg_width, bg_height, radius);
                canvas.draw_path(&path, &bg_paint);
            } else {
                let rect = Rect::new(bg_x, bg_y, bg_x + bg_width, bg_y + bg_height);
                canvas.draw_rect(rect, &bg_paint);
            }
        }

        // Render all lines
        for (i, line) in lines.iter().enumerate() {
            let y_pos = self.y + (i as f32 * self.font_size * self.line_height);
            draw_text_line_improved(canvas, line, self.x, y_pos, font, &paint, text_direction, &self.align);
        }
        
        Ok(())
    }
    
    // Process RTL text for better display
    fn process_rtl_text(&self, text: &str) -> String {
        // For Arabic script text (including Uyghur), we should NOT reverse the text
        // because Skia Safe handles the correct display direction automatically.
        // Reversing would break ligatures and proper text shaping.
        // We preserve the original text and let Skia handle the RTL rendering.
        text.to_string()
    }
}

// Implementation for PosterGenerator
impl PosterGenerator {
    /// Creates a new poster generator.
    ///
    /// # Arguments
    ///
    /// * `width` - Canvas width in pixels
    /// * `height` - Canvas height in pixels
    /// * `background_color` - Background color in hex format (e.g., "#ffffff")
    ///
    /// # Example
    ///
    /// ```
    /// use poster_generator::PosterGenerator;
    ///
    /// let generator = PosterGenerator::new(1920, 1080, "#000000".to_string());
    /// ```
    pub fn new(width: u32, height: u32, background_color: String) -> Self {
        Self {
            width,
            height,
            background_color,
            elements: Vec::new(),
        }
    }

    /// Adds a background element to the poster.
    ///
    /// Background elements are always rendered first (z-index: -1000).
    ///
    /// # Example
    ///
    /// ```
    /// use poster_generator::{PosterGenerator, BackgroundElement, Radius};
    ///
    /// let mut generator = PosterGenerator::new(800, 600, "#ffffff".to_string());
    /// let bg = BackgroundElement {
    ///     color: "#f0f0f0".to_string(),
    ///     image: None,
    ///     radius: Some(Radius::Single(20.0)),
    /// };
    /// generator.add_background(bg);
    /// ```
    pub fn add_background(&mut self, background: BackgroundElement) -> &mut Self {
        self.elements.push(Box::new(background));
        self
    }

    /// Adds an image element to the poster.
    ///
    /// # Example
    ///
    /// ```
    /// use poster_generator::{PosterGenerator, ImageElement, ObjectFit, Radius};
    ///
    /// let mut generator = PosterGenerator::new(800, 600, "#ffffff".to_string());
    /// let img = ImageElement {
    ///     src: "photo.jpg".to_string(),
    ///     x: 50.0,
    ///     y: 50.0,
    ///     width: 300.0,
    ///     height: 200.0,
    ///     radius: Some(Radius::Single(10.0)),
    ///     z_index: Some(1),
    ///     object_fit: ObjectFit::Cover,
    /// };
    /// generator.add_image(img);
    /// ```
    pub fn add_image(&mut self, image: ImageElement) -> &mut Self {
        self.elements.push(Box::new(image));
        self
    }

    /// Adds a text element to the poster.
    ///
    /// Text elements support RTL languages and will be automatically detected.
    ///
    /// # Example
    ///
    /// ```
    /// use poster_generator::{PosterGenerator, TextElement, TextAlignType, TextDirectionType};
    ///
    /// let mut generator = PosterGenerator::new(800, 600, "#ffffff".to_string());
    /// let text = TextElement {
    ///     text: "Hello, World!".to_string(),
    ///     x: 400.0,
    ///     y: 300.0,
    ///     font_size: 48.0,
    ///     color: "#000000".to_string(),
    ///     align: TextAlignType::Center,
    ///     ..Default::default()
    /// };
    /// generator.add_text(text);
    /// ```
    pub fn add_text(&mut self, text: TextElement) -> &mut Self {
        self.elements.push(Box::new(text));
        self
    }

    /// Clears all elements from the poster.
    pub fn clear(&mut self) -> &mut Self {
        self.elements.clear();
        self
    }

    /// Sets all elements at once, replacing any existing elements.
    ///
    /// # Example
    ///
    /// ```
    /// use poster_generator::{PosterGenerator, Element, TextElement, TextAlignType};
    ///
    /// let mut generator = PosterGenerator::new(800, 600, "#ffffff".to_string());
    /// let elements = vec![
    ///     Element::Text(TextElement {
    ///         text: "Title".to_string(),
    ///         x: 400.0,
    ///         y: 100.0,
    ///         font_size: 64.0,
    ///         color: "#000000".to_string(),
    ///         align: TextAlignType::Center,
    ///         ..Default::default()
    ///     }),
    /// ];
    /// generator.set_elements(elements);
    /// ```
    pub fn set_elements(&mut self, elements: Vec<Element>) -> &mut Self {
        self.clear();
        
        for element in elements {
            match element {
                Element::Background(bg) => self.add_background(bg),
                Element::Image(img) => self.add_image(img),
                Element::Text(txt) => self.add_text(txt),
            };
        }
        
        self
    }

    /// Generates the poster as PNG image data.
    ///
    /// Returns a vector of bytes containing the PNG image data.
    ///
    /// # Errors
    ///
    /// Returns an error if rendering fails or PNG encoding fails.
    ///
    /// # Example
    ///
    /// ```
    /// use poster_generator::PosterGenerator;
    ///
    /// let generator = PosterGenerator::new(800, 600, "#ffffff".to_string());
    /// let png_data = generator.generate().expect("Failed to generate");
    /// std::fs::write("output.png", png_data).expect("Failed to write file");
    /// ```
    pub fn generate(&self) -> Result<Vec<u8>> {
        // Create surface
        let mut surface = skia_safe::surfaces::raster_n32_premul((self.width as i32, self.height as i32)).ok_or_else(|| {
            PosterError::RenderError("Failed to create surface".to_string())
        })?;
        
        {
            // Get canvas
            let canvas = surface.canvas();
            
            // Fill with background color
            let bg_color = parse_color(&self.background_color);
            canvas.clear(bg_color);
            
            // Sort elements by z-index
            let mut sorted_elements = self.elements.iter().collect::<Vec<_>>();
            sorted_elements.sort_by_key(|e| e.z_index());
            
            // Render each element
            for element in sorted_elements {
                element.render(canvas)?;
            }
        }
        
        // Encode as PNG
        let image = surface.image_snapshot();
        let data = image.encode_to_data(EncodedImageFormat::PNG).ok_or_else(|| {
            PosterError::OutputError("Failed to encode image as PNG".to_string())
        })?;
        
        Ok(data.as_bytes().to_vec())
    }

    /// Generates the poster and saves it to a file.
    ///
    /// # Arguments
    ///
    /// * `path` - Output file path
    ///
    /// # Errors
    ///
    /// Returns an error if rendering fails or file writing fails.
    ///
    /// # Example
    ///
    /// ```
    /// use poster_generator::PosterGenerator;
    ///
    /// let generator = PosterGenerator::new(800, 600, "#ffffff".to_string());
    /// generator.generate_file("poster.png").expect("Failed to save");
    /// ```
    pub fn generate_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let png_data = self.generate()?;
        
        // Save to file
        std::fs::write(path, png_data)?;
        
        Ok(())
    }

    /// Generates the poster as a base64 encoded data URL.
    ///
    /// Returns a string in the format: `data:image/png;base64,<encoded_data>`
    ///
    /// # Errors
    ///
    /// Returns an error if rendering or encoding fails.
    ///
    /// # Example
    ///
    /// ```
    /// use poster_generator::PosterGenerator;
    ///
    /// let generator = PosterGenerator::new(800, 600, "#ffffff".to_string());
    /// let base64_url = generator.generate_base64().expect("Failed to encode");
    /// println!("Data URL: {}", base64_url);
    /// ```
    pub fn generate_base64(&self) -> Result<String> {
        let png_data = self.generate()?;
        
        // Encode to base64
        let base64 = general_purpose::STANDARD.encode(&png_data);
        
        Ok(format!("data:image/png;base64,{}", base64))
    }
}

// Utility functions
fn parse_color(color_str: &str) -> Color {
    if color_str.starts_with('#') {
        // Parse hex color
        let hex = &color_str[1..];
        if hex.len() == 6 {
            if let (Ok(r), Ok(g), Ok(b)) = (
                u8::from_str_radix(&hex[0..2], 16),
                u8::from_str_radix(&hex[2..4], 16),
                u8::from_str_radix(&hex[4..6], 16),
            ) {
                return Color::from_rgb(r, g, b);
            }
        } else if hex.len() == 8 {
            if let (Ok(r), Ok(g), Ok(b), Ok(a)) = (
                u8::from_str_radix(&hex[0..2], 16),
                u8::from_str_radix(&hex[2..4], 16),
                u8::from_str_radix(&hex[4..6], 16),
                u8::from_str_radix(&hex[6..8], 16),
            ) {
                return Color::from_argb(a, r, g, b);
            }
        }
    }
    
    // Default to black if parsing fails
    Color::BLACK
}

fn load_image(path: &str) -> Result<Image> {
    // Check if path is a base64 string
    if path.starts_with("data:image/") {
        let base64_data = path.split(',').nth(1).ok_or_else(|| {
            PosterError::ImageLoadError("Invalid base64 image format".to_string())
        })?;
        
        let bytes = general_purpose::STANDARD.decode(base64_data)?;
        let data = Data::new_copy(&bytes);
        
        let image = Image::from_encoded(data).ok_or_else(|| {
            PosterError::ImageLoadError("Failed to decode base64 image".to_string())
        })?;
        
        return Ok(image);
    }
    
    // Otherwise load from file
    let bytes = std::fs::read(path)?;
    let data = Data::new_copy(&bytes);
    
    let image = Image::from_encoded(data).ok_or_else(|| {
        PosterError::ImageLoadError(format!("Failed to load image from: {}", path))
    })?;
    
    Ok(image)
}

fn scale_image(img: Image, width: f32, height: f32, object_fit: &ObjectFit) -> Result<Image> {
    let src_width = img.width() as f32;
    let src_height = img.height() as f32;
    
    let mut surface = match object_fit {
        ObjectFit::Cover => {
            // Calculate scale to fill the target area while maintaining aspect ratio
            let scale_x = width / src_width;
            let scale_y = height / src_height;
            let scale = scale_x.max(scale_y);
            
            let scaled_width = (src_width * scale).ceil() as i32;
            let scaled_height = (src_height * scale).ceil() as i32;
            
            // Create a surface for the scaled image
            let mut surface = skia_safe::surfaces::raster_n32_premul((width as i32, height as i32)).ok_or_else(|| {
                PosterError::RenderError("Failed to create surface for scaled image".to_string())
            })?;
            
            let canvas = surface.canvas();
            
            // Calculate position to center the scaled image
            let x = (width - scaled_width as f32) / 2.0;
            let y = (height - scaled_height as f32) / 2.0;
            
            // Draw the image scaled and centered
            let mut paint = Paint::default();
            paint.set_anti_alias(true);
            canvas.scale((scale, scale));
            canvas.draw_image(img, Point::new(x / scale, y / scale), Some(&paint));
            
            surface
        },
        ObjectFit::Contain => {
            // Calculate scale to fit within the target area while maintaining aspect ratio
            let scale_x = width / src_width;
            let scale_y = height / src_height;
            let scale = scale_x.min(scale_y);
            
            let scaled_width = (src_width * scale) as i32;
            let scaled_height = (src_height * scale) as i32;
            
            // Create a surface for the scaled image
            let mut surface = skia_safe::surfaces::raster_n32_premul((width as i32, height as i32)).ok_or_else(|| {
                PosterError::RenderError("Failed to create surface for scaled image".to_string())
            })?;
            
            let canvas = surface.canvas();
            
            // Calculate position to center the scaled image
            let x = (width - scaled_width as f32) / 2.0;
            let y = (height - scaled_height as f32) / 2.0;
            
            // Draw the image scaled and centered
            let mut paint = Paint::default();
            paint.set_anti_alias(true);
            let src_rect = Rect::new(0.0, 0.0, src_width, src_height);
            let dest_rect = Rect::new(x, y, x + scaled_width as f32, y + scaled_height as f32);
            canvas.draw_image_rect(img, Some((&src_rect, skia_safe::canvas::SrcRectConstraint::Fast)), dest_rect, &paint);
            
            surface
        },
        ObjectFit::Stretch => {
            // Create a surface for the stretched image
            let mut surface = skia_safe::surfaces::raster_n32_premul((width as i32, height as i32)).ok_or_else(|| {
                PosterError::RenderError("Failed to create surface for stretched image".to_string())
            })?;
            
            let canvas = surface.canvas();
            
            // Draw the image stretched to fill the target area
            let src_rect = Rect::new(0.0, 0.0, src_width, src_height);
            let dest_rect = Rect::new(0.0, 0.0, width, height);
            
            let mut paint = Paint::default();
            paint.set_anti_alias(true);
            canvas.draw_image_rect(img, Some((&src_rect, skia_safe::canvas::SrcRectConstraint::Fast)), dest_rect, &paint);
            
            surface
        }
    };
    
    Ok(surface.image_snapshot())
}

fn create_rounded_rect_path(x: f32, y: f32, width: f32, height: f32, radius: &Radius) -> SkPath {
    let mut path = SkPath::new();
    
    match radius {
        Radius::Single(r) => {
            let r = r.min(width / 2.0).min(height / 2.0);
            path.add_round_rect(
                Rect::new(x, y, x + width, y + height),
                (r, r), 
                None
            );
        },
        Radius::Multiple(corners) => {
            let tl = corners[0].min(width / 2.0).min(height / 2.0);
            let tr = corners[1].min(width / 2.0).min(height / 2.0);
            let br = corners[2].min(width / 2.0).min(height / 2.0);
            let bl = corners[3].min(width / 2.0).min(height / 2.0);
            
            // Drawing a path with different corner radii
            path.move_to((x + tl, y));
            path.line_to((x + width - tr, y));
            if tr > 0.0 {
                path.quad_to((x + width, y), (x + width, y + tr));
            }
            path.line_to((x + width, y + height - br));
            if br > 0.0 {
                path.quad_to((x + width, y + height), (x + width - br, y + height));
            }
            path.line_to((x + bl, y + height));
            if bl > 0.0 {
                path.quad_to((x, y + height), (x, y + height - bl));
            }
            path.line_to((x, y + tl));
            if tl > 0.0 {
                path.quad_to((x, y), (x + tl, y));
            }
            path.close();
        }
    }
    
    path
}

// Improved text measurement with better font support
fn measure_text_with_font(text: &str, font: &Font) -> (f32, f32) {
    // Use Skia's text measurement
    let blob = TextBlob::new(text, font).unwrap_or_else(|| {
        TextBlob::new(" ", font).unwrap() // Fallback to a space if there's an issue
    });
    
    let bounds = blob.bounds();
    (bounds.width(), bounds.height())
}

// RTL-aware text breaking
fn break_text_rtl(text: &str, max_width: f32, font: &Font, max_lines: Option<u32>) -> Vec<String> {
    let mut lines = Vec::new();
    let mut current_line = String::new();
    
    // Split text by whitespace (same for both LTR and RTL - character order is preserved)
    let words: Vec<&str> = text.split_whitespace().collect();
    
    for word in words {
        let test_line = if current_line.is_empty() {
            word.to_string()
        } else {
            format!("{} {}", current_line, word)
        };
        
        let (test_width, _) = measure_text_with_font(&test_line, font);
        
        if test_width <= max_width || current_line.is_empty() {
            current_line = test_line;
        } else {
            lines.push(current_line);
            current_line = word.to_string();
            
            if let Some(max) = max_lines {
                if lines.len() >= max as usize - 1 {
                    break;
                }
            }
        }
    }
    
    if !current_line.is_empty() {
        if let Some(max) = max_lines {
            if lines.len() >= max as usize {
                // Truncate last line with ellipsis
                let last_line = lines.last_mut().unwrap();
                *last_line = truncate_with_ellipsis_rtl(last_line, max_width, font);
            } else {
                lines.push(current_line);
            }
        } else {
            lines.push(current_line);
        }
    }
    
    lines
}

fn truncate_with_ellipsis_rtl(text: &str, max_width: f32, font: &Font) -> String {
    let ellipsis = if is_rtl_text(text) { "..." } else { "..." }; // Could use RTL ellipsis: "…"
    let (ellipsis_width, _) = measure_text_with_font(ellipsis, font);
    
    let (text_width, _) = measure_text_with_font(text, font);
    if text_width <= max_width {
        return text.to_string();
    }
    
    let available_width = max_width - ellipsis_width;
    let mut result = String::new();
    
    for ch in text.chars() {
        let test_text = format!("{}{}", result, ch);
        let (test_width, _) = measure_text_with_font(&test_text, font);
        
        if test_width <= available_width {
            result.push(ch);
        } else {
            break;
        }
    }
    
    format!("{}{}", result, ellipsis)
}

// Improved text drawing with RTL support
fn draw_text_line_improved(
    canvas: &Canvas, 
    text: &str, 
    x: f32, 
    y: f32, 
    font: &Font, 
    paint: &Paint, 
    direction: &TextDirectionType,
    align: &TextAlignType
) {
    // For RTL text (Arabic/Hebrew/Uyghur), use Skia's textlayout for proper shaping and direction
    if matches!(direction, TextDirectionType::Rtl) && is_rtl_text(text) {
        // Create paragraph style with RTL direction
        let mut paragraph_style = ParagraphStyle::new();
        paragraph_style.set_text_direction(TextDirection::RTL);

        // Set text alignment
        let text_align = match align {
            TextAlignType::Left => TextAlign::Left,
            TextAlignType::Right => TextAlign::Right,
            TextAlignType::Center => TextAlign::Center,
        };
        paragraph_style.set_text_align(text_align);

        // Use system font manager for font collection
        let font_mgr = FontMgr::default();
        let mut font_collection = FontCollection::new();
        font_collection.set_default_font_manager(font_mgr, None);

        let mut paragraph_builder = ParagraphBuilder::new(&paragraph_style, font_collection);

        // Create text style using the font that was already selected by get_font_for_text_with_family
        let mut text_style = TextStyle::new();
        text_style.set_font_size(font.size());
        text_style.set_color(paint.color());

        // Extract font family name from the font
        let family_name = font.typeface().family_name();
        text_style.set_font_families(&[family_name.as_str()]);

        // Add styled text
        paragraph_builder.push_style(&text_style);
        paragraph_builder.add_text(text);

        // Build and layout paragraph
        let mut paragraph = paragraph_builder.build();
        paragraph.layout(1000.0); // Wide layout for proper text measurement

        // Adjust Y position for baseline
        let draw_y = y - font.size();

        // For center alignment, adjust X position
        let draw_x = if matches!(align, TextAlignType::Center) {
            x - paragraph.max_width() / 2.0
        } else {
            x
        };

        // Draw the paragraph
        paragraph.paint(canvas, Point::new(draw_x, draw_y));

    } else {
        // For LTR text, use standard TextBlob approach
        if let Some(blob) = TextBlob::new(text, font) {
            let (text_width, _) = measure_text_with_font(text, font);
            
            let draw_x = match align {
                TextAlignType::Left => x,
                TextAlignType::Right => x - text_width,
                TextAlignType::Center => x - text_width / 2.0,
            };
            
            canvas.draw_text_blob(blob, Point::new(draw_x, y), paint);
        }
    }
}