about summary refs log tree commit diff
path: root/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.rs')
-rw-r--r--src/main.rs182
1 files changed, 131 insertions, 51 deletions
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 }
+}
+