opacity.rs

  1use std::{fs, path::PathBuf, time::Duration};
  2
  3use anyhow::Result;
  4use gpui::{
  5    div, hsla, img, point, prelude::*, px, rgb, size, svg, App, Application, AssetSource, Bounds,
  6    BoxShadow, ClickEvent, Context, SharedString, Task, Timer, Window, WindowBounds, WindowOptions,
  7};
  8
  9struct Assets {
 10    base: PathBuf,
 11}
 12
 13impl AssetSource for Assets {
 14    fn load(&self, path: &str) -> Result<Option<std::borrow::Cow<'static, [u8]>>> {
 15        fs::read(self.base.join(path))
 16            .map(|data| Some(std::borrow::Cow::Owned(data)))
 17            .map_err(|e| e.into())
 18    }
 19
 20    fn list(&self, path: &str) -> Result<Vec<SharedString>> {
 21        fs::read_dir(self.base.join(path))
 22            .map(|entries| {
 23                entries
 24                    .filter_map(|entry| {
 25                        entry
 26                            .ok()
 27                            .and_then(|entry| entry.file_name().into_string().ok())
 28                            .map(SharedString::from)
 29                    })
 30                    .collect()
 31            })
 32            .map_err(|e| e.into())
 33    }
 34}
 35
 36struct HelloWorld {
 37    _task: Option<Task<()>>,
 38    opacity: f32,
 39}
 40
 41impl HelloWorld {
 42    fn new(_window: &mut Window, _: &mut Context<Self>) -> Self {
 43        Self {
 44            _task: None,
 45            opacity: 0.5,
 46        }
 47    }
 48
 49    fn change_opacity(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
 50        self.opacity = 0.0;
 51        cx.notify();
 52
 53        self._task = Some(cx.spawn_in(window, async move |view, cx| loop {
 54            Timer::after(Duration::from_secs_f32(0.05)).await;
 55            let mut stop = false;
 56            let _ = cx.update(|_, cx| {
 57                view.update(cx, |view, cx| {
 58                    if view.opacity >= 1.0 {
 59                        stop = true;
 60                        return;
 61                    }
 62
 63                    view.opacity += 0.1;
 64                    cx.notify();
 65                })
 66            });
 67
 68            if stop {
 69                break;
 70            }
 71        }));
 72    }
 73}
 74
 75impl Render for HelloWorld {
 76    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 77        div()
 78            .flex()
 79            .flex_row()
 80            .size_full()
 81            .bg(rgb(0xe0e0e0))
 82            .text_xl()
 83            .child(
 84                div()
 85                    .flex()
 86                    .size_full()
 87                    .justify_center()
 88                    .items_center()
 89                    .border_1()
 90                    .text_color(gpui::blue())
 91                    .child(div().child("This is background text.")),
 92            )
 93            .child(
 94                div()
 95                    .id("panel")
 96                    .on_click(cx.listener(Self::change_opacity))
 97                    .absolute()
 98                    .top_8()
 99                    .left_8()
100                    .right_8()
101                    .bottom_8()
102                    .opacity(self.opacity)
103                    .flex()
104                    .justify_center()
105                    .items_center()
106                    .bg(gpui::white())
107                    .border_3()
108                    .border_color(gpui::red())
109                    .text_color(gpui::yellow())
110                    .child(
111                        div()
112                            .flex()
113                            .flex_col()
114                            .gap_2()
115                            .justify_center()
116                            .items_center()
117                            .size(px(300.))
118                            .bg(gpui::blue())
119                            .border_3()
120                            .border_color(gpui::black())
121                            .shadow(smallvec::smallvec![BoxShadow {
122                                color: hsla(0.0, 0.0, 0.0, 0.5),
123                                blur_radius: px(1.0),
124                                spread_radius: px(5.0),
125                                offset: point(px(10.0), px(10.0)),
126                            }])
127                            .child(img("image/app-icon.png").size_8())
128                            .child("Opacity Panel (Click to test)")
129                            .child(
130                                div()
131                                    .id("deep-level-text")
132                                    .flex()
133                                    .justify_center()
134                                    .items_center()
135                                    .p_4()
136                                    .bg(gpui::black())
137                                    .text_color(gpui::white())
138                                    .text_decoration_2()
139                                    .text_decoration_wavy()
140                                    .text_decoration_color(gpui::red())
141                                    .child(format!("opacity: {:.1}", self.opacity)),
142                            )
143                            .child(
144                                svg()
145                                    .path("image/arrow_circle.svg")
146                                    .text_color(gpui::black())
147                                    .text_2xl()
148                                    .size_8(),
149                            )
150                            .child("🎊✈️🎉🎈🎁🎂")
151                            .child(img("image/black-cat-typing.gif").size_12()),
152                    ),
153            )
154    }
155}
156
157fn main() {
158    Application::new()
159        .with_assets(Assets {
160            base: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples"),
161        })
162        .run(|cx: &mut App| {
163            let bounds = Bounds::centered(None, size(px(500.0), px(500.0)), cx);
164            cx.open_window(
165                WindowOptions {
166                    window_bounds: Some(WindowBounds::Windowed(bounds)),
167                    ..Default::default()
168                },
169                |window, cx| cx.new(|cx| HelloWorld::new(window, cx)),
170            )
171            .unwrap();
172            cx.activate(true);
173        });
174}