svg.rs

 1use std::fs;
 2use std::path::PathBuf;
 3
 4use anyhow::Result;
 5use gpui::{
 6    App, Application, AssetSource, Bounds, Context, SharedString, Window, WindowBounds,
 7    WindowOptions, div, prelude::*, px, rgb, size, svg,
 8};
 9
10struct Assets {
11    base: PathBuf,
12}
13
14impl AssetSource for Assets {
15    fn load(&self, path: &str) -> Result<Option<std::borrow::Cow<'static, [u8]>>> {
16        fs::read(self.base.join(path))
17            .map(|data| Some(std::borrow::Cow::Owned(data)))
18            .map_err(|err| err.into())
19    }
20
21    fn list(&self, path: &str) -> Result<Vec<SharedString>> {
22        fs::read_dir(self.base.join(path))
23            .map(|entries| {
24                entries
25                    .filter_map(|entry| {
26                        entry
27                            .ok()
28                            .and_then(|entry| entry.file_name().into_string().ok())
29                            .map(SharedString::from)
30                    })
31                    .collect()
32            })
33            .map_err(|err| err.into())
34    }
35}
36
37struct SvgExample;
38
39impl Render for SvgExample {
40    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
41        div()
42            .flex()
43            .flex_row()
44            .size_full()
45            .justify_center()
46            .items_center()
47            .gap_8()
48            .bg(rgb(0xffffff))
49            .child(
50                svg()
51                    .path("svg/dragon.svg")
52                    .size_8()
53                    .text_color(rgb(0xff0000)),
54            )
55            .child(
56                svg()
57                    .path("svg/dragon.svg")
58                    .size_8()
59                    .text_color(rgb(0x00ff00)),
60            )
61            .child(
62                svg()
63                    .path("svg/dragon.svg")
64                    .size_8()
65                    .text_color(rgb(0x0000ff)),
66            )
67    }
68}
69
70fn main() {
71    Application::new()
72        .with_assets(Assets {
73            base: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples"),
74        })
75        .run(|cx: &mut App| {
76            let bounds = Bounds::centered(None, size(px(300.0), px(300.0)), cx);
77            cx.open_window(
78                WindowOptions {
79                    window_bounds: Some(WindowBounds::Windowed(bounds)),
80                    ..Default::default()
81                },
82                |_, cx| cx.new(|_| SvgExample),
83            )
84            .unwrap();
85            cx.activate(true);
86        });
87}