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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright (C) 2021-2022  Tassilo Horn <tsdh@gnu.org>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program.  If not, see <https://www.gnu.org/licenses/>.

//! Functions and data structures of the swayrd daemon.

use crate::cmds;
use crate::config::{self, Config};
use crate::focus::FocusData;
use crate::focus::FocusEvent;
use crate::focus::FocusMessage;
use crate::layout;
use crate::util;
use std::collections::HashMap;
use std::io::Read;
use std::os::unix::net::{UnixListener, UnixStream};
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::RwLock;
use std::thread;
use std::time::Duration;
use swayipc as s;

pub fn run_daemon() {
    let (focus_tx, focus_rx) = mpsc::channel();
    let fdata = FocusData {
        focus_tick_by_id: Arc::new(RwLock::new(HashMap::new())),
        focus_chan: focus_tx,
    };

    let config = config::load_config();
    let lockin_delay = config.get_focus_lockin_delay();

    {
        let fdata = fdata.clone();
        thread::spawn(move || {
            monitor_sway_events(fdata, &config);
        });
    }

    {
        let fdata = fdata.clone();
        thread::spawn(move || {
            focus_lock_in_handler(focus_rx, fdata, lockin_delay);
        });
    }

    serve_client_requests(fdata);
}

fn connect_and_subscribe() -> s::Fallible<s::EventStream> {
    s::Connection::new()?.subscribe(&[
        s::EventType::Window,
        s::EventType::Workspace,
        s::EventType::Shutdown,
    ])
}

pub fn monitor_sway_events(fdata: FocusData, config: &Config) {
    let mut focus_counter = 0;
    let mut resets = 0;
    let max_resets = 10;

    'reset: loop {
        if resets >= max_resets {
            break;
        }
        resets += 1;

        log::debug!("Connecting to sway for subscribing to events...");
        match connect_and_subscribe() {
            Err(err) => {
                log::warn!("Could not connect and subscribe: {}", err);
                std::thread::sleep(std::time::Duration::from_secs(3));
            }
            Ok(iter) => {
                for ev_result in iter {
                    let show_extra_props_state;
                    resets = 0;
                    match ev_result {
                        Ok(ev) => match ev {
                            s::Event::Window(win_ev) => {
                                focus_counter += 1;
                                show_extra_props_state = handle_window_event(
                                    win_ev,
                                    &fdata,
                                    config,
                                    focus_counter,
                                );
                            }
                            s::Event::Workspace(ws_ev) => {
                                focus_counter += 1;
                                show_extra_props_state = handle_workspace_event(
                                    ws_ev,
                                    &fdata,
                                    focus_counter,
                                );
                            }
                            s::Event::Shutdown(sd_ev) => {
                                log::debug!(
                                    "Sway shuts down with reason '{:?}'.",
                                    sd_ev.change
                                );
                                break 'reset;
                            }
                            _ => show_extra_props_state = false,
                        },
                        Err(e) => {
                            log::warn!("Error while receiving events: {}", e);
                            std::thread::sleep(std::time::Duration::from_secs(
                                3,
                            ));
                            show_extra_props_state = false;
                            log::warn!("Resetting!");
                        }
                    }
                    if show_extra_props_state {
                        log::debug!(
                            "New extra_props state:\n{:#?}",
                            *fdata.focus_tick_by_id.read().unwrap()
                        );
                    }
                }
            }
        }
    }
    log::debug!("Swayr daemon shutting down.")
}

fn handle_window_event(
    ev: Box<s::WindowEvent>,
    fdata: &FocusData,
    config: &config::Config,
    focus_val: u64,
) -> bool {
    let s::WindowEvent {
        change, container, ..
    } = *ev;
    match change {
        s::WindowChange::Focus => {
            layout::maybe_auto_tile(config);
            fdata.send(FocusMessage::FocusEvent(FocusEvent {
                node_id: container.id,
                ev_focus_ctr: focus_val,
            }));
            log::debug!("Handled window event type {:?}", change);
            true
        }
        s::WindowChange::New => {
            layout::maybe_auto_tile(config);
            fdata.ensure_id(container.id);
            log::debug!("Handled window event type {:?}", change);
            true
        }
        s::WindowChange::Close => {
            fdata.remove_focus_data(container.id);
            layout::maybe_auto_tile(config);
            log::debug!("Handled window event type {:?}", change);
            true
        }
        s::WindowChange::Move | s::WindowChange::Floating => {
            layout::maybe_auto_tile(config);
            log::debug!("Handled window event type {:?}", change);
            false // We don't affect the extra_props state here.
        }
        _ => {
            log::debug!("Unhandled window event type {:?}", change);
            false
        }
    }
}

fn handle_workspace_event(
    ev: Box<s::WorkspaceEvent>,
    fdata: &FocusData,
    focus_val: u64,
) -> bool {
    let s::WorkspaceEvent {
        change,
        current,
        old: _,
        ..
    } = *ev;
    match change {
        s::WorkspaceChange::Init | s::WorkspaceChange::Focus => {
            let id = current
                .expect("No current in Init or Focus workspace event")
                .id;
            fdata.send(FocusMessage::FocusEvent(FocusEvent {
                node_id: id,
                ev_focus_ctr: focus_val,
            }));
            log::debug!("Handled workspace event type {:?}", change);
            true
        }
        s::WorkspaceChange::Empty => {
            fdata.remove_focus_data(
                current.expect("No current in Empty workspace event").id,
            );
            log::debug!("Handled workspace event type {:?}", change);
            true
        }
        _ => false,
    }
}

pub fn serve_client_requests(fdata: FocusData) {
    match std::fs::remove_file(util::get_swayr_socket_path()) {
        Ok(()) => log::debug!("Deleted stale socket from previous run."),
        Err(e) => log::error!("Could not delete socket:\n{:?}", e),
    }

    match UnixListener::bind(util::get_swayr_socket_path()) {
        Ok(listener) => {
            for stream in listener.incoming() {
                match stream {
                    Ok(stream) => {
                        handle_client_request(stream, &fdata);
                    }
                    Err(err) => {
                        log::error!("Error handling client request: {}", err);
                        break;
                    }
                }
            }
        }
        Err(err) => {
            log::error!("Could not bind socket: {}", err)
        }
    }
}

fn handle_client_request(mut stream: UnixStream, fdata: &FocusData) {
    let mut cmd_str = String::new();
    if stream.read_to_string(&mut cmd_str).is_ok() {
        if let Ok(cmd) = serde_json::from_str::<cmds::SwayrCommand>(&cmd_str) {
            cmds::exec_swayr_cmd(cmds::ExecSwayrCmdArgs {
                cmd: &cmd,
                focus_data: fdata,
            });
        } else {
            log::error!(
                "Could not serialize following string to SwayrCommand.\n{}",
                cmd_str
            );
        }
    } else {
        log::error!("Could not read command from client.");
    }
}

#[derive(Debug)]
enum InhibitState {
    FocusInhibit,
    FocusActive,
}

impl InhibitState {
    pub fn set(&mut self) {
        if let InhibitState::FocusActive = self {
            log::debug!("Inhibiting tick focus updates");
            *self = InhibitState::FocusInhibit;
        }
    }

    pub fn clear(&mut self) {
        if let InhibitState::FocusInhibit = self {
            log::debug!("Activating tick focus updates");
            *self = InhibitState::FocusActive;
        }
    }
}

fn focus_lock_in_handler(
    focus_chan: mpsc::Receiver<FocusMessage>,
    fdata: FocusData,
    lockin_delay: Duration,
) {
    // Focus event that has not yet been locked-in to the LRU order
    let mut pending_fev: Option<FocusEvent> = None;

    // Toggle to inhibit LRU focus updates
    let mut inhibit = InhibitState::FocusActive;

    let update_focus = |fev: Option<FocusEvent>| {
        if let Some(fev) = fev {
            log::debug!("Locking-in focus on {}", fev.node_id);
            fdata.update_last_focus_tick(fev.node_id, fev.ev_focus_ctr)
        }
    };

    // outer loop, waiting for focus events
    loop {
        let fmsg = match focus_chan.recv() {
            Ok(fmsg) => fmsg,
            Err(mpsc::RecvError) => return,
        };

        let mut fev = match fmsg {
            FocusMessage::TickUpdateInhibit => {
                inhibit.set();
                continue;
            }
            FocusMessage::TickUpdateActivate => {
                inhibit.clear();
                update_focus(pending_fev.take());
                continue;
            }
            FocusMessage::FocusEvent(fev) => {
                if let InhibitState::FocusInhibit = inhibit {
                    // update the pending event but take no further action
                    pending_fev = Some(fev);
                    continue;
                }
                fev
            }
        };

        // Inner loop, waiting for the lock-in delay to expire
        loop {
            let fmsg = match focus_chan.recv_timeout(lockin_delay) {
                Ok(fmsg) => fmsg,
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    update_focus(Some(fev));
                    break; // return to outer loop
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => return,
            };

            match fmsg {
                FocusMessage::TickUpdateInhibit => {
                    // inhibit requested before currently focused container
                    // was locked-in, set it as pending in case no other
                    // focus changes are made while updates remain inhibited
                    inhibit.set();
                    pending_fev = Some(fev);
                    break; // return to outer loop with a preset pending_fev
                }
                FocusMessage::TickUpdateActivate => {
                    // updates reactivated while we were waiting to lockin
                    // Immediately lockin fev
                    inhibit.clear();
                    update_focus(Some(fev));
                    break;
                }
                FocusMessage::FocusEvent(new_fev) => {
                    // start a new wait (inner) loop with the most recent
                    // focus event
                    fev = new_fev;
                }
            }
        }
    }
}