Toggle the Comet when pressing F12

This commit is contained in:
Héctor Ramón Jiménez 2024-05-11 12:25:44 +02:00
parent fc53a97831
commit b7c65c877d
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
9 changed files with 125 additions and 35 deletions

View file

@ -37,7 +37,7 @@ qr_code = ["iced_widget/qr_code"]
# Enables lazy widgets
lazy = ["iced_widget/lazy"]
# Enables a debug view in native platforms (press F12)
debug = ["iced_debug/enable"]
debug = ["iced_winit/debug"]
# Enables `tokio` as the `executor::Default` on native platforms
tokio = ["iced_futures/tokio"]
# Enables `async-std` as the `executor::Default` on native platforms
@ -62,8 +62,8 @@ fira-sans = ["iced_renderer/fira-sans"]
auto-detect-theme = ["iced_core/auto-detect-theme"]
[dependencies]
iced_core.workspace = true
iced_debug.workspace = true
iced_core.workspace = true
iced_futures.workspace = true
iced_renderer.workspace = true
iced_widget.workspace = true

View file

@ -9,6 +9,7 @@ use tokio::net;
use tokio::sync::mpsc;
use tokio::time;
use std::sync::atomic::{self, AtomicBool};
use std::sync::Arc;
use std::thread;
@ -17,6 +18,7 @@ pub const SERVER_ADDRESS: &str = "127.0.0.1:9167";
#[derive(Debug, Clone)]
pub struct Client {
sender: mpsc::Sender<Message>,
is_connected: Arc<AtomicBool>,
_handle: Arc<thread::JoinHandle<()>>,
}
@ -31,6 +33,9 @@ pub enum Message {
at: SystemTime,
event: Event,
},
Quit {
at: SystemTime,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@ -47,28 +52,50 @@ impl Client {
event,
});
}
pub fn is_connected(&self) -> bool {
self.is_connected.load(atomic::Ordering::Relaxed)
}
pub fn quit(&self) {
let _ = self.sender.try_send(Message::Quit {
at: SystemTime::now(),
});
}
}
#[must_use]
pub fn connect(name: String) -> Client {
let (sender, receiver) = mpsc::channel(100);
let is_connected = Arc::new(AtomicBool::new(false));
let handle = std::thread::spawn(move || run(name, receiver));
let handle = {
let is_connected = is_connected.clone();
std::thread::spawn(move || run(name, is_connected.clone(), receiver))
};
Client {
sender,
is_connected,
_handle: Arc::new(handle),
}
}
#[tokio::main]
async fn run(name: String, mut receiver: mpsc::Receiver<Message>) {
async fn run(
name: String,
is_connected: Arc<AtomicBool>,
mut receiver: mpsc::Receiver<Message>,
) {
let version = semver::Version::parse(env!("CARGO_PKG_VERSION"))
.expect("Parse package version");
loop {
match _connect().await {
Ok(mut stream) => {
is_connected.store(true, atomic::Ordering::Relaxed);
let _ = send(
&mut stream,
Message::Connected {
@ -92,6 +119,7 @@ async fn run(name: String, mut receiver: mpsc::Receiver<Message>) {
}
}
Err(_) => {
is_connected.store(false, atomic::Ordering::Relaxed);
time::sleep(time::Duration::from_secs(2)).await;
}
}

View file

@ -35,6 +35,12 @@ pub enum Event {
duration: Duration,
span: Span,
},
QuitRequested {
at: SystemTime,
},
AlreadyRunning {
at: SystemTime,
},
}
impl Event {
@ -43,19 +49,36 @@ impl Event {
Self::Connected { at, .. }
| Self::Disconnected { at, .. }
| Self::ThemeChanged { at, .. }
| Self::SpanFinished { at, .. } => *at,
| Self::SpanFinished { at, .. }
| Self::QuitRequested { at }
| Self::AlreadyRunning { at } => *at,
}
}
}
pub fn is_running() -> bool {
std::net::TcpListener::bind(client::SERVER_ADDRESS).is_err()
}
pub fn run() -> impl Stream<Item = Event> {
stream::channel(|mut output| async move {
let mut buffer = Vec::new();
loop {
let Ok(mut stream) = connect().await else {
delay().await;
continue;
let mut stream = match connect().await {
Ok(stream) => stream,
Err(error) => {
if error.kind() == io::ErrorKind::AddrInUse {
let _ = output
.send(Event::AlreadyRunning {
at: SystemTime::now(),
})
.await;
}
delay().await;
continue;
}
};
loop {
@ -124,6 +147,11 @@ pub fn run() -> impl Stream<Item = Event> {
}
}
}
client::Message::Quit { at } => {
let _ = output
.send(Event::QuitRequested { at })
.await;
}
};
}
Err(Error::IOFailed(_)) => {

View file

@ -9,7 +9,9 @@ pub fn init(name: &str) {
internal::init(name);
}
pub fn open_comet() {}
pub fn toggle_comet() {
internal::toggle_comet();
}
pub fn log_message(_message: &impl std::fmt::Debug) {}
@ -65,6 +67,7 @@ mod internal {
use beacon::span;
use once_cell::sync::Lazy;
use std::process;
use std::sync::atomic::{self, AtomicBool};
use std::sync::RwLock;
@ -72,6 +75,18 @@ mod internal {
name.clone_into(&mut NAME.write().expect("Write application name"));
}
pub fn toggle_comet() {
if BEACON.is_connected() {
BEACON.quit();
} else {
let _ = process::Command::new("iced_comet")
.stdin(process::Stdio::null())
.stdout(process::Stdio::null())
.stderr(process::Stdio::null())
.spawn();
}
}
pub fn theme_changed(f: impl FnOnce() -> Option<theme::Palette>) {
let Some(palette) = f() else {
return;
@ -166,6 +181,8 @@ mod internal {
pub fn init(_name: &str) {}
pub fn toggle_comet() {}
pub fn theme_changed(_f: impl FnOnce() -> Option<theme::Palette>) {}
pub fn boot() -> Span {

View file

@ -15,6 +15,7 @@ workspace = true
[features]
default = ["x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
debug = ["iced_debug/enable"]
system = ["sysinfo"]
application = []
x11 = ["winit/x11"]
@ -24,6 +25,7 @@ wayland-csd-adwaita = ["winit/wayland-csd-adwaita"]
multi-window = ["iced_runtime/multi-window"]
[dependencies]
iced_debug.workspace = true
iced_futures.workspace = true
iced_graphics.workspace = true
iced_runtime.workspace = true

View file

@ -716,6 +716,26 @@ async fn run_instance<A, E, C>(
break;
}
#[cfg(feature = "debug")]
match window_event {
winit::event::WindowEvent::KeyboardInput {
event:
winit::event::KeyEvent {
logical_key:
winit::keyboard::Key::Named(
winit::keyboard::NamedKey::F12,
),
state: winit::event::ElementState::Pressed,
repeat: false,
..
},
..
} => {
crate::debug::toggle_comet();
}
_ => {}
}
state.update(&window, &window_event);
if let Some(event) = conversion::window_event(

View file

@ -161,19 +161,6 @@ where
WindowEvent::ModifiersChanged(new_modifiers) => {
self.modifiers = new_modifiers.state();
}
#[cfg(feature = "debug")]
WindowEvent::KeyboardInput {
event:
winit::event::KeyEvent {
logical_key:
winit::keyboard::Key::Named(
winit::keyboard::NamedKey::F12,
),
state: winit::event::ElementState::Pressed,
..
},
..
} => crate::debug::open_axe(),
_ => {}
}
}

View file

@ -777,6 +777,27 @@ async fn run_instance<A, E, C>(
event: window_event,
window_id,
} => {
#[cfg(feature = "debug")]
match window_event {
winit::event::WindowEvent::KeyboardInput {
event:
winit::event::KeyEvent {
logical_key:
winit::keyboard::Key::Named(
winit::keyboard::NamedKey::F12,
),
state:
winit::event::ElementState::Pressed,
repeat: false,
..
},
..
} => {
crate::debug::toggle_comet();
}
_ => {}
}
let Some((id, window)) =
window_manager.get_mut_alias(window_id)
else {

View file

@ -173,19 +173,6 @@ where
WindowEvent::ModifiersChanged(new_modifiers) => {
self.modifiers = new_modifiers.state();
}
#[cfg(feature = "debug")]
WindowEvent::KeyboardInput {
event:
winit::event::KeyEvent {
logical_key:
winit::keyboard::Key::Named(
winit::keyboard::NamedKey::F12,
),
state: winit::event::ElementState::Pressed,
..
},
..
} => _debug.toggle(),
_ => {}
}
}