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
use std::{borrow::Cow, collections::HashMap};

use anyhow::Result;
use config::{Map, Value, ValueKind};
use csscolorparser::Color;
use lazy_static::lazy_static;
use regex::{Captures, Regex};
use tokio::{io::AsyncWriteExt, net::UnixStream};

use crate::{bar::EventResponse, ipc::ChannelEndpoint, parser};

lazy_static! {
    static ref REGEX: Regex = Regex::new(r"%\{(?<const>\w+)}").unwrap();
}

/// A wrapper struct to read indefinitely from a [`UnixStream`] and send the
/// results through a channel.
pub struct UnixStreamWrapper {
    inner: UnixStream,
    endpoint: ChannelEndpoint<String, EventResponse>,
}

impl UnixStreamWrapper {
    /// Creates a new wrapper from a stream and a sender
    pub const fn new(
        inner: UnixStream,
        endpoint: ChannelEndpoint<String, EventResponse>,
    ) -> Self {
        Self { inner, endpoint }
    }

    /// Reads from the inner [`UnixStream`] until an error is encountered or the
    /// program terminates.
    pub async fn run(mut self) -> Result<()> {
        let mut data = [0; 1024];
        self.inner.readable().await?;
        let len = self.inner.try_read(&mut data)?;
        let message = String::from_utf8_lossy(&data[0..len]);
        if message.len() == 0 {
            return Ok(());
        }
        self.endpoint.send.send(message.to_string())?;
        let response =
            self.endpoint.recv.recv().await.unwrap_or(EventResponse::Ok);

        self.inner.writable().await?;
        self.inner
            .try_write(serde_json::to_string(&response)?.as_bytes())?;

        self.inner.shutdown().await?;

        Ok(())
    }
}

/// Removes a value from a given config table and returns an attempt at parsing
/// it into a table
pub fn get_table_from_config<S: std::hash::BuildHasher>(
    id: &str,
    table: &HashMap<String, Value, S>,
) -> Option<Map<String, Value>> {
    table.get(id).and_then(|val| {
        val.clone().into_table().map_or_else(
            |_| {
                log::warn!("Ignoring non-table value {val:?}");
                None
            },
            Some,
        )
    })
}

/// Removes a value from a given config table and returns an attempt at parsing
/// it into a string
pub fn remove_string_from_config<S: std::hash::BuildHasher>(
    id: &str,
    table: &mut HashMap<String, Value, S>,
) -> Option<String> {
    table.remove(id).and_then(|val| {
        val.clone().into_string().map_or_else(
            |_| {
                log::warn!("Ignoring non-string value {val:?}");
                None
            },
            |s| {
                Some(
                    replace_consts(s.as_str(), parser::CONSTS.get().unwrap())
                        .to_string(),
                )
            },
        )
    })
}

/// Removes a value from a given config table and returns an attempt at parsing
/// it into an array
pub fn remove_array_from_config<S: std::hash::BuildHasher>(
    id: &str,
    table: &mut HashMap<String, Value, S>,
) -> Option<Vec<Value>> {
    table.remove(id).and_then(|val| {
        val.clone().into_array().map_or_else(
            |_| {
                log::warn!("Ignoring non-array value {val:?}");
                None
            },
            |v| {
                Some(
                    v.into_iter()
                        .map(|val| {
                            let origin = val.origin().map(ToString::to_string);
                            val.clone().into_string().map_or(val, |val| {
                                Value::new(
                                    origin.as_ref(),
                                    ValueKind::String(
                                        replace_consts(
                                            val.as_str(),
                                            parser::CONSTS.get().unwrap(),
                                        )
                                        .to_string(),
                                    ),
                                )
                            })
                        })
                        .collect(),
                )
            },
        )
    })
}

/// Removes a value from a given config table and returns an attempt at parsing
/// it into a uint
pub fn remove_uint_from_config<S: std::hash::BuildHasher>(
    id: &str,
    table: &mut HashMap<String, Value, S>,
) -> Option<u64> {
    table.remove(id).and_then(|val| {
        val.clone().into_uint().map_or_else(
            |_| {
                log::warn!("Ignoring non-uint value {val:?}");
                None
            },
            Some,
        )
    })
}

/// Removes a value from a given config table and returns an attempt at parsing
/// it into a bool
pub fn remove_bool_from_config<S: std::hash::BuildHasher>(
    id: &str,
    table: &mut HashMap<String, Value, S>,
) -> Option<bool> {
    table.remove(id).and_then(|val| {
        val.clone().into_bool().map_or_else(
            |_| {
                log::warn!("Ignoring non-boolean value {val:?}");
                None
            },
            Some,
        )
    })
}

/// Removes a value from a given config table and returns an attempt at parsing
/// it into a float
pub fn remove_float_from_config<S: std::hash::BuildHasher>(
    id: &str,
    table: &mut HashMap<String, Value, S>,
) -> Option<f64> {
    table.remove(id).and_then(|val| {
        val.clone().into_float().map_or_else(
            |_| {
                log::warn!("Ignoring non-float value {val:?}");
                None
            },
            Some,
        )
    })
}

/// Removes a value from a given config table and returns an attempt at parsing
/// it into a color
pub fn remove_color_from_config<S: std::hash::BuildHasher>(
    id: &str,
    table: &mut HashMap<String, Value, S>,
) -> Option<Color> {
    table.remove(id).and_then(|val| {
        val.clone().into_string().map_or_else(
            |_| {
                log::warn!("Ignoring non-string value {val:?}");
                None
            },
            |val| {
                replace_consts(val.as_str(), parser::CONSTS.get().unwrap())
                    .parse()
                    .map_or_else(
                        |_| {
                            log::warn!("Invalid color {val}");
                            None
                        },
                        Some,
                    )
            },
        )
    })
}

/// Replace references to constants (of the form `%{const_name}`) with their
/// respective constants
pub fn replace_consts<'a, S: std::hash::BuildHasher>(
    format: &'a str,
    consts: &HashMap<String, Value, S>,
) -> Cow<'a, str> {
    REGEX.replace_all(format, |caps: &Captures| {
        let con = &caps["const"];
        consts
            .get(con)
            .and_then(|c| c.clone().into_string().ok())
            .map_or_else(
                || {
                    log::warn!("Invalid constant: {con}");
                    String::new()
                },
                |con| con,
            )
    })
}