~tsdh/swayr

ref: 0d5288f8459e297e85382f002165d173698416b0 swayr/src/con.rs -rw-r--r-- 13.7 KiB
0d5288f8Tassilo Horn Docs 3 months ago
                                                                                
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Copyright (C) 2021  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/>.

//! Convenience data structures built from the IPC structs.

use crate::config as cfg;
use crate::util;
use crate::util::DisplayFormat;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use std::cmp;
use std::collections::HashMap;
use swayipc as s;

/// Immutable Node Iterator
///
/// Iterates nodes in depth-first order, tiled nodes before floating nodes.
pub struct NodeIter<'a> {
    stack: Vec<&'a s::Node>,
}

impl<'a> NodeIter<'a> {
    pub fn new(node: &'a s::Node) -> NodeIter {
        NodeIter { stack: vec![node] }
    }
}

impl<'a> Iterator for NodeIter<'a> {
    type Item = &'a s::Node;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(node) = self.stack.pop() {
            for n in &node.floating_nodes {
                self.stack.push(n);
            }
            for n in &node.nodes {
                self.stack.push(n);
            }
            Some(node)
        } else {
            None
        }
    }
}

/// Extension methods for [`swayipc::Node`].
pub trait NodeMethods {
    /// Returns an iterator for this [`swayipc::Node`] and its childres.
    fn iter(&self) -> NodeIter;

    fn is_window(&self) -> bool;

    /// Either a workspace or a con holding windows, e.g. a vertical split side
    /// in a horizontally split workspace.
    fn is_container(&self) -> bool;

    /// Returns all nodes being application windows.
    fn windows(&self) -> Vec<&s::Node>;

    /// Returns all nodes being workspaces.
    fn workspaces(&self) -> Vec<&s::Node>;

    fn is_scratchpad(&self) -> bool;
}

impl NodeMethods for s::Node {
    fn iter(&self) -> NodeIter {
        NodeIter::new(self)
    }

    fn is_window(&self) -> bool {
        (self.node_type == s::NodeType::Con
            || self.node_type == s::NodeType::FloatingCon)
            && self.name.is_some()
    }

    fn is_container(&self) -> bool {
        self.node_type == s::NodeType::Workspace
            || self.node_type == s::NodeType::Con
                && self.name.is_none()
                && self.layout != s::NodeLayout::None
    }

    fn windows(&self) -> Vec<&s::Node> {
        self.iter().filter(|n| n.is_window()).collect()
    }

    fn workspaces(&self) -> Vec<&s::Node> {
        self.iter()
            .filter(|n| n.node_type == s::NodeType::Workspace)
            .collect()
    }

    fn is_scratchpad(&self) -> bool {
        self.name.is_some() && self.name.as_ref().unwrap().eq("__i3_scratch")
    }
}

/// Extra properties gathered by swayrd for windows and workspaces.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ExtraProps {
    /// Milliseconds since UNIX epoch.
    pub last_focus_time: u128,
}

#[derive(Debug)]
pub struct Window<'a> {
    node: &'a s::Node,
    workspace: &'a s::Node,
    extra_props: Option<ExtraProps>,
}

impl Window<'_> {
    pub fn get_id(&self) -> i64 {
        self.node.id
    }

    pub fn get_app_name(&self) -> &str {
        if let Some(app_id) = &self.node.app_id {
            app_id
        } else if let Some(wp_class) = self
            .node
            .window_properties
            .as_ref()
            .and_then(|wp| wp.class.as_ref())
        {
            wp_class
        } else {
            "<Unknown>"
        }
    }

    pub fn get_title(&self) -> &str {
        self.node.name.as_ref().unwrap()
    }

    pub fn is_urgent(&self) -> bool {
        self.node.urgent
    }

    pub fn is_focused(&self) -> bool {
        self.node.focused
    }

    pub fn is_floating(&self) -> bool {
        self.node.node_type == s::NodeType::FloatingCon
    }

    pub fn get_parent(&self) -> &s::Node {
        NodeIter::new(self.workspace)
            .find(|n| n.nodes.contains(self.node))
            .expect("No parent node of a window!")
    }

    pub fn is_child_of_tiled_container(&self) -> bool {
        let layout = &self.get_parent().layout;
        layout == &s::NodeLayout::SplitH || layout == &s::NodeLayout::SplitV
    }

    pub fn is_child_of_tabbed_or_stacked_container(&self) -> bool {
        let layout = &self.get_parent().layout;
        layout == &s::NodeLayout::Tabbed || layout == &s::NodeLayout::Stacked
    }
}

impl PartialEq for Window<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.get_id() == other.get_id()
    }
}

impl Eq for Window<'_> {}

impl Ord for Window<'_> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        if self == other {
            cmp::Ordering::Equal
        } else if self.is_urgent() && !other.is_urgent()
            || !self.is_focused() && other.is_focused()
        {
            cmp::Ordering::Less
        } else if !self.is_urgent() && other.is_urgent()
            || self.is_focused() && !other.is_focused()
        {
            std::cmp::Ordering::Greater
        } else {
            let lru_a =
                self.extra_props.as_ref().map_or(0, |wp| wp.last_focus_time);
            let lru_b = other
                .extra_props
                .as_ref()
                .map_or(0, |wp| wp.last_focus_time);
            lru_a.cmp(&lru_b).reverse()
        }
    }
}

impl PartialOrd for Window<'_> {
    fn partial_cmp(&self, other: &Window) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

lazy_static! {
    static ref APP_NAME_AND_VERSION_RX: regex::Regex =
        regex::Regex::new("(.+)(-[0-9.]+)").unwrap();
}

fn maybe_html_escape(do_it: bool, text: &str) -> String {
    if do_it {
        text.replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("&", "&amp;")
    } else {
        text.to_string()
    }
}

impl<'a> DisplayFormat for Window<'a> {
    fn format_for_display(&self, cfg: &cfg::Config) -> String {
        let window_format = cfg.get_format_window_format();
        let urgency_start = cfg.get_format_urgency_start();
        let urgency_end = cfg.get_format_urgency_end();
        let html_escape = cfg.get_format_html_escape();
        let icon_dirs = cfg.get_format_icon_dirs();
        // fallback_icon has no default value.
        let fallback_icon: Option<Box<std::path::Path>> = cfg
            .get_format_fallback_icon()
            .as_ref()
            .map(|i| std::path::Path::new(i).to_owned().into_boxed_path());

        // Some apps report, e.g., Gimp-2.10 but the icon is still named
        // gimp.png.
        let app_name_no_version =
            APP_NAME_AND_VERSION_RX.replace(self.get_app_name(), "$1");

        window_format
            .replace("{id}", format!("{}", self.get_id()).as_str())
            .replace(
                "{urgency_start}",
                if self.is_urgent() {
                    urgency_start.as_str()
                } else {
                    ""
                },
            )
            .replace(
                "{urgency_end}",
                if self.is_urgent() {
                    urgency_end.as_str()
                } else {
                    ""
                },
            )
            .replace(
                "{app_name}",
                &maybe_html_escape(html_escape, self.get_app_name()),
            )
            .replace(
                "{workspace_name}",
                &maybe_html_escape(
                    html_escape,
                    self.workspace.name.as_ref().unwrap().as_str(),
                ),
            )
            .replace(
                "{marks}",
                &maybe_html_escape(html_escape, &self.node.marks.join(", ")),
            )
            .replace(
                "{app_icon}",
                util::get_icon(self.get_app_name(), &icon_dirs)
                    .or_else(|| {
                        util::get_icon(&app_name_no_version, &icon_dirs)
                    })
                    .or_else(|| {
                        util::get_icon(
                            &app_name_no_version.to_lowercase(),
                            &icon_dirs,
                        )
                    })
                    .or(fallback_icon)
                    .map(|i| i.to_string_lossy().into_owned())
                    .unwrap_or_else(String::new)
                    .as_str(),
            )
            .replace(
                "{title}",
                &maybe_html_escape(html_escape, self.get_title()),
            )
    }
}

fn build_windows<'a>(
    root: &'a s::Node,
    include_scratchpad_windows: bool,
    extra_props: Option<&HashMap<i64, ExtraProps>>,
) -> Vec<Window<'a>> {
    let mut v = vec![];
    for workspace in root.workspaces() {
        if !include_scratchpad_windows && workspace.is_scratchpad() {
            continue;
        }

        for n in workspace.windows() {
            v.push(Window {
                node: n,
                extra_props: extra_props.and_then(|m| m.get(&n.id).cloned()),
                workspace,
            })
        }
    }
    v
}

fn build_workspaces<'a>(
    root: &'a s::Node,
    include_scratchpad: bool,
    extra_props: Option<&HashMap<i64, ExtraProps>>,
) -> Vec<Workspace<'a>> {
    let mut v = vec![];
    for workspace in root.workspaces() {
        if workspace.windows().is_empty()
            || workspace.is_scratchpad() && !include_scratchpad
        {
            continue;
        }

        let mut wins: Vec<Window> = workspace
            .windows()
            .iter()
            .map(|w| Window {
                node: w,
                extra_props: extra_props.and_then(|m| m.get(&w.id).cloned()),
                workspace,
            })
            .collect();
        wins.sort();
        v.push(Workspace {
            node: workspace,
            extra_props: extra_props
                .and_then(|m| m.get(&workspace.id).cloned()),
            windows: wins,
        })
    }
    v.sort();
    v
}

/// Gets all application windows of the tree.
pub fn get_windows<'a>(
    root: &'a s::Node,
    include_scratchpad_windows: bool,
    extra_props: Option<&HashMap<i64, ExtraProps>>,
) -> Vec<Window<'a>> {
    let extra_props_given = extra_props.is_some();
    let mut wins = build_windows(root, include_scratchpad_windows, extra_props);
    if extra_props_given {
        wins.sort();
    }
    wins
}

/// Gets all workspaces of the tree.
pub fn get_workspaces<'a>(
    root: &'a s::Node,
    include_scratchpad: bool,
    extra_props: Option<&HashMap<i64, ExtraProps>>,
) -> Vec<Workspace<'a>> {
    let mut workspaces =
        build_workspaces(root, include_scratchpad, extra_props);
    workspaces.rotate_left(1);
    workspaces
}

pub fn select_window<'a>(
    prompt: &str,
    windows: &'a [Window],
) -> Option<&'a Window<'a>> {
    util::select_from_menu(prompt, windows)
}

pub fn select_workspace<'a>(
    prompt: &str,
    workspaces: &'a [Workspace],
) -> Option<&'a Workspace<'a>> {
    util::select_from_menu(prompt, workspaces)
}

pub enum WsOrWin<'a> {
    Ws { ws: &'a Workspace<'a> },
    Win { win: &'a Window<'a> },
}

impl DisplayFormat for WsOrWin<'_> {
    fn format_for_display(&self, cfg: &cfg::Config) -> String {
        match self {
            WsOrWin::Ws { ws } => ws.format_for_display(cfg),
            WsOrWin::Win { win } => win.format_for_display(cfg),
        }
    }
}

impl WsOrWin<'_> {
    pub fn from_workspaces<'a>(
        workspaces: &'a [Workspace],
    ) -> Vec<WsOrWin<'a>> {
        let mut v = vec![];
        for ws in workspaces {
            v.push(WsOrWin::Ws { ws });
            for win in &ws.windows {
                v.push(WsOrWin::Win { win });
            }
        }
        v
    }
}

pub fn select_workspace_or_window<'a>(
    prompt: &'a str,
    ws_or_wins: &'a [WsOrWin<'a>],
) -> Option<&'a WsOrWin<'a>> {
    util::select_from_menu(prompt, ws_or_wins)
}

pub struct Workspace<'a> {
    pub node: &'a s::Node,
    extra_props: Option<ExtraProps>,
    pub windows: Vec<Window<'a>>,
}

impl Workspace<'_> {
    pub fn get_name(&self) -> &str {
        self.node.name.as_ref().unwrap()
    }

    pub fn get_id(&self) -> i64 {
        self.node.id
    }

    pub fn is_scratchpad(&self) -> bool {
        self.node.is_scratchpad()
    }

    pub fn is_current(&self) -> bool {
        is_current_container(self.node)
    }
}

pub fn is_current_container(node: &s::Node) -> bool {
    node.focused || NodeIter::new(node).any(|c| c.focused)
}

impl PartialEq for Workspace<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.get_id() == other.get_id()
    }
}

impl Eq for Workspace<'_> {}

impl Ord for Workspace<'_> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        if self == other {
            cmp::Ordering::Equal
        } else {
            let lru_a =
                self.extra_props.as_ref().map_or(0, |wp| wp.last_focus_time);
            let lru_b = other
                .extra_props
                .as_ref()
                .map_or(0, |wp| wp.last_focus_time);
            lru_a.cmp(&lru_b).reverse()
        }
    }
}

impl PartialOrd for Workspace<'_> {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a> DisplayFormat for Workspace<'a> {
    fn format_for_display(&self, cfg: &cfg::Config) -> String {
        let fmt = cfg.get_format_workspace_format();
        let html_escape = cfg.get_format_html_escape();

        fmt.replace("{id}", format!("{}", self.get_id()).as_str())
            .replace("{name}", &maybe_html_escape(html_escape, self.get_name()))
    }
}