about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/facility/i3.rs87
-rw-r--r--src/main.rs10
-rw-r--r--src/module.rs2
-rw-r--r--src/module/i3_mode.rs33
4 files changed, 129 insertions, 3 deletions
diff --git a/src/facility/i3.rs b/src/facility/i3.rs
index 2911b4b..268d6bd 100644
--- a/src/facility/i3.rs
+++ b/src/facility/i3.rs
@@ -3,11 +3,17 @@ use crate::facility::{ CreatableFacility, Facility, FacilityType };
 use crate::xdg::xdg_runtime_directory;
 
 use std::any::Any;
+use std::ffi::CStr;
+use std::mem::{ size_of_val, MaybeUninit };
 use std::path::{ Path, PathBuf };
+use std::ptr::null_mut;
 
-use async_fs::{ metadata, read_dir, File };
+use async_fs::{ metadata, read_dir, File, OpenOptions };
 use async_fs::unix::FileTypeExt;
 use futures_lite::StreamExt;
+use libc::{ getpwuid_r, passwd };
+use rustix::io::Errno;
+use rustix::process::{ getuid, Uid };
 
 
 pub struct I3 {
@@ -80,10 +86,84 @@ impl I3 {
     }
     /* As before, an absent environment variable is not an error. */
 
+    let username = Self::get_username().await?;
+    let tmp_path: PathBuf = "/tmp/".into();
+    match Self::try_tmp_directory(&tmp_path, &username).await {
+      Ok(Some(socket)) => { return Ok(socket); }
+      Ok(None) => { }
+      Err(error) => { errors.push(error); }
+    }
+
     for error in errors { error.log() }
     Err(Error::custom("i3 window manager socket not found"))
   }
 
+  async fn get_username() -> Result<String> {
+    let uid: Uid = getuid();
+
+    let mut buffer: [i8; 512] = [0; 512];
+    let mut entry: MaybeUninit<passwd> = MaybeUninit::uninit();
+    let mut result = null_mut();
+
+    let error = unsafe {
+      getpwuid_r(uid.as_raw(),
+                 &raw mut entry as *mut passwd,
+                 &raw mut buffer as *mut i8,
+                 size_of_val(&buffer),
+                 &mut result)
+    };
+    if error != 0 {
+      return Err(Errno::from_raw_os_error(error).into());
+    }
+
+    let name = unsafe { entry.assume_init() }.pw_name;
+    let name = unsafe { CStr::from_ptr(name) };
+
+    Ok(name.to_string_lossy().into_owned())
+  }
+
+  /*   One of the ways to find an i3 socket is to look within the tmp directory
+   * for subdirectories with names having a specific pattern. Do that.
+   */
+  async fn try_tmp_directory(path: &Path, username: &str)
+    -> Result<Option<File>>
+  {
+    let mut directory = read_dir(path).await?;
+
+    while let Some(entry) = directory.try_next().await? {
+      /*   Do not follow symlinks for the name check.
+       *
+       *   Note also that if the name isn't valid Unicode, it doesn't match the
+       * pattern anyway.
+       */
+      if let Some(name) = entry.file_name().to_str() {
+        let prefix = format!("i3-{}.", username);
+
+        if name.starts_with(&prefix) {
+          let tail = &name[prefix.len() ..];
+
+          if tail.len() == 6 {
+            let full_path = path.join(name);
+            if let Some(socket)
+                   = Self::try_socket_directory(&full_path).await?
+            {
+              return Ok(Some(socket));
+            }
+          }
+        }
+      }
+    }
+
+    Ok(None)
+  }
+
+  /*   Several of the ways to find an i3 socket start with a known directory
+   * name, and look immediately within it for a socket with a name having a
+   * specific pattern. Handle that case.
+   *
+   *   The directory iteration logic is a lot like that for try_tmp_directory().
+   * In principle, it could make sense to write a helper.
+   */
   async fn try_socket_directory(path: &Path) -> Result<Option<File>> {
     let mut directory = read_dir(path).await?;
 
@@ -113,13 +193,16 @@ impl I3 {
     Ok(None)
   }
 
+  /* If we have a candidate full path to an i3 socket, see if it works. */
   async fn try_socket_path(path: &Path) -> Result<Option<File>> {
     /* Do follow symlinks, for the socket check. */
     if !metadata(path).await?.file_type().is_socket() {
       return Ok(None);
     }
 
-    let socket = File::open(path).await?;
+    /* Unix-domain sockets don't use open(), despite appearing in the filesystem. TODO */
+    let socket = OpenOptions::new().read(true).write(true).open(path).await?;
+    println!("got i3 socket {:?}", path);
     Ok(Some(socket))
   }
 }
diff --git a/src/main.rs b/src/main.rs
index b1b4b0e..8d3adda 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, TimeModule,
+  BatteryModule, I3ModeModule, TimeModule,
 };
 use crate::x::{
   Color,
@@ -201,6 +201,7 @@ impl Dock {
                             + configuration.baseline_offset as i16;
 
     let mut required_facilities = FacilityType::empty();
+    required_facilities |= I3ModeModule::REQUIRED_FACILITIES;
     required_facilities |= BatteryModule::REQUIRED_FACILITIES;
     required_facilities |= TimeModule::REQUIRED_FACILITIES;
 
@@ -227,6 +228,13 @@ impl Dock {
       {
         alignment: Alignment::Right,
       }));
+
+      modules.push((Arc::new(Mutex::new(I3ModeModule::new(
+                        facilities.borrow_mut())?.as_box())),
+                    ModuleFraming
+      {
+        alignment: Alignment::Left,
+      }));
     }
 
     /*   We start is_visible at false. Since redraw events set it to true, this
diff --git a/src/module.rs b/src/module.rs
index 6d32c40..6d2822c 100644
--- a/src/module.rs
+++ b/src/module.rs
@@ -5,9 +5,11 @@ use std::time::Duration;
 
 
 pub use battery::BatteryModule;
+pub use i3_mode::I3ModeModule;
 pub use time::TimeModule;
 
 pub mod battery;
+pub mod i3_mode;
 pub mod time;
 
 
diff --git a/src/module/i3_mode.rs b/src/module/i3_mode.rs
new file mode 100644
index 0000000..6151d90
--- /dev/null
+++ b/src/module/i3_mode.rs
@@ -0,0 +1,33 @@
+use crate::error::Result;
+use crate::facility::{ FacilityMap, FacilityType };
+use crate::module::{ CreatableModule, Module };
+
+use std::time::Duration;
+
+
+pub struct I3ModeModule {
+}
+
+
+impl CreatableModule for I3ModeModule {
+  const REQUIRED_FACILITIES: FacilityType = FacilityType::I3;
+
+  fn new(_facilities: &mut FacilityMap) -> Result<I3ModeModule> {
+    Ok(I3ModeModule { })
+  }
+}
+
+impl Module for I3ModeModule {
+  fn format(&mut self, _facilities: &mut FacilityMap) -> Result<String> {
+    Ok("mode goes here".to_string())
+  }
+
+  fn sleep_duration(&self) -> Option<Duration> {
+    None
+  }
+
+  fn is_visible(&self) -> bool {
+    true
+  }
+}
+