browser_engine 0.1.0

A modular, GPU-accelerated, security-first web browser engine built from scratch in Rust.
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
use std::collections::HashMap;

use crate::layout::{LayoutBox, BoxType, Rect};
use crate::style::ComputedStyle;

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Color {
    pub fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
        Color { r, g, b, a }
    }

    pub fn rgb(r: f32, g: f32, b: f32) -> Self {
        Color { r, g, b, a: 1.0 }
    }

    pub fn black() -> Self {
        Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }
    }

    pub fn white() -> Self {
        Color { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
    }

    pub fn transparent() -> Self {
        Color { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }
    }
}

pub fn parse_color(val: &str) -> Option<Color> {
    let s = val.trim().to_ascii_lowercase();
    if s.starts_with('#') {
        let chars: Vec<char> = s.chars().collect();
        if chars.len() == 4 {
            let r = chars[1].to_digit(16)? as f32 / 15.0;
            let g = chars[2].to_digit(16)? as f32 / 15.0;
            let b = chars[3].to_digit(16)? as f32 / 15.0;
            return Some(Color::new(r, g, b, 1.0));
        } else if chars.len() == 7 {
            let r = (chars[1].to_digit(16)? * 16 + chars[2].to_digit(16)?) as f32 / 255.0;
            let g = (chars[3].to_digit(16)? * 16 + chars[4].to_digit(16)?) as f32 / 255.0;
            let b = (chars[5].to_digit(16)? * 16 + chars[6].to_digit(16)?) as f32 / 255.0;
            return Some(Color::new(r, g, b, 1.0));
        } else if chars.len() == 9 {
            let r = (chars[1].to_digit(16)? * 16 + chars[2].to_digit(16)?) as f32 / 255.0;
            let g = (chars[3].to_digit(16)? * 16 + chars[4].to_digit(16)?) as f32 / 255.0;
            let b = (chars[5].to_digit(16)? * 16 + chars[6].to_digit(16)?) as f32 / 255.0;
            let a = (chars[7].to_digit(16)? * 16 + chars[8].to_digit(16)?) as f32 / 255.0;
            return Some(Color::new(r, g, b, a));
        }
    } else if s.starts_with("rgb(") && s.ends_with(')') {
        let content = &s[4..s.len() - 1];
        let parts: Vec<&str> = content.split(',').collect();
        if parts.len() == 3 {
            let r = parts[0].trim().parse::<f32>().ok()? / 255.0;
            let g = parts[1].trim().parse::<f32>().ok()? / 255.0;
            let b = parts[2].trim().parse::<f32>().ok()? / 255.0;
            return Some(Color::new(r, g, b, 1.0));
        }
    } else if s.starts_with("rgba(") && s.ends_with(')') {
        let content = &s[5..s.len() - 1];
        let parts: Vec<&str> = content.split(',').collect();
        if parts.len() == 4 {
            let r = parts[0].trim().parse::<f32>().ok()? / 255.0;
            let g = parts[1].trim().parse::<f32>().ok()? / 255.0;
            let b = parts[2].trim().parse::<f32>().ok()? / 255.0;
            let a = parts[3].trim().parse::<f32>().ok()?;
            return Some(Color::new(r, g, b, a.clamp(0.0, 1.0)));
        }
    } else {
        match s.as_str() {
            "red" => return Some(Color::new(1.0, 0.0, 0.0, 1.0)),
            "green" => return Some(Color::new(0.0, 0.5, 0.0, 1.0)),
            "blue" => return Some(Color::new(0.0, 0.0, 1.0, 1.0)),
            "black" => return Some(Color::black()),
            "white" => return Some(Color::white()),
            "transparent" => return Some(Color::transparent()),
            _ => {}
        }
    }
    None
}

#[derive(Debug, Clone, PartialEq)]
pub enum PaintCommand {
    DrawRect {
        rect: Rect,
        color: Color,
        border_radius: f32,
        is_fixed: bool,
    },
    DrawText {
        text: String,
        rect: Rect,
        color: Color,
        font_size: f32,
        is_fixed: bool,
    },
    DrawImage {
        rect: Rect,
        src: String,
        alt: String,
        is_fixed: bool,
    },
}

#[derive(Clone)]
struct LayeredCommand {
    cmd: PaintCommand,
    z_index: i32,
    order: usize,
}

pub fn build_display_list(
    layout_box: &LayoutBox,
    styles: &HashMap<usize, ComputedStyle>,
) -> Vec<PaintCommand> {
    let mut items = Vec::new();
    let mut order = 0;
    build_recursive(layout_box, styles, None, false, 0, &mut items, &mut order);
    items.sort_by(|a, b| a.z_index.cmp(&b.z_index).then(a.order.cmp(&b.order)));
    items.into_iter().map(|item| item.cmd).collect()
}

fn build_recursive(
    lb: &LayoutBox,
    styles: &HashMap<usize, ComputedStyle>,
    parent_style: Option<&ComputedStyle>,
    parent_is_fixed: bool,
    parent_z_index: i32,
    items: &mut Vec<LayeredCommand>,
    order: &mut usize,
) {
    match lb.box_type {
        BoxType::Block(node_idx) => {
            let style = styles.get(&node_idx);

            let is_fixed = style
                .and_then(|s| s.get("position"))
                .map(|p| p.trim().eq_ignore_ascii_case("fixed"))
                .unwrap_or(parent_is_fixed);

            let z_index = style
                .and_then(|s| s.get("z-index"))
                .and_then(|z| z.trim().parse::<i32>().ok())
                .unwrap_or(parent_z_index);

            let border_radius = style
                .and_then(|s| s.get("border-radius"))
                .map(|br| crate::layout::engine::parse_length(br, lb.dimensions.content.width))
                .unwrap_or(0.0);

            // 0. Draw Box Shadow (Elevation)
            if let Some(s) = style {
                if let Some(_shadow_str) = s.get("box-shadow") {
                    let shadow_color = parse_color("rgba(0, 0, 0, 0.35)").unwrap_or(Color::new(0.0, 0.0, 0.0, 0.35));
                    *order += 1;
                    items.push(LayeredCommand {
                        cmd: PaintCommand::DrawRect {
                            rect: Rect {
                                x: lb.dimensions.padding_box().x + 2.0,
                                y: lb.dimensions.padding_box().y + 4.0,
                                width: lb.dimensions.padding_box().width,
                                height: lb.dimensions.padding_box().height,
                            },
                            color: shadow_color,
                            border_radius: border_radius + 2.0,
                            is_fixed,
                        },
                        z_index,
                        order: *order,
                    });
                }
            }

            // 1. Draw Background
            if let Some(s) = style {
                if let Some(bg_color_str) = s.get("background-color") {
                    if let Some(color) = parse_color(bg_color_str) {
                        if color.a > 0.0 {
                            *order += 1;
                            items.push(LayeredCommand {
                                cmd: PaintCommand::DrawRect {
                                    rect: lb.dimensions.padding_box(),
                                    color,
                                    border_radius,
                                    is_fixed,
                                },
                                z_index,
                                order: *order,
                            });
                        }
                    }
                }
            }

            // 2. Draw Borders
            let border_width = lb.dimensions.border;
            if border_width.top > 0.0 || border_width.bottom > 0.0 || border_width.left > 0.0 || border_width.right > 0.0 {
                let border_color_str = style.and_then(|s| s.get("border-color"));
                let color = border_color_str
                    .and_then(|c| parse_color(c))
                    .unwrap_or(Color::black());

                let border_box = lb.dimensions.border_box();

                if border_width.top > 0.0 {
                    *order += 1;
                    items.push(LayeredCommand {
                        cmd: PaintCommand::DrawRect {
                            rect: Rect {
                                x: border_box.x,
                                y: border_box.y,
                                width: border_box.width,
                                height: border_width.top,
                            },
                            color,
                            border_radius: 0.0,
                            is_fixed,
                        },
                        z_index,
                        order: *order,
                    });
                }
                if border_width.bottom > 0.0 {
                    *order += 1;
                    items.push(LayeredCommand {
                        cmd: PaintCommand::DrawRect {
                            rect: Rect {
                                x: border_box.x,
                                y: border_box.y + border_box.height - border_width.bottom,
                                width: border_box.width,
                                height: border_width.bottom,
                            },
                            color,
                            border_radius: 0.0,
                            is_fixed,
                        },
                        z_index,
                        order: *order,
                    });
                }
                if border_width.left > 0.0 {
                    *order += 1;
                    items.push(LayeredCommand {
                        cmd: PaintCommand::DrawRect {
                            rect: Rect {
                                x: border_box.x,
                                y: border_box.y,
                                width: border_width.left,
                                height: border_box.height,
                            },
                            color,
                            border_radius: 0.0,
                            is_fixed,
                        },
                        z_index,
                        order: *order,
                    });
                }
                if border_width.right > 0.0 {
                    *order += 1;
                    items.push(LayeredCommand {
                        cmd: PaintCommand::DrawRect {
                            rect: Rect {
                                x: border_box.x + border_box.width - border_width.right,
                                y: border_box.y,
                                width: border_width.right,
                                height: border_box.height,
                            },
                            color,
                            border_radius: 0.0,
                            is_fixed,
                        },
                        z_index,
                        order: *order,
                    });
                }
            }

            for child in &lb.children {
                build_recursive(child, styles, style, is_fixed, z_index, items, order);
            }
        }
        BoxType::Anonymous => {
            if let Some(text) = &lb.text_content {
                let color = parent_style
                    .and_then(|s| s.get("color"))
                    .and_then(|c| parse_color(c))
                    .unwrap_or(Color::black());

                let font_size = parent_style
                    .and_then(|s| s.get("font-size"))
                    .and_then(|fs| {
                        let fs_trimmed = fs.trim();
                        if let Some(stripped) = fs_trimmed.strip_suffix("px") {
                            stripped.trim().parse::<f32>().ok()
                        } else {
                            fs_trimmed.parse::<f32>().ok()
                        }
                    })
                    .unwrap_or(16.0);

                let char_width = 8.0 * (font_size / 16.0);
                let line_height = 18.0 * (font_size / 16.0);
                let lines = crate::layout::engine::wrap_text(text, lb.dimensions.content.width, char_width);

                for (idx, line) in lines.into_iter().enumerate() {
                    *order += 1;
                    items.push(LayeredCommand {
                        cmd: PaintCommand::DrawText {
                            text: line,
                            rect: Rect {
                                x: lb.dimensions.content.x,
                                y: lb.dimensions.content.y + idx as f32 * line_height,
                                width: lb.dimensions.content.width,
                                height: line_height,
                            },
                            color,
                            font_size,
                            is_fixed: parent_is_fixed,
                        },
                        z_index: parent_z_index,
                        order: *order,
                    });
                }
            }
        }
    }
}

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

    #[test]
    fn parses_hex_and_named_colors() {
        assert_eq!(parse_color("#ff0000"), Some(Color::new(1.0, 0.0, 0.0, 1.0)));
        assert_eq!(parse_color("#00f"), Some(Color::new(0.0, 0.0, 1.0, 1.0)));
        assert_eq!(parse_color("black"), Some(Color::black()));
        assert_eq!(parse_color("transparent"), Some(Color::transparent()));
    }

    #[test]
    fn parses_rgb_color_function() {
        assert_eq!(parse_color("rgb(255, 0, 0)"), Some(Color::new(1.0, 0.0, 0.0, 1.0)));
        assert_eq!(parse_color("rgba(0, 128, 255, 0.5)"), Some(Color::new(0.0, 128.0 / 255.0, 1.0, 0.5)));
    }

    #[test]
    fn test_draw_image_paint_command() {
        let cmd = PaintCommand::DrawImage {
            rect: Rect { x: 0.0, y: 0.0, width: 100.0, height: 100.0 },
            src: "logo.png".to_string(),
            alt: "Logo".to_string(),
            is_fixed: false,
        };
        assert!(matches!(cmd, PaintCommand::DrawImage { .. }));
    }

    #[test]
    fn test_border_radius_display_list() {
        let box_node = LayoutBox::new(BoxType::Block(0));
        let mut styles = HashMap::new();
        let mut style = HashMap::new();
        style.insert("background-color".to_string(), "#1e293b".to_string());
        style.insert("border-radius".to_string(), "12px".to_string());
        styles.insert(0, style);

        let list = build_display_list(&box_node, &styles);
        assert!(!list.is_empty());
        if let PaintCommand::DrawRect { border_radius, .. } = &list[0] {
            assert_eq!(*border_radius, 12.0);
        } else {
            panic!("Expected DrawRect with border_radius");
        }
    }

    #[test]
    fn test_z_index_display_ordering() {
        let mut root = LayoutBox::new(BoxType::Block(0));
        let child1 = LayoutBox::new(BoxType::Block(1));
        let child2 = LayoutBox::new(BoxType::Block(2));
        root.children.push(child1);
        root.children.push(child2);

        let mut styles = HashMap::new();
        let mut style1 = HashMap::new();
        style1.insert("background-color".to_string(), "red".to_string());
        style1.insert("z-index".to_string(), "10".to_string());
        styles.insert(1, style1);

        let mut style2 = HashMap::new();
        style2.insert("background-color".to_string(), "blue".to_string());
        style2.insert("z-index".to_string(), "1".to_string());
        styles.insert(2, style2);

        let list = build_display_list(&root, &styles);
        // child 2 (z-index 1) must be rendered before child 1 (z-index 10)
        assert_eq!(list.len(), 2);
        if let (PaintCommand::DrawRect { color: c1, .. }, PaintCommand::DrawRect { color: c2, .. }) = (&list[0], &list[1]) {
            assert_eq!(*c1, Color::new(0.0, 0.0, 1.0, 1.0)); // blue
            assert_eq!(*c2, Color::new(1.0, 0.0, 0.0, 1.0)); // red
        }
    }
}