about summary refs log tree commit diff
path: root/src/module/i3_workspace.rs
blob: d6a35706d32ae8e112fa1128305d1c4402258aa6 (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
181
182
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;

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<BTreeMap<u64, 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 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),
                                                 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 = block_on(self.workspaces.lock());

    let mut text = String::new();
    let mut is_first = true;
    for (_, workspace) in workspaces.iter() {
      if !is_first {
        text.push_str(" ");
      }

      if workspace.is_focused {
        text.push_str("*");
      }
      text.push_str(&workspace.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<BTreeMap<u64, Workspace>>>,
                     redraw_sender: Sender<()>)
{
  loop {
    match receiver.recv().await {
      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;
              }
            }
          }

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