about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock4
-rw-r--r--Cargo.toml2
-rw-r--r--src/facility/i3.rs53
-rw-r--r--src/json.rs207
-rw-r--r--src/main.rs13
-rw-r--r--src/module.rs2
-rw-r--r--src/module/i3_workspace.rs112
7 files changed, 348 insertions, 45 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 9350b7f..48c6ca6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -212,9 +212,9 @@ checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
 
 [[package]]
 name = "json-event-parser"
-version = "0.2.3"
+version = "0.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "574b0cd5e90ee2ba03a66d0611fc9a09c9a0c28b2ecc2dc8a181dd31a53ca5d7"
+checksum = "a121688e494b9dce01de697297fba5cf6ef2324d76cd052125dfe5c01839d094"
 
 [[package]]
 name = "libc"
diff --git a/Cargo.toml b/Cargo.toml
index 50e7f42..9b776de 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,7 +12,7 @@ async-lock = "3.0.0"
 async-net = "2.0.0"
 async-task = "4.7.1"
 libc = "0.2.191"
-json-event-parser = "0.2.3"
+json-event-parser = "0.3.0"
 futures-lite = "2.0.0"
 xml = "1.4.0"
 
diff --git a/src/facility/i3.rs b/src/facility/i3.rs
index 4dd4a87..9435b45 100644
--- a/src/facility/i3.rs
+++ b/src/facility/i3.rs
@@ -1,5 +1,6 @@
 use crate::error::{ Error, Result };
 use crate::facility::{ CreatableFacility, Facility, FacilityType };
+use crate::json::{ parse_json, Value };
 use crate::unix::get_username;
 use crate::xdg::xdg_runtime_directory;
 
@@ -20,7 +21,6 @@ use async_task::Task;
 use bitflags::bitflags;
 use futures_lite::{ AsyncReadExt, AsyncWriteExt, StreamExt };
 use futures_lite::io::{ split, ReadHalf, WriteHalf };
-use json_event_parser::{ JsonEvent, SliceJsonParser };
 
 
 #[allow(unused)]
@@ -504,54 +504,25 @@ async fn read(socket: Arc<Mutex<ReadHalf<UnixStream>>>)
 }
 
 
-/*   We make no attempt to parse fully general JSON; we exploit our knowledge
- * of the format i3 uses. Maybe later.
- */
 fn parse_success_object(json: &[u8]) -> Result<bool> {
-  let mut parser = SliceJsonParser::new(json);
-
-  if let JsonEvent::StartObject = parser.parse_next()? { } else {
-    return Err(Error::custom("Reading i3 JSON, expected object start."));
-  }
-
-  if let JsonEvent::ObjectKey(key) = parser.parse_next()? {
-    if key == "success" {
-      if let JsonEvent::Boolean(result) = parser.parse_next()? {
-        /* That's our answer; exit early. */
-        return Ok(result);
-      } else {
-        return Err(Error::custom("Reading i3 JSON, expected boolean."));
-      }
-    } else {
-      return Err(Error::custom("Reading i3 JSON, expected \"success\" key."));
-    }
+  if let Value::Object(object) = parse_json(json)?
+      && let Some(Value::Boolean(result)) = object.get("success")
+  {
+    Ok(*result)
   } else {
-    return Err(Error::custom("Reading i3 JSON, expected object key."));
+    Err(Error::custom("Reading i3 JSON, expected success boolean."))
   }
 }
 
 
 fn parse_top_level_key_string(json: &[u8], expected_key: &str) -> Result<String> {
-  let mut parser = SliceJsonParser::new(json);
-
-  if let JsonEvent::StartObject = parser.parse_next()? { } else {
-    return Err(Error::custom("Reading i3 JSON, expected object start."));
-  }
-
-  if let JsonEvent::ObjectKey(key) = parser.parse_next()? {
-    if key == expected_key {
-      if let JsonEvent::String(result) = parser.parse_next()? {
-        /* That's our answer; exit early. */
-        return Ok(result.into_owned());
-      } else {
-        return Err(Error::custom("Reading i3 JSON, expected string."));
-      }
-    } else {
-      return Err(Error::custom(&format!("Reading i3 JSON, expected {:?} key.",
-                                        expected_key)));
-    }
+  if let Value::Object(object) = parse_json(json)?
+      && let Some(Value::String(result)) = object.get(expected_key)
+  {
+    Ok(String::clone(result))
   } else {
-    return Err(Error::custom("Reading i3 JSON, expected object key."));
+    Err(Error::custom(&format!("Reading i3 JSON, expected {} string.",
+                               expected_key)))
   }
 }
 
diff --git a/src/json.rs b/src/json.rs
new file mode 100644
index 0000000..0ed2efa
--- /dev/null
+++ b/src/json.rs
@@ -0,0 +1,207 @@
+use crate::error::{ Error, Result };
+
+use std::collections::HashMap;
+use std::str::FromStr;
+
+use json_event_parser::{ JsonEvent, SliceJsonParser };
+
+
+#[allow(unused)]
+#[derive(Debug)]
+pub enum Value {
+  Object(Object),
+  Array(Array),
+  Integer(i64),
+  Float(f64),
+  String(String),
+  Boolean(bool),
+  Null,
+}
+pub type Object = HashMap<String, Value>;
+pub type Array = Vec<Value>;
+
+
+pub fn parse_json(json: &[u8]) -> Result<Value> {
+  let mut parser = SliceJsonParser::new(json);
+
+  if let Some(event) = parser.next() {
+    match event? {
+      JsonEvent::StartObject => {
+        Ok(Value::Object(parse_json_object(&mut parser)?))
+      }
+      JsonEvent::StartArray => {
+        Ok(Value::Array(parse_json_array(&mut parser)?))
+      }
+      JsonEvent::String(_) => {
+        Err(Error::custom("JSON: unexpected string at top level"))
+      }
+      JsonEvent::Number(_) => {
+        Err(Error::custom("JSON: unexpected number at top level"))
+      }
+      JsonEvent::Boolean(_) => {
+        Err(Error::custom("JSON: unexpected Boolean at top level"))
+      }
+      JsonEvent::Null => {
+        Err(Error::custom("JSON: unexpected null at top level"))
+      }
+      JsonEvent::ObjectKey(_) => {
+        Err(Error::custom("JSON: unexpected key at top level"))
+      }
+      JsonEvent::EndObject => {
+        Err(Error::custom("JSON: unexpected object end at top level"))
+      }
+      JsonEvent::EndArray => {
+        Err(Error::custom("JSON: unexpected array end at top level"))
+      }
+    }
+  } else {
+    Err(Error::custom("JSON: unexpected end at top level"))
+  }
+}
+
+
+fn parse_json_object(parser: &mut SliceJsonParser) -> Result<Object> {
+  let mut object = HashMap::new();
+
+  loop {
+    if let Some(event) = parser.next() {
+      match event? {
+        JsonEvent::EndObject => {
+          return Ok(object);
+        }
+
+        JsonEvent::ObjectKey(key) => {
+          if object.contains_key(key.as_ref()) {
+            return Err(Error::custom(&format!("JSON: duplicate key {}", key)));
+          }
+
+          let value = parse_json_value(parser)?;
+          object.insert(key.into_owned(), value);
+        }
+
+        JsonEvent::StartObject => {
+          return Err(Error::custom("JSON: unexpected object instead of key"));
+        }
+        JsonEvent::StartArray => {
+          return Err(Error::custom("JSON: unexpected array instead of key"));
+        }
+
+        JsonEvent::String(_) => {
+          return Err(Error::custom("JSON: unexpected string instead of key"));
+        }
+        JsonEvent::Number(_) => {
+          return Err(Error::custom("JSON: unexpected number instead of key"));
+        }
+        JsonEvent::Boolean(_) => {
+          return Err(Error::custom("JSON: unexpected Boolean instead of key"));
+        }
+        JsonEvent::Null => {
+          return Err(Error::custom("JSON: unexpected null instead of key"));
+        }
+
+        JsonEvent::EndArray => {
+          return Err(Error::custom("JSON: unexpected array end instead of key"));
+        }
+      }
+    } else {
+      return Err(Error::custom("JSON: unexpected end instead of key"));
+    }
+  }
+}
+
+
+fn parse_json_array(parser: &mut SliceJsonParser) -> Result<Array> {
+  let mut array = Vec::new();
+
+  loop {
+    if let Some(event) = parser.next() {
+      match event? {
+        JsonEvent::EndArray => {
+          return Ok(array);
+        }
+
+        JsonEvent::StartObject => {
+          array.push(Value::Object(parse_json_object(parser)?));
+        }
+        JsonEvent::StartArray => {
+          array.push(Value::Array(parse_json_array(parser)?));
+        }
+        other => {
+          array.push(parse_json_atomic_value(other)?);
+        }
+      }
+    } else {
+      return Err(Error::custom("JSON: unexpected end instead of value"));
+    }
+  }
+}
+
+
+fn parse_json_value(parser: &mut SliceJsonParser) -> Result<Value> {
+  if let Some(event) = parser.next() {
+    match event? {
+      JsonEvent::StartObject => {
+        Ok(Value::Object(parse_json_object(parser)?))
+      }
+      JsonEvent::StartArray => {
+        Ok(Value::Array(parse_json_array(parser)?))
+      }
+      other => parse_json_atomic_value(other),
+    }
+  } else {
+    Err(Error::custom("JSON: unexpected end instead of value"))
+  }
+}
+
+
+fn parse_json_atomic_value(event: JsonEvent) -> Result<Value> {
+  match event {
+    JsonEvent::String(string) => {
+      Ok(Value::String(string.into_owned()))
+    }
+    JsonEvent::Number(token) => {
+      parse_json_number(&token)
+    }
+    JsonEvent::Boolean(value) => {
+      Ok(Value::Boolean(value))
+    }
+    JsonEvent::Null => {
+      Ok(Value::Null)
+    }
+
+    JsonEvent::ObjectKey(_) => {
+      Err(Error::custom("JSON: unexpected key instead of value"))
+    }
+    JsonEvent::EndObject => {
+      Err(Error::custom("JSON: unexpected object end instead of value"))
+    }
+    JsonEvent::EndArray => {
+      Err(Error::custom("JSON: unexpected array end instead of value"))
+    }
+
+    /*   These ones don't actually come up from how we're called, but it's
+     * better to handle the cases exhaustively.
+     */
+    JsonEvent::StartObject => {
+      Err(Error::custom(
+          "JSON: unexpected object start instead of atomic value"))
+    }
+    JsonEvent::StartArray => {
+      Err(Error::custom(
+          "JSON: unexpected array start instead of atomic value"))
+    }
+  }
+}
+
+
+fn parse_json_number(token: &str) -> Result<Value> {
+  if let Ok(number) = i64::from_str_radix(&token, 10) {
+    Ok(Value::Integer(number))
+  } else if let Ok(number) = f64::from_str(&token) {
+    Ok(Value::Float(number))
+  } else {
+    /* JSON is highly permissive about numbers, but we aren't. */
+    Err(Error::custom("JSON: unsupported number syntax"))
+  }
+}
+
diff --git a/src/main.rs b/src/main.rs
index 225ca2c..786f0e3 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,7 +6,7 @@ use crate::geometry::{ Alignment, Corner, Rectangle, Side };
 use crate::layout::Parcel;
 use crate::module::{
   Module, CreatableModule,
-  BatteryModule, I3ModeModule, TimeModule,
+  BatteryModule, I3ModeModule, I3WorkspaceModule, TimeModule,
 };
 use crate::x::{
   Color,
@@ -44,6 +44,7 @@ use xcb::x::{
 
 mod error;
 mod facility;
+mod json;
 mod geometry;
 mod layout;
 mod module;
@@ -209,6 +210,7 @@ impl Dock {
 
     let mut required_facilities = FacilityType::empty();
     required_facilities |= I3ModeModule::REQUIRED_FACILITIES;
+    required_facilities |= I3WorkspaceModule::REQUIRED_FACILITIES;
     required_facilities |= BatteryModule::REQUIRED_FACILITIES;
     required_facilities |= TimeModule::REQUIRED_FACILITIES;
 
@@ -240,6 +242,15 @@ impl Dock {
         alignment: Alignment::Right,
       }));
 
+      modules.push((Arc::new(Mutex::new(I3WorkspaceModule::new(
+                        facilities.borrow_mut(),
+                        &EXECUTOR,
+                        Sender::clone(&redraw_sender)).await?.as_box())),
+                    ModuleFraming
+      {
+        alignment: Alignment::Left,
+      }));
+
       modules.push((Arc::new(Mutex::new(I3ModeModule::new(
                         facilities.borrow_mut(),
                         &EXECUTOR,
diff --git a/src/module.rs b/src/module.rs
index 8d5264f..8f3ea5a 100644
--- a/src/module.rs
+++ b/src/module.rs
@@ -9,10 +9,12 @@ use async_executor::StaticExecutor;
 
 pub use battery::BatteryModule;
 pub use i3_mode::I3ModeModule;
+pub use i3_workspace::I3WorkspaceModule;
 pub use time::TimeModule;
 
 pub mod battery;
 pub mod i3_mode;
+pub mod i3_workspace;
 pub mod time;
 
 
diff --git a/src/module/i3_workspace.rs b/src/module/i3_workspace.rs
new file mode 100644
index 0000000..d70bd3d
--- /dev/null
+++ b/src/module/i3_workspace.rs
@@ -0,0 +1,112 @@
+use crate::error::{ Error, Result };
+use crate::facility::{ FacilityMap, FacilityType };
+use crate::facility::i3::{ EventType, I3 };
+use crate::module::{ CreatableModule, Module };
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_channel::{ unbounded, Sender, Receiver };
+use async_executor::StaticExecutor;
+use async_lock::Mutex;
+use async_task::Task;
+use futures_lite::future::block_on;
+
+
+pub struct I3WorkspaceModule {
+  _update_task: Task<()>,
+  workspaces: Arc<Mutex<Vec<Workspace>>>,
+}
+
+struct Workspace {
+  name: String,
+  is_focused: bool,
+}
+
+
+impl CreatableModule for I3WorkspaceModule {
+  const REQUIRED_FACILITIES: FacilityType = FacilityType::I3;
+
+  async fn new(facilities: &mut FacilityMap,
+               executor: &'static StaticExecutor,
+               redraw_sender: Sender<()>)
+    -> Result<I3WorkspaceModule>
+  {
+    let i3: &mut I3 = facilities.get().ok_or(Error::custom(
+            "I3 workspace module can't access i3 facility."))?;
+
+    let (sender, receiver) = unbounded();
+
+    if !i3.subscribe(EventType::WORKSPACE, sender).await? {
+      return Err(Error::custom("Unable to subscribe to i3 workspace changes."));
+    }
+
+    let workspaces = Arc::new(Mutex::new(Vec::new()));
+
+    let update_task = executor.spawn(update_loop(receiver,
+                                                 Arc::clone(&workspaces),
+                                                 redraw_sender));
+
+    Ok(I3WorkspaceModule {
+      _update_task: update_task,
+      workspaces,
+    })
+  }
+}
+
+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 mut text = String::new();
+    let mut is_first = true;
+    for name in vec!["playful", "cool", "fic", "tech", "nonfic"] {
+      if is_first {
+	text.push_str(" ");
+      }
+
+      text.push_str(name);
+
+      is_first = false;
+    }
+
+    Ok(text)
+  }
+
+  fn sleep_duration(&self) -> Option<Duration> {
+    None
+  }
+
+  fn is_visible(&self) -> bool {
+    block_on(self.workspaces.lock()).len() > 0
+  }
+}
+
+
+async fn update_loop(receiver: Receiver<(EventType, String)>,
+                     workspaces: Arc<Mutex<Vec<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()
+            }
+          //}
+          //Err(error) => { error.log(); }
+        //}
+      }
+      Err(error) => {
+        Into::<Error>::into(error).log();
+      }
+    }
+  }
+}
+