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
//! Functions and data structures of the swayrd demon.

use crate::cmds;
use crate::ipc;
use crate::util;

use std::collections::HashMap;
use std::io::Read;
use std::os::unix::net::{UnixListener, UnixStream};
use std::sync::Arc;
use std::sync::RwLock;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};

use swayipc as s;
use swayipc::reply as r;

pub fn run_demon() {
    let extra_props: Arc<RwLock<HashMap<i64, ipc::ExtraProps>>> =
        Arc::new(RwLock::new(HashMap::new()));
    let extra_props_for_ev_handler = extra_props.clone();

    thread::spawn(move || {
        monitor_sway_events(extra_props_for_ev_handler);
    });

    serve_client_requests(extra_props);
}

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

pub fn monitor_sway_events(
    extra_props: Arc<RwLock<HashMap<i64, ipc::ExtraProps>>>,
) {
    'reset: loop {
        println!("Connecting to sway for subscribing to events...");
        match connect_and_subscribe() {
            Err(err) => {
                eprintln!("Could not connect and subscribe: {}", err);
                std::thread::sleep(std::time::Duration::from_secs(3));
                break 'reset;
            }
            Ok(iter) => {
                for ev_result in iter {
                    let handled;
                    match ev_result {
                        Ok(ev) => match ev {
                            r::Event::Window(win_ev) => {
                                let extra_props_clone = extra_props.clone();
                                handled = handle_window_event(
                                    win_ev,
                                    extra_props_clone,
                                );
                            }
                            r::Event::Workspace(ws_ev) => {
                                let extra_props_clone = extra_props.clone();
                                handled = handle_workspace_event(
                                    ws_ev,
                                    extra_props_clone,
                                );
                            }
                            _ => handled = false,
                        },
                        Err(e) => {
                            eprintln!("Error while receiving events: {}", e);
                            std::thread::sleep(std::time::Duration::from_secs(
                                3,
                            ));
                            eprintln!("Resetting!");
                            break 'reset;
                        }
                    }
                    if handled {
                        println!(
                            "New extra_props state:\n{:#?}",
                            *extra_props.read().unwrap()
                        );
                    }
                }
            }
        }
    }
}

fn handle_window_event(
    ev: Box<r::WindowEvent>,
    extra_props: Arc<RwLock<HashMap<i64, ipc::ExtraProps>>>,
) -> bool {
    let r::WindowEvent { change, container } = *ev;
    match change {
        r::WindowChange::New | r::WindowChange::Focus => {
            update_last_focus_time(container.id, extra_props);
            println!("Handled window event type {:?}", change);
            true
        }
        r::WindowChange::Close => {
            remove_extra_props(container.id, extra_props);
            println!("Handled window event type {:?}", change);
            true
        }
        _ => false,
    }
}

fn handle_workspace_event(
    ev: Box<r::WorkspaceEvent>,
    extra_props: Arc<RwLock<HashMap<i64, ipc::ExtraProps>>>,
) -> bool {
    let r::WorkspaceEvent {
        change,
        current,
        old: _,
    } = *ev;
    match change {
        r::WorkspaceChange::Init | r::WorkspaceChange::Focus => {
            update_last_focus_time(
                current
                    .expect("No current in Init or Focus workspace event")
                    .id,
                extra_props,
            );
            println!("Handled workspace event type {:?}", change);
            true
        }
        r::WorkspaceChange::Empty => {
            remove_extra_props(
                current.expect("No current in Empty workspace event").id,
                extra_props,
            );
            println!("Handled workspace event type {:?}", change);
            true
        }
        _ => false,
    }
}

fn update_last_focus_time(
    id: i64,
    extra_props: Arc<RwLock<HashMap<i64, ipc::ExtraProps>>>,
) {
    let mut write_lock = extra_props.write().unwrap();
    if let Some(wp) = write_lock.get_mut(&id) {
        wp.last_focus_time = get_epoch_time_as_millis();
    } else {
        write_lock.insert(
            id,
            ipc::ExtraProps {
                last_focus_time: get_epoch_time_as_millis(),
            },
        );
    }
}

fn remove_extra_props(
    id: i64,
    extra_props: Arc<RwLock<HashMap<i64, ipc::ExtraProps>>>,
) {
    extra_props.write().unwrap().remove(&id);
}

fn get_epoch_time_as_millis() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("Couldn't get epoch time!")
        .as_millis()
}

pub fn serve_client_requests(
    extra_props: Arc<RwLock<HashMap<i64, ipc::ExtraProps>>>,
) {
    match std::fs::remove_file(util::get_swayr_socket_path()) {
        Ok(()) => println!("Deleted stale socket from previous run."),
        Err(e) => eprintln!("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, extra_props.clone());
                    }
                    Err(err) => {
                        eprintln!("Error handling client request: {}", err);
                        break;
                    }
                }
            }
        }
        Err(err) => {
            eprintln!("Could not bind socket: {}", err)
        }
    }
}

fn handle_client_request(
    mut stream: UnixStream,
    extra_props: Arc<RwLock<HashMap<i64, ipc::ExtraProps>>>,
) {
    let mut cmd_str = String::new();
    if stream.read_to_string(&mut cmd_str).is_ok() {
        if let Ok(cmd) = serde_json::from_str::<ipc::SwayrCommand>(&cmd_str) {
            cmds::exec_swayr_cmd(cmds::ExecSwayrCmdArgs {
                cmd: &cmd,
                extra_props,
            });
        } else {
            eprintln!(
                "Could not serialize following string to SwayrCommand.\n{}",
                cmd_str
            );
        }
    } else {
        eprintln!("Could not read command from client.");
    }
}