iced-yoda/devtools/src/lib.rs

513 lines
16 KiB
Rust
Raw Normal View History

#![allow(missing_docs)]
use iced_debug as debug;
use iced_program as program;
use iced_widget as widget;
use iced_widget::core;
use iced_widget::runtime;
use iced_widget::runtime::futures;
mod comet;
mod executor;
mod time_machine;
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::time_machine::TimeMachine;
use crate::widget::{
2025-04-11 01:22:54 +02:00
bottom_right, button, center, column, container, horizontal_space, opaque,
row, scrollable, stack, text, themer,
};
use std::fmt;
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,
time_machine: TimeMachine<P>,
}
#[derive(Debug, Clone)]
enum Message {
HideNotification,
ToggleComet,
CometLaunched(Result<(), comet::Error>),
InstallComet,
InstallationProgressed(Result<comet::Installation, comet::Error>),
CancelSetup,
}
enum Mode {
None,
Setup(Setup),
}
enum Setup {
Idle { goal: Goal },
Running { logs: Vec<String> },
}
enum Goal {
Installation,
Update { revision: Option<String> },
}
impl<P> DevTools<P>
where
P: Program + 'static,
{
fn new(state: P::State) -> (Self, Task<Message>) {
(
Self {
state,
mode: Mode::None,
show_notification: true,
time_machine: TimeMachine::new(),
},
executor::spawn_blocking(|mut sender| {
thread::sleep(seconds(2));
let _ = sender.try_send(());
})
.map(|_| Message::HideNotification),
)
}
fn title(&self, program: &P, window: window::Id) -> String {
program.title(&self.state, window)
}
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;
}
Task::none()
} else if debug::quit() {
Task::none()
} else {
comet::launch()
.map(Message::CometLaunched)
.map(Event::Message)
}
}
Message::CometLaunched(Ok(())) => Task::none(),
Message::CometLaunched(Err(error)) => {
match error {
comet::Error::NotFound => {
self.mode = Mode::Setup(Setup::Idle {
goal: Goal::Installation,
});
}
comet::Error::Outdated { revision } => {
self.mode = Mode::Setup(Setup::Idle {
goal: Goal::Update { revision },
});
}
comet::Error::IoFailed(error) => {
log::error!("comet failed to run: {error}");
}
}
Task::none()
}
Message::InstallComet => {
self.mode =
Mode::Setup(Setup::Running { logs: Vec::new() });
comet::install()
.map(Message::InstallationProgressed)
.map(Event::Message)
}
Message::InstallationProgressed(Ok(installation)) => {
let Mode::Setup(Setup::Running { logs }) = &mut self.mode
else {
return Task::none();
};
match installation {
comet::Installation::Logged(log) => {
logs.push(log);
Task::none()
}
comet::Installation::Finished => {
self.mode = Mode::None;
comet::launch().discard()
}
}
}
Message::InstallationProgressed(_error) => {
// TODO
Task::none()
}
Message::CancelSetup => {
self.mode = Mode::None;
Task::none()
}
},
Event::Program(message) => {
self.time_machine.push(&message);
2025-04-20 21:50:12 +02:00
if self.time_machine.is_rewinding() {
debug::enable();
2025-04-17 03:24:17 +02:00
}
let span = debug::update(&message);
let task = program.update(&mut self.state, message);
debug::tasks_spawned(task.units());
span.finish();
if self.time_machine.is_rewinding() {
2025-04-20 21:50:12 +02:00
debug::disable();
}
2025-04-17 03:24:17 +02:00
task.map(Event::Program)
}
Event::Command(command) => {
match command {
debug::Command::RewindTo { message } => {
self.time_machine.rewind(program, message);
2025-04-17 03:24:17 +02:00
}
2025-04-20 21:50:12 +02:00
debug::Command::GoLive => {
self.time_machine.go_to_present();
2025-04-20 21:50:12 +02:00
}
2025-04-17 03:24:17 +02:00
}
Task::none()
}
2025-04-20 21:50:12 +02:00
Event::Discard => Task::none(),
}
}
fn view(
&self,
program: &P,
window: window::Id,
) -> Element<'_, Event<P>, P::Theme, P::Renderer> {
let state = self.state();
2025-04-17 03:24:17 +02:00
2025-04-20 21:50:12 +02:00
let view = {
let view = program.view(state, window);
if self.time_machine.is_rewinding() {
2025-04-20 21:50:12 +02:00
view.map(|_| Event::Discard)
} else {
view.map(Event::Program)
}
};
2025-04-17 03:24:17 +02:00
let theme = program.theme(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 { goal } => {
let controls = row![
button(text("Cancel").center().width(Fill))
.width(100)
.on_press(Message::CancelSetup)
.style(button::danger),
horizontal_space(),
button(
text(match goal {
Goal::Installation => "Install",
Goal::Update { .. } => "Update",
})
.center()
.width(Fill)
)
.width(100)
.on_press(Message::InstallComet)
.style(button::success),
];
let command = container(
text(
"cargo install --locked \
--git https://github.com/iced-rs/comet.git",
)
.size(14),
)
.width(Fill)
.padding(5)
.style(container::dark);
match goal {
Goal::Installation => 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?",
command,
controls,
]
.spacing(20),
Goal::Update { revision } => column![
text("comet is out of date!").size(20),
text!(
"The installed revision is \"{current}\", \
but the latest compatible is \"{compatible}\".",
current = revision
.as_deref()
.unwrap_or("Unknown"),
compatible = comet::COMPATIBLE_REVISION,
),
"Do you wish to update it with the following \
command?",
command,
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(),
2025-04-11 01:22:54 +02:00
bottom_right(opaque(
container(text("Press F12 to open debug metrics"))
.padding(10)
.style(container::dark),
2025-04-11 01:22:54 +02:00
)),
)
});
stack![view]
2025-04-17 03:24:17 +02:00
.height(Fill)
2025-04-11 01:22:54 +02:00
.push_maybe(mode.map(opaque))
.push_maybe(notification)
.into()
}
fn subscription(&self, program: &P) -> Subscription<Event<P>> {
let subscription =
program.subscription(&self.state).map(Event::Program);
2025-04-17 03:24:17 +02:00
debug::subscriptions_tracked(subscription.units());
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);
2025-04-17 03:24:17 +02:00
let commands = debug::commands().map(Event::Command);
Subscription::batch([subscription, hotkeys, commands])
}
fn theme(&self, program: &P, window: window::Id) -> P::Theme {
program.theme(self.state(), window)
}
fn style(&self, program: &P, theme: &P::Theme) -> theme::Style {
program.style(self.state(), theme)
}
fn scale_factor(&self, program: &P, window: window::Id) -> f64 {
program.scale_factor(self.state(), window)
}
fn state(&self) -> &P::State {
self.time_machine.state().unwrap_or(&self.state)
}
}
enum Event<P>
where
P: Program,
{
Message(Message),
Program(P::Message),
2025-04-17 03:24:17 +02:00
Command(debug::Command),
2025-04-20 21:50:12 +02:00
Discard,
}
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),
2025-04-17 03:24:17 +02:00
Self::Command(command) => command.fmt(f),
2025-04-20 21:50:12 +02:00
Self::Discard => f.write_str("Discard"),
2025-04-17 03:24:17 +02:00
}
}
}
#[cfg(feature = "time-travel")]
impl<P> Clone for Event<P>
where
P: Program,
{
fn clone(&self) -> Self {
match self {
2025-04-20 21:50:12 +02:00
Self::Message(message) => Self::Message(message.clone()),
Self::Program(message) => Self::Program(message.clone()),
Self::Command(command) => Self::Command(*command),
Self::Discard => Self::Discard,
}
}
}