ferrishot_iced_devtools 0.14.1

devtools
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
413
414
415
416
417
418
#![allow(missing_docs)]
use ferrishot_iced_debug as debug;
use ferrishot_iced_program as program;
use ferrishot_iced_widget as widget;
use ferrishot_iced_widget::core;
use ferrishot_iced_widget::runtime;
use ferrishot_iced_widget::runtime::futures;

mod executor;

use crate::core::keyboard;
use crate::core::theme::{self, Base, Theme};
use crate::core::time::seconds;
use crate::core::window;
use crate::core::{Color, Element, Length::Fill};
use crate::futures::Subscription;
use crate::program::Program;
use crate::runtime::Task;
use crate::widget::{
    bottom_right, button, center, column, container, horizontal_space, opaque,
    row, scrollable, stack, text, themer,
};

use std::fmt;
use std::io;
use std::thread;

pub fn attach(program: impl Program + 'static) -> impl Program {
    struct Attach<P> {
        program: P,
    }

    impl<P> Program for Attach<P>
    where
        P: Program + 'static,
    {
        type State = DevTools<P>;
        type Message = Event<P>;
        type Theme = P::Theme;
        type Renderer = P::Renderer;
        type Executor = P::Executor;

        fn name() -> &'static str {
            P::name()
        }

        fn boot(&self) -> (Self::State, Task<Self::Message>) {
            let (state, boot) = self.program.boot();
            let (devtools, task) = DevTools::new(state);

            (
                devtools,
                Task::batch([
                    boot.map(Event::Program),
                    task.map(Event::Message),
                ]),
            )
        }

        fn update(
            &self,
            state: &mut Self::State,
            message: Self::Message,
        ) -> Task<Self::Message> {
            state.update(&self.program, message)
        }

        fn view<'a>(
            &self,
            state: &'a Self::State,
            window: window::Id,
        ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> {
            state.view(&self.program, window)
        }

        fn title(&self, state: &Self::State, window: window::Id) -> String {
            state.title(&self.program, window)
        }

        fn subscription(
            &self,
            state: &Self::State,
        ) -> runtime::futures::Subscription<Self::Message> {
            state.subscription(&self.program)
        }

        fn theme(
            &self,
            state: &Self::State,
            window: window::Id,
        ) -> Self::Theme {
            state.theme(&self.program, window)
        }

        fn style(
            &self,
            state: &Self::State,
            theme: &Self::Theme,
        ) -> theme::Style {
            state.style(&self.program, theme)
        }

        fn scale_factor(&self, state: &Self::State, window: window::Id) -> f64 {
            state.scale_factor(&self.program, window)
        }
    }

    Attach { program }
}

struct DevTools<P>
where
    P: Program,
{
    state: P::State,
    mode: Mode,
    show_notification: bool,
}

#[derive(Debug, Clone)]
enum Message {
    HideNotification,
    ToggleComet,
    InstallComet,
    InstallationLogged(String),
    InstallationFinished,
    CancelSetup,
}

enum Mode {
    None,
    Setup(Setup),
}

enum Setup {
    Idle,
    Running { logs: Vec<String> },
}

impl<P> DevTools<P>
where
    P: Program + 'static,
{
    pub fn new(state: P::State) -> (Self, Task<Message>) {
        (
            Self {
                state,
                mode: Mode::None,
                show_notification: true,
            },
            executor::spawn_blocking(|mut sender| {
                thread::sleep(seconds(2));
                let _ = sender.try_send(());
            })
            .map(|_| Message::HideNotification),
        )
    }

    pub fn title(&self, program: &P, window: window::Id) -> String {
        program.title(&self.state, window)
    }

    pub fn update(&mut self, program: &P, event: Event<P>) -> Task<Event<P>> {
        match event {
            Event::Message(message) => match message {
                Message::HideNotification => {
                    self.show_notification = false;

                    Task::none()
                }
                Message::ToggleComet => {
                    if let Mode::Setup(setup) = &self.mode {
                        if matches!(setup, Setup::Idle) {
                            self.mode = Mode::None;
                        }
                    } else if let Err(error) = debug::toggle_comet() {
                        if error.kind() == io::ErrorKind::NotFound {
                            self.mode = Mode::Setup(Setup::Idle);
                        }
                    }

                    Task::none()
                }
                Message::InstallComet => {
                    self.mode =
                        Mode::Setup(Setup::Running { logs: Vec::new() });

                    executor::spawn_blocking(|mut sender| {
                        use std::io::{BufRead, BufReader};
                        use std::process::{Command, Stdio};

                        let Ok(install) = Command::new("cargo")
                            .args([
                                "install",
                                "--locked",
                                "--git",
                                "https://github.com/iced-rs/comet.git",
                                "--rev",
                                "fc9832833f81a8e95e2c4ab8e7e65dcc3c000253",
                            ])
                            .stdin(Stdio::null())
                            .stdout(Stdio::null())
                            .stderr(Stdio::piped())
                            .spawn()
                        else {
                            return;
                        };

                        let mut stderr = BufReader::new(
                            install.stderr.expect("stderr must be piped"),
                        );

                        let mut log = String::new();

                        while let Ok(n) = stderr.read_line(&mut log) {
                            if n == 0 {
                                break;
                            }

                            let _ = sender.try_send(
                                Message::InstallationLogged(log.clone()),
                            );

                            log.clear();
                        }

                        let _ = sender.try_send(Message::InstallationFinished);
                    })
                    .map(Event::Message)
                }
                Message::InstallationLogged(log) => {
                    if let Mode::Setup(Setup::Running { logs }) = &mut self.mode
                    {
                        logs.push(log);
                    }

                    Task::none()
                }
                Message::InstallationFinished => {
                    self.mode = Mode::None;

                    let _ = debug::toggle_comet();

                    Task::none()
                }
                Message::CancelSetup => {
                    self.mode = Mode::None;

                    Task::none()
                }
            },
            Event::Program(message) => {
                program.update(&mut self.state, message).map(Event::Program)
            }
        }
    }

    pub fn view(
        &self,
        program: &P,
        window: window::Id,
    ) -> Element<'_, Event<P>, P::Theme, P::Renderer> {
        let view = program.view(&self.state, window).map(Event::Program);
        let theme = program.theme(&self.state, window);

        let derive_theme = move || {
            theme
                .palette()
                .map(|palette| Theme::custom("DevTools".to_owned(), palette))
                .unwrap_or_default()
        };

        let mode = match &self.mode {
            Mode::None => None,
            Mode::Setup(setup) => {
                let stage: Element<'_, _, Theme, P::Renderer> = match setup {
                    Setup::Idle => {
                        let controls = row![
                            button(text("Cancel").center().width(Fill))
                                .width(100)
                                .on_press(Message::CancelSetup)
                                .style(button::danger),
                            horizontal_space(),
                            button(text("Install").center().width(Fill))
                                .width(100)
                                .on_press(Message::InstallComet)
                                .style(button::success),
                        ];

                        column![
                            text("comet is not installed!").size(20),
                            "In order to display performance metrics, the \
                            comet debugger must be installed in your system.",
                            "The comet debugger is an official companion tool \
                            that helps you debug your iced applications.",
                            "Do you wish to install it with the following \
                            command?",
                            container(
                                text(
                                    "cargo install --locked \
                                    --git https://github.com/iced-rs/comet.git"
                                )
                                .size(14)
                            )
                            .width(Fill)
                            .padding(5)
                            .style(container::dark),
                            controls,
                        ]
                        .spacing(20)
                        .into()
                    }
                    Setup::Running { logs } => column![
                        text("Installing comet...").size(20),
                        container(
                            scrollable(
                                column(
                                    logs.iter()
                                        .map(|log| text(log).size(12).into()),
                                )
                                .spacing(3),
                            )
                            .spacing(10)
                            .width(Fill)
                            .height(300)
                            .anchor_bottom(),
                        )
                        .padding(10)
                        .style(container::dark)
                    ]
                    .spacing(20)
                    .into(),
                };

                let setup = center(
                    container(stage)
                        .padding(20)
                        .width(500)
                        .style(container::bordered_box),
                )
                .padding(10)
                .style(|_theme| {
                    container::Style::default()
                        .background(Color::BLACK.scale_alpha(0.8))
                });

                Some(setup)
            }
        }
        .map(|mode| {
            themer(derive_theme(), Element::from(mode).map(Event::Message))
        });

        let notification = self.show_notification.then(|| {
            themer(
                derive_theme(),
                bottom_right(opaque(
                    container(text("Press F12 to open debug metrics"))
                        .padding(10)
                        .style(container::dark),
                )),
            )
        });

        stack![view]
            .push_maybe(mode.map(opaque))
            .push_maybe(notification)
            .into()
    }

    pub fn subscription(&self, program: &P) -> Subscription<Event<P>> {
        let subscription =
            program.subscription(&self.state).map(Event::Program);

        let hotkeys =
            futures::keyboard::on_key_press(|key, _modifiers| match key {
                keyboard::Key::Named(keyboard::key::Named::F12) => {
                    Some(Message::ToggleComet)
                }
                _ => None,
            })
            .map(Event::Message);

        Subscription::batch([subscription, hotkeys])
    }

    pub fn theme(&self, program: &P, window: window::Id) -> P::Theme {
        program.theme(&self.state, window)
    }

    pub fn style(&self, program: &P, theme: &P::Theme) -> theme::Style {
        program.style(&self.state, theme)
    }

    pub fn scale_factor(&self, program: &P, window: window::Id) -> f64 {
        program.scale_factor(&self.state, window)
    }
}

enum Event<P>
where
    P: Program,
{
    Message(Message),
    Program(P::Message),
}

impl<P> fmt::Debug for Event<P>
where
    P: Program,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Message(message) => message.fmt(f),
            Self::Program(message) => message.fmt(f),
        }
    }
}