about summary refs log tree commit diff
diff options
context:
space:
mode:
authorIrene Knapp <ireneista@irenes.space>2026-11-15 22:30:48 -0700
committerIrene Knapp <ireneista@irenes.space>2026-11-15 22:30:48 -0700
commit73296ede1fc7b1abde65546a71aef5a988c21e8d (patch)
treef19bdf87f74663f207975353b3b90420084fc2fa
parent5b488f558ccaca6ac35edda0366d74b9126285e3 (diff)
multi-threaded. more dependencies :( the clock runs now!
some unfortunate reliance on exact sequencing, which needs to be cleaned up

Force-Push: yes
Change-Id: I833dd0dd5047e3c2f04203e80e3fd722e36bf252
-rw-r--r--Cargo.lock54
-rw-r--r--Cargo.toml5
-rw-r--r--src/error.rs34
-rw-r--r--src/main.rs182
-rw-r--r--src/modules/time.rs5
5 files changed, 227 insertions, 53 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 3e1a3ed..ed87140 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3,6 +3,32 @@
 version = 4
 
 [[package]]
+name = "async-channel"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
+dependencies = [
+ "concurrent-queue",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-executor"
+version = "1.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
+dependencies = [
+ "async-task",
+ "concurrent-queue",
+ "fastrand",
+ "futures-lite",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
 name = "async-io"
 version = "2.6.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -21,6 +47,12 @@ dependencies = [
 ]
 
 [[package]]
+name = "async-task"
+version = "4.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
+
+[[package]]
 name = "autocfg"
 version = "1.5.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -70,6 +102,26 @@ dependencies = [
 ]
 
 [[package]]
+name = "event-listener"
+version = "5.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
+dependencies = [
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener-strategy"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
+dependencies = [
+ "event-listener",
+ "pin-project-lite",
+]
+
+[[package]]
 name = "fastrand"
 version = "2.5.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -221,6 +273,8 @@ dependencies = [
 name = "sandbar"
 version = "1.0.0"
 dependencies = [
+ "async-channel",
+ "async-executor",
  "async-io",
  "futures-lite",
  "time",
diff --git a/Cargo.toml b/Cargo.toml
index fe5a94c..49c7fe1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,9 +5,14 @@ authors = ["Irene Knapp <ireneista@gmail.com>"]
 edition = "2024"
 
 [dependencies]
+async-channel = "2.0.0"
 async-io = "2.1.0"
 futures-lite = "2.0.0"
 
+[dependencies.async-executor]
+version = "1.5.0"
+features = [ "static" ]
+
 [dependencies.time]
 version = "0.3.55"
 features = [ "local-offset", "macros", "formatting" ]
diff --git a/src/error.rs b/src/error.rs
index 81c69e5..8537d2e 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -5,12 +5,37 @@ pub struct Error(String);
 pub type Result<T> = std::result::Result<T, Error>;
 
 
+impl Error {
+  pub fn log(&self) {
+    println!("Error: {}", self);
+  }
+}
+
+
 impl Display for Error {
   fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     write!(formatter, "Error: {}", self.0)
   }
 }
 
+impl<T> From<std::sync::PoisonError<T>> for Error {
+  fn from(error: std::sync::PoisonError<T>) -> Error {
+    Error(format!("Lock poisoned: {}", error))
+  }
+}
+
+impl From<async_channel::RecvError> for Error {
+  fn from(error: async_channel::RecvError) -> Error {
+    Error(format!("Channel receive error: {}", error))
+  }
+}
+
+impl<T> From<async_channel::SendError<T>> for Error {
+  fn from(error: async_channel::SendError<T>) -> Error {
+    Error(format!("Channel send error: {}", error))
+  }
+}
+
 impl From<xcb::Error> for Error {
   fn from(error: xcb::Error) -> Error {
     match error {
@@ -33,3 +58,12 @@ impl From<xcb::ProtocolError> for Error {
 }
 
 
+pub fn log_and_ignore_errors<T, E: Into<Error>>(
+           result: std::result::Result<T, E>)
+{
+  match result {
+    Ok(_) => (),
+    Err(error) => Into::<Error>::into(error).log()
+  }
+}
+
diff --git a/src/main.rs b/src/main.rs
index 2ca4259..bf0dfda 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,11 +1,18 @@
+#![allow(linker_messages)]
 use crate::error::*;
 use crate::geometry::*;
 use crate::modules::*;
 use crate::x::*;
 
+use std::num::NonZero;
+use std::process::ExitCode;
 use std::sync::Arc;
+use std::sync::Mutex;
 use std::time::Duration;
 
+use async_channel::{ Sender, Receiver };
+use async_executor::StaticExecutor;
+use futures_lite::future;
 use xcb::{ Xid };
 use xcb::x::{
   ClearArea,
@@ -25,6 +32,9 @@ mod modules;
 mod x;
 
 
+static EXECUTOR: StaticExecutor = StaticExecutor::new();
+
+
 struct DockConfiguration {
   thickness: u16,
   baseline_offset: i8,
@@ -42,7 +52,7 @@ struct Dock {
   bounds: Arc<Rectangle<u16>>,
   font: Arc<Font>,
   baseline_position: i16,
-  time_module: TimeModule,
+  time_module: Arc<Mutex<TimeModule>>,
 }
 
 impl HasWindow for Dock {
@@ -50,17 +60,62 @@ impl HasWindow for Dock {
 }
 
 
-fn main() -> Result<()> {
-  async_io::block_on(async {
-    let display = Arc::new(Display::new()?);
+fn main() -> ExitCode {
+  let (shutdown_sender, shutdown_receiver) = async_channel::unbounded();
+
+  let n_extra_threads = std::thread::available_parallelism()
+			    .map(|i| i.into()).unwrap_or(1);
+  for _ in 0 .. n_extra_threads {
+    let child_receiver = Receiver::clone(&shutdown_receiver);
+
+    let _ = std::thread::spawn(move || {
+      log_and_ignore_errors(future::block_on(
+	  EXECUTOR.run(child_receiver.recv())));
+    });
+  }
+
+  future::block_on(async {
+    if let Err(error) = async_main(shutdown_sender).await {
+      error.log();
+      println!("That means... we are released from our task. Fare well.");
+      ExitCode::FAILURE
+    } else { ExitCode::SUCCESS }
+  })
+}
+
+
+async fn async_main(_shutdown_sender: Sender<()>) -> Result<()> {
+  let display = Arc::new(Display::new()?);
+  let configuration = DockConfiguration::new(&display)?;
+  let dock = Dock::new(Arc::clone(&display), configuration)?;
+
+  let (redraw_sender, redraw_receiver) = async_channel::unbounded();
+  let event_task = EXECUTOR.spawn(
+	  event_loop(display, Sender::clone(&redraw_sender)));
+
+  /*   Recall that Dock is non-Send, because it holds pointers to xft
+   * state, which are opaque from our perspective. Thus, we have to do
+   * this on the primary thread.
+   *
+   *   Or we could Mutex-ify everything, but this is simpler.
+   */
+  redraw_loop(dock, redraw_sender, redraw_receiver).await;
+
+  event_task.cancel();
+
+  Ok(())
+}
+
 
+impl DockConfiguration {
+  fn new(display: &Arc<Display>) -> Result<DockConfiguration> {
     // #d4ffcc
     let background = display.allocate_color(54484, 65535, 52428)?;
 
     // #5c01be
     let foreground = display.allocate_color(23644, 257, 48830)?;
 
-    let mut dock = Dock::new(Arc::clone(&display), DockConfiguration {
+    Ok(DockConfiguration {
       thickness: 34,
       baseline_offset: 2,
       edge_inset: 12,
@@ -68,40 +123,8 @@ fn main() -> Result<()> {
       background, foreground,
       use_rounded_inside_corners: false,
       use_rounded_outside_corners: true,
-    })?;
-
-    loop {
-      match display.wait_for_event()? {
-        xcb::Event::X(xcb::x::Event::Expose(_event)) => {
-          match dock.redraw() {
-            Ok(Some(duration)) => {
-              dock.connection().flush()?;
-              println!("sleeping");
-              std::thread::sleep(duration);
-            }
-            Ok(None) => { }
-            Err(_) => { } // TODO
-          }
-        }
-
-        xcb::Event::X(xcb::x::Event::ButtonPress(event)) => {
-          println!("click {:?}", event);
-        }
-
-        xcb::Event::X(xcb::x::Event::ClientMessage(event)) => {
-          if let ClientMessageData::Data32([atom, ..]) = event.data() {
-            if atom == display.atoms().wm_delete_window.resource_id() {
-              break;
-            }
-          }
-        }
-
-        event => { println!("unknown event {:?}", event); }
-      }
-    }
-
-    Ok(())
-  })
+    })
+  }
 }
 
 
@@ -241,7 +264,7 @@ impl Dock {
   }
 
 
-  fn redraw(&mut self) -> Result<Option<Duration>> {
+  async fn redraw(&self) -> Result<Option<Duration>> {
     let drawable = Drawable::Window(self.window_id());
     let context = GraphicContext::new(
                       Arc::clone(self.display()), drawable)?;
@@ -257,21 +280,13 @@ impl Dock {
 
     self.draw_text("playful cool fic tech nonfic", Alignment::Left)?;
 
-    let time = self.time_module.format();
+    let time = self.time_module.lock()?.format();
     self.draw_text(&time, Alignment::Right)?;
 
     let mut shortest_duration = None;
 
-    let next_duration = self.time_module.sleep_duration();
-    if let Some(old_value) = shortest_duration {
-      if let Some(new_value) = next_duration
-         && new_value < old_value
-      {
-        shortest_duration = Some(new_value);
-      }
-    } else {
-      shortest_duration = next_duration;
-    }
+    let next_duration = self.time_module.lock()?.sleep_duration();
+    shortest_duration = shorter_duration(shortest_duration, next_duration);
 
     Ok(shortest_duration)
   }
@@ -279,6 +294,7 @@ impl Dock {
 
   fn erase_all(&self) -> Result<()> {
     let cookie = self.send_request_checked(&ClearArea {
+      // TODO load-bearing...
       exposures: true,
       window: self.window().window_id(),
       x: 0,
@@ -403,3 +419,67 @@ impl HasConnection for Dock {
 }
 
 
+async fn event_loop(display: Arc<Display>, sender: Sender<()>) {
+  loop {
+    println!("waiting for event");
+    match display.wait_for_event() {
+      result@Err(_) => log_and_ignore_errors(result),
+
+      Ok(xcb::Event::X(xcb::x::Event::Expose(_event))) => {
+        log_and_ignore_errors(sender.send(()).await);
+      }
+
+      Ok(xcb::Event::X(xcb::x::Event::ButtonPress(event))) => {
+        println!("click {:?}", event);
+      }
+
+      Ok(xcb::Event::X(xcb::x::Event::ClientMessage(event))) => {
+        if let ClientMessageData::Data32([atom, ..]) = event.data() {
+          if atom == display.atoms().wm_delete_window.resource_id() {
+            break;
+          }
+        }
+      }
+
+      Ok(event) => { println!("unknown event {:?}", event); }
+    }
+  }
+}
+
+
+async fn redraw_loop(dock: Dock,
+                     redraw_sender: Sender<()>,
+                     redraw_receiver: Receiver<()>)
+{
+  loop {
+    println!("awaiting redraw notification");
+    if let Ok(()) = redraw_receiver.recv().await {
+      match dock.redraw().await {
+        Ok(Some(duration)) => {
+          if let Err(error) = dock.connection().flush() {
+	    Into::<Error>::into(error).log();
+	  }
+          println!("sleeping");
+          std::thread::sleep(duration);
+	  // TODO
+          //redraw_sender.send(()).await;
+        }
+        Ok(None) => { }
+        result@Err(_) => log_and_ignore_errors(result)
+      }
+    } else { break }
+  }
+}
+
+
+
+fn shorter_duration(a: Option<Duration>, b: Option<Duration>)
+  -> Option<Duration>
+{
+  if let Some(a_value) = a {
+    if let Some(b_value) = b
+       && b_value < a_value
+    { b } else { a }
+  } else { b }
+}
+
diff --git a/src/modules/time.rs b/src/modules/time.rs
index 8f6f417..f8ef95c 100644
--- a/src/modules/time.rs
+++ b/src/modules/time.rs
@@ -1,3 +1,4 @@
+use std::sync::{ Arc, Mutex };
 use std::time::Duration;
 
 use time::OffsetDateTime;
@@ -10,14 +11,14 @@ pub struct TimeModule {
 
 
 impl TimeModule {
-  pub fn new() -> TimeModule {
+  pub fn new() -> Arc<Mutex<TimeModule>> {
     let format_string = 
         "[weekday repr:short] [year]-[month]-[day] ".to_owned()
         + "[hour repr:24]:[minute]:[second]";
 
     let time_format = parse_owned::<3>(&format_string).unwrap();
 
-    TimeModule { time_format }
+    Arc::new(Mutex::new(TimeModule { time_format }))
   }
 
   pub fn format(&mut self) -> String {