about summary refs log tree commit diff
path: root/src/facility/i3.rs
blob: 4b91b02b19f12e2acb8556709dbe3c2c17f3104e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use crate::error::{ Error, Result };
use crate::facility::{ CreatableFacility, Facility, FacilityType };
use crate::unix::get_username;
use crate::xdg::xdg_runtime_directory;

use std::any::Any;
use std::path::{ Path, PathBuf };

use async_fs::{ metadata, read_dir, File, OpenOptions };
use async_fs::unix::FileTypeExt;
use futures_lite::StreamExt;


pub struct I3 {
  socket: File,
}


impl Facility for I3 {
  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }

  fn update(&mut self) -> Result<()> {
    Ok(())
  }
}

impl CreatableFacility for I3 {
  const FACILITY_TYPE: FacilityType = FacilityType::I3;

  async fn new() -> Result<Self> {
    let socket = Self::find_socket().await?;

    Ok(I3 { socket })
  }
}

impl I3 {
  async fn find_socket() -> Result<File> {
    /*   We save most errors for the end, because they aren't really errors if
     * a subsequent attempt succeeds.
     */
    let mut errors: Vec<Error> = Vec::new();

    /*   According to the i3 documentation, the first-choice path is the one
     * set in the config file. However, we opt not to parse the config - this
     * would be the sole benefit we'd get from doing so. So, we skip it. If
     * this affects you, sorry about that.
     */

    match std::env::var("I3SOCK") {
      Ok(path) => {
        /*   If it's set but invalid, we regard that as a reason to immediately
         * declare failure.
         */
        let path = PathBuf::from(path);

        match Self::try_socket_path(&path).await {
          Ok(Some(socket)) => { return Ok(socket); }
          Ok(None) => { }
          Err(error) => { errors.push(error); }
        }
      }

      /*   We don't consider the mere absence of an environment variable to be
       * an error; the user is perfectly capable of noticing that on their own.
       */
      Err(std::env::VarError::NotPresent) => { }
      Err(error) => { errors.push(error.into()); }
    }

    if let Some(mut path) = xdg_runtime_directory()? {
      path.push("i3/");

      match Self::try_socket_directory(&path).await {
        Ok(Some(socket)) => { return Ok(socket); }
        Ok(None) => { }
        Err(error) => { errors.push(error); }
      }
    }
    /* As before, an absent environment variable is not an error. */

    let username = 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"))
  }

  /*   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?;

    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 = "ipc-socket.";
        if name.starts_with(prefix) {
          let tail = &name[prefix.len() ..];

          if tail.len() > 0
             && tail.chars().all(|c| { c.is_ascii_digit() })
          {
            let full_path = path.join(name);
            if let Some(socket) = Self::try_socket_path(&full_path).await? {
              return Ok(Some(socket));
            }
          }
        }
      }
    }

    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);
    }

    /* 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))
  }
}