about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorIrene Knapp <ireneista@irenes.space>2026-11-26 01:58:35 -0700
committerIrene Knapp <ireneista@irenes.space>2026-11-26 01:58:35 -0700
commit66e5b1c78382dfa489c447b4e0cd1dc70c152f96 (patch)
tree2d8a6494e4fd2c226330fcd375e8f501dbd6d34e /src
parentb3cb3553ab5c4649b0fe6b5f94ac42c5b69e8f89 (diff)
the i3 workspace module now works, yay!
Force-Push: yes
Change-Id: Ica29bfa0b8ead44372567e6c43b7d36cdce6545a
Diffstat (limited to 'src')
-rw-r--r--src/module/i3_workspace.rs108
1 files changed, 89 insertions, 19 deletions
diff --git a/src/module/i3_workspace.rs b/src/module/i3_workspace.rs
index d70bd3d..d6a3570 100644
--- a/src/module/i3_workspace.rs
+++ b/src/module/i3_workspace.rs
@@ -1,8 +1,10 @@
 use crate::error::{ Error, Result };
 use crate::facility::{ FacilityMap, FacilityType };
 use crate::facility::i3::{ EventType, I3 };
+use crate::json::{ parse_json, Value };
 use crate::module::{ CreatableModule, Module };
 
+use std::collections::BTreeMap;
 use std::sync::Arc;
 use std::time::Duration;
 
@@ -15,7 +17,7 @@ use futures_lite::future::block_on;
 
 pub struct I3WorkspaceModule {
   _update_task: Task<()>,
-  workspaces: Arc<Mutex<Vec<Workspace>>>,
+  workspaces: Arc<Mutex<BTreeMap<u64, Workspace>>>,
 }
 
 struct Workspace {
@@ -41,7 +43,28 @@ impl CreatableModule for I3WorkspaceModule {
       return Err(Error::custom("Unable to subscribe to i3 workspace changes."));
     }
 
-    let workspaces = Arc::new(Mutex::new(Vec::new()));
+    let mut workspaces = BTreeMap::new();
+    let json = i3.command(1, "").await?;
+    if let Value::Array(entries) = parse_json(json.as_bytes())? {
+      for entry in entries {
+        if let Value::Object(entry) = entry
+           && let Some(Value::String(name)) = entry.get("name")
+           && let Some(Value::Integer(index)) = entry.get("num")
+           && let Some(Value::Boolean(is_focused)) = entry.get("focused")
+        {
+          workspaces.insert(*index as u64, Workspace {
+            name: String::clone(name),
+            is_focused: *is_focused,
+          });
+        } else {
+          return Err(Error::custom(
+              "Unexpected format of initial i3 workspace data."));
+        }
+      }
+    } else {
+      return Err(Error::custom("Unable to check initial i3 workspaces."));
+    }
+    let workspaces = Arc::new(Mutex::new(workspaces));
 
     let update_task = executor.spawn(update_loop(receiver,
                                                  Arc::clone(&workspaces),
@@ -57,16 +80,19 @@ impl CreatableModule for I3WorkspaceModule {
 impl Module for I3WorkspaceModule {
   fn format(&mut self, _facilities: &mut FacilityMap) -> Result<String> {
     /* A shame we can't be async. */
-    let workspaces = self.workspaces.lock();
+    let workspaces = block_on(self.workspaces.lock());
 
     let mut text = String::new();
     let mut is_first = true;
-    for name in vec!["playful", "cool", "fic", "tech", "nonfic"] {
-      if is_first {
-	text.push_str(" ");
+    for (_, workspace) in workspaces.iter() {
+      if !is_first {
+        text.push_str(" ");
       }
 
-      text.push_str(name);
+      if workspace.is_focused {
+        text.push_str("*");
+      }
+      text.push_str(&workspace.name);
 
       is_first = false;
     }
@@ -85,23 +111,67 @@ impl Module for I3WorkspaceModule {
 
 
 async fn update_loop(receiver: Receiver<(EventType, String)>,
-                     workspaces: Arc<Mutex<Vec<Workspace>>>,
+                     workspaces: Arc<Mutex<BTreeMap<u64, Workspace>>>,
                      redraw_sender: Sender<()>)
 {
   loop {
     match receiver.recv().await {
-      Ok((_, body)) => {
-        println!("{}", body);
-        //match parse_change_string(body.as_bytes()) {
-          //Ok(new_workspaces) => {
-            let mut _workspaces = workspaces.lock().await;
-
-            if let Err(error) = redraw_sender.send(()).await {
-              Into::<Error>::into(error).log()
+      Ok((_, json)) => {
+        if let Ok(Value::Object(change)) = parse_json(json.as_bytes())
+           && let Some(Value::String(change_type)) = change.get("change")
+           && let Some(Value::Object(current)) = change.get("current")
+           && let Some(Value::String(current_name)) = current.get("name")
+           && let Some(Value::Integer(current_index)) = current.get("num")
+        {
+          /*   We'll want to release the workspace lock before we're done, so
+           * let's have a scope for that.
+           */
+          {
+            let mut workspaces = workspaces.lock().await;
+
+            /*   It's tempting to try to write some generic logic, but the
+             * meaning of "current" is specific to the change verb. It's not
+             * always the focused workspace. So, this all has to be broken down
+             * by change type.
+             */
+            if change_type == "empty" {
+              /*   For this event, the meaning of "current" is the workspace
+               * being removed.
+               */
+              let _ = workspaces.remove(&(*current_index as u64));
+            } else if *change_type == "init" {
+              /*   All we do is create the workspace here. We'll get a focus
+               * event right after, and that one will fix the focus.
+               */
+              workspaces.insert(*current_index as u64, Workspace {
+                name: String::clone(current_name),
+                is_focused: true,
+              });
+            } else if *change_type == "focus" {
+              if let Some(Value::Object(old)) = change.get("old")
+                 && let Some(Value::Integer(old_index)) = old.get("num")
+                 && let Some(entry) = workspaces.get_mut(&(*old_index as u64))
+              {
+                entry.is_focused = false;
+              }
+
+              /*   Notice that the workspace already exists; we don't need to
+               * create it as part of "focus".
+               */
+              if let Some(entry) = workspaces.get_mut(&(*current_index as u64)) {
+                entry.is_focused = true;
+              }
             }
-          //}
-          //Err(error) => { error.log(); }
-        //}
+          }
+
+          /* Notice we released the mutex first. */
+          if let Err(error) = redraw_sender.send(()).await {
+            Into::<Error>::into(error).log()
+          }
+        }
+        /*   If it's not in an expected format, ignore it; that's probably not
+         * our fault, so there's no point spamming the logs.
+         */
       }
       Err(error) => {
         Into::<Error>::into(error).log();