svg.rs

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