aboutsummaryrefslogtreecommitdiff
path: root/.config/awesome/quarrel/native/src/lenses/mod.rs
blob: bb7f727a53c318087f07ed5b30bbd21b9fc0b1f4 (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
pub mod application;
pub mod calculator;

use std::sync::Arc;

use itertools::Itertools;
use mlua::{
    prelude::*,
    LuaSerdeExt,
};
use rayon::iter::FromParallelIterator;
use serde::{
    Deserialize,
    Serialize,
};

#[derive(Clone, Debug)]
pub enum Entries {
    Multiple(Vec<Entry>),
    Single(Entry),
    None
}

impl FromIterator<Entry> for Entries {
    fn from_iter<T: IntoIterator<Item = Entry>>(iter: T) -> Self {
        let mut iter = iter.into_iter();
        match (iter.next(), iter.next()) {
            (None, None) => Self::None,
            (Some(first), None) => Self::Single(first),
            (None, Some(_)) => unreachable!(),
            (Some(first), Some(second)) => {
                let mut vec = Vec::from([first, second]);
                vec.extend(iter);
                Self::Multiple(vec)
            },
        }
    }
}

impl From<Vec<Entry>> for Entries {
    fn from(entries: Vec<Entry>) -> Self {
        match entries.len() {
            0 => Self::None,
            1 => {
                let entry = entries.into_iter().exactly_one().unwrap();
                Self::Single(entry)
            },
            _ => Self::Multiple(entries)
        }
    }
}

impl IntoLua for Entries {
    fn into_lua(self, lua: &Lua) -> LuaResult<LuaValue> {
        match self {
            Entries::Multiple(entries) => entries.into_lua(lua),
            Entries::Single(entry) => entry.into_lua(lua),
            Entries::None => Ok(LuaValue::Nil)
        }
    }
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Entry {
    pub message: String,
    pub exec: Option<(String, bool)>,
}

impl IntoLua for Entry {
    fn into_lua(self, lua: &Lua) -> LuaResult<LuaValue> {
        return lua.to_value(&self);
    }
}

impl FromLua for Entry {
    fn from_lua(value: LuaValue, lua: &Lua) -> LuaResult<Self> {
        return lua.from_value(value);
    }
}

#[derive(Default, Clone, Debug)]
pub enum Cache {
    Valid(Entries),
    #[default]
    Stale,
}

pub struct _Lense<T: Lense>(pub Arc<T>);

pub trait Lense {
    const NAME: &'static str;

    fn init() -> Arc<Self>;

    fn set_cache(&self, cache: Cache);
    fn get_cache(&self) -> Cache;

    fn set_interrupt(&self, interrupt: bool);
    fn get_interrupt(&self) -> bool;

    fn entries(&self, lua: &Lua, input: String) -> Result<Entries, anyhow::Error>;
    fn filter(&self, entries: Entries, input: String) -> Entries {
        let entry_contains = |entry: &Entry| {
            entry.message.to_lowercase().contains(&input.to_lowercase())
        };
        match entries {
            Entries::Multiple(entries) => entries.into_iter()
                .filter(entry_contains)
                .collect(),
            Entries::Single(entry) => if entry_contains(&entry) { Entries::Single(entry) } else { Entries::None }
            Entries::None => Entries::None
        }
    }
}

impl<T: Lense + 'static> LuaUserData for _Lense<T> {
    fn add_fields<F: LuaUserDataFields<Self>>(fields: &mut F) {
        fields.add_field_method_get("stale", |_, this| {
            Ok(matches!(this.0.get_cache(), Cache::Stale))
        });

        fields.add_field("name", T::NAME);
    }

    fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) {
        methods.add_method_mut("query", |lua, this, input: String| {
            this.0.set_interrupt(false); // reset interrupt so that we can use the lense again
            return Ok(match this.0.get_cache() {
                Cache::Valid(entries) => this.0.filter(entries.clone(), input),
                Cache::Stale => {
                    let entries = this.0.entries(lua, input.clone()).map_err(LuaError::external)?;
                    let mut entries = this.0.filter(entries, input);
                    match entries {
                        Entries::Multiple(ref mut entries) => entries.sort_by(|a, b| a.message.cmp(&b.message)),
                        _ => {}
                    }
                    this.0.set_cache(Cache::Valid(entries.clone()));
                    entries
                }
            });
        });

        methods.add_method_mut("mark_stale", |_, this, _: ()| {
            Ok(this.0.set_cache(Cache::Stale))
        });
        methods.add_method_mut("interrupt", |_, this, _: ()| Ok(this.0.set_interrupt(true)));
    }
}