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

use anyhow::Result;
use config::{Config, Map, Value};
use csscolorparser::Color;
use derive_builder::Builder;
use pangocairo::functions::show_layout;
use tokio::{io::AsyncWriteExt, net::UnixStream};

use crate::{
    bar::{Dependence, EventResponse, PanelDrawInfo},
    ipc::ChannelEndpoint,
    Attrs, Ramp,
};

/// 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(())
    }
}

/// The end of a typical draw function.
///
/// Takes a cairo context, a string to
/// display, and attributes to use, and returns a closure that will do the
/// drawing and a tuple representing the final width and height.
///
/// The text will be interpreted as markup. If this is not your intended
/// behavior, use [`markup_escape_text`][crate::markup_escape_text] to display
/// what you want or implement this functionality manually.
pub fn draw_common(
    cr: &Rc<cairo::Context>,
    text: &str,
    attrs: &Attrs,
    dependence: Dependence,
    height: i32,
) -> Result<PanelDrawInfo> {
    let layout = pangocairo::functions::create_layout(cr);
    layout.set_markup(text);
    attrs.apply_font(&layout);
    let dims = layout.pixel_size();

    let attrs = attrs.clone();
    let bg = attrs.bg.clone().unwrap_or_default();

    Ok(PanelDrawInfo::new(
        bg.adjust_dims(dims, height),
        dependence,
        Box::new(move |cr| {
            let offset =
                bg.draw(cr, dims.0 as f64, dims.1 as f64, height as f64)?;
            cr.save()?;
            cr.translate(
                offset.0,
                if offset.1 {
                    (height - dims.1) as f64 / 2.0
                } else {
                    0.0
                },
            );
            attrs.apply_fg(cr);
            show_layout(cr, &layout);
            cr.restore()?;
            Ok(())
        }),
    ))
}

/// A map from mouse buttons to panel events
#[derive(Debug, Clone, Default, Builder)]
pub struct Actions {
    /// The event that should be run when the panel is left-clicked
    #[builder(default = "String::new()")]
    pub left: String,
    /// The event that should be run when the panel is right-clicked
    #[builder(default = "String::new()")]
    pub right: String,
    /// The event that should be run when the panel is middle-clicked
    #[builder(default = "String::new()")]
    pub middle: String,
    /// The event that should be run when the panel is scrolled up
    #[builder(default = "String::new()")]
    pub up: String,
    /// The event that should be run when the panel is scrolled down
    #[builder(default = "String::new()")]
    pub down: String,
}

impl Actions {
    /// Attempts to parse an instance of this type from a subset of tthe global
    /// [`Config`][config::Config].
    ///
    /// Configuration options:
    /// - `click_left`: The name of the event to run when the panel is
    ///   left-clicked.
    /// - `click_right`: The name of the event to run when the panel is
    ///   right-clicked.
    /// - `click_middle`: The name of the event to run when the panel is
    ///   middle-clicked.
    /// - `scroll_up`: The name of the event to run when the panel is scrolled
    ///   up.
    /// - `scroll_down`: The name of the event to run when the panel is scrolled
    ///   down.
    pub fn parse<S: std::hash::BuildHasher>(
        table: &mut HashMap<String, Value, S>,
    ) -> Result<Self> {
        let mut builder = ActionsBuilder::default();

        if let Some(left) = remove_string_from_config("click_left", table) {
            builder.left(left);
        }
        if let Some(right) = remove_string_from_config("click_right", table) {
            builder.right(right);
        }
        if let Some(middle) = remove_string_from_config("click_middle", table) {
            builder.middle(middle);
        }
        if let Some(up) = remove_string_from_config("scroll_up", table) {
            builder.up(up);
        }
        if let Some(down) = remove_string_from_config("scroll_down", table) {
            builder.down(down);
        }

        Ok(builder.build()?)
    }
}

/// The common part of most [`PanelConfigs`][crate::PanelConfig]. Stores format
/// strings, [`Attrs`], and [`Dependence`]
#[derive(Debug, Clone, Builder)]
#[builder_struct_attr(allow(missing_docs))]
#[builder_impl_attr(allow(missing_docs))]
pub struct PanelCommon {
    /// The format strings used by the panel
    pub formats: Vec<String>,
    /// Whether the panel depends on its neighbors
    pub dependence: Dependence,
    /// The instances of [`Attrs`] used by the panel
    pub attrs: Vec<Attrs>,
    /// The events that should be run on mouse events
    pub actions: Actions,
    /// The ramps that are available for use in format strings
    pub ramps: Vec<Ramp>,
    /// Whether the panel should be visible on startup
    pub visible: bool,
}

impl PanelCommon {
    /// Attempts to parse common panel configuration options from a subset of
    /// the global [`Config`][config::Config]. The format suffixes and defaults
    /// and attrs prefixes are documented by each panel.
    ///
    /// Format strings should be specified as `format{suffix} = "value"`. Where
    /// not noted, panels accept one format string with no suffix.
    /// Dependence should be specified as `dependence = "value"`, where value is
    /// a valid variant of [`Dependence`].
    /// See [`Attrs::parse`] and [`Actions::parse`] for more parsing details.
    pub fn parse<S: std::hash::BuildHasher>(
        table: &mut HashMap<String, Value, S>,
        global: &Config,
        format_suffixes: &[&'static str],
        format_defaults: &[&'static str],
        attrs_prefixes: &[&'static str],
        ramp_suffixes: &[&'static str],
    ) -> Result<Self> {
        let mut builder = PanelCommonBuilder::default();

        builder.formats(
            format_suffixes
                .iter()
                .zip(format_defaults.iter())
                .map(|(suffix, default)| {
                    remove_string_from_config(
                        format!("format{suffix}").as_str(),
                        table,
                    )
                    .unwrap_or_else(|| (*default).to_string())
                })
                .collect(),
        );
        log::debug!("got formats: {:?}", builder.formats);

        builder.dependence(
            match remove_string_from_config("dependence", table)
                .map(|s| s.to_lowercase())
                .as_deref()
            {
                Some("left") => Dependence::Left,
                Some("right") => Dependence::Right,
                Some("both") => Dependence::Both,
                _ => Dependence::None,
            },
        );
        log::debug!("got dependence: {:?}", builder.dependence);

        builder.attrs(
            attrs_prefixes
                .iter()
                .map(|p| {
                    if let Some(name) = remove_string_from_config(
                        format!("{p}attrs").as_str(),
                        table,
                    ) {
                        Attrs::parse(name, global).unwrap_or_default()
                    } else {
                        Attrs::default()
                    }
                })
                .collect(),
        );
        log::debug!("got attrs: {:?}", builder.attrs);

        builder.actions(Actions::parse(table)?);
        log::debug!("got actions: {:?}", builder.actions);

        builder.ramps(
            ramp_suffixes
                .iter()
                .map(|suffix| {
                    if let Some(ramp) = remove_string_from_config(
                        format!("ramp{suffix}").as_str(),
                        table,
                    ) {
                        Ramp::parse(ramp, global)
                    } else {
                        None
                    }
                    .unwrap_or_default()
                })
                .collect(),
        );
        log::debug!("got ramps: {:?}", builder.ramps);

        builder
            .visible(remove_bool_from_config("visible", table).unwrap_or(true));

        Ok(builder.build()?)
    }

    /// Attempts to parse common panel configuration options from a subset of
    /// the global [`Config`][config::Config]. The format defaults, attrs
    /// prefixes, and ramp suffixes are documented by each panel.
    ///
    /// Format strings should be specified as `formats = ["value", ...]`.
    /// Dependence should be specified as `dependence = "value"`, where value is
    /// a valid variant of [`Dependence`].
    /// See [`Attrs::parse`] for more parsing details.
    pub fn parse_variadic<S: std::hash::BuildHasher>(
        table: &mut HashMap<String, Value, S>,
        global: &Config,
        format_default: &[&'static str],
        attrs_prefixes: &[&'static str],
        ramp_suffixes: &[&'static str],
    ) -> Result<Self> {
        let mut builder = PanelCommonBuilder::default();

        builder.formats(
            remove_array_from_config("formats", table)
                .map(|arr| {
                    arr.into_iter()
                        .filter_map(|v| v.into_string().ok())
                        .collect::<Vec<_>>()
                })
                .unwrap_or_else(|| {
                    format_default
                        .iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>()
                }),
        );
        log::debug!("got formats: {:?}", builder.formats);

        builder.dependence(
            match remove_string_from_config("dependence", table)
                .map(|s| s.to_lowercase())
                .as_deref()
            {
                Some("left") => Dependence::Left,
                Some("right") => Dependence::Right,
                Some("both") => Dependence::Both,
                _ => Dependence::None,
            },
        );
        log::debug!("got dependence: {:?}", builder.dependence);

        builder.attrs(
            attrs_prefixes
                .iter()
                .map(|p| {
                    if let Some(name) = remove_string_from_config(
                        format!("{p}attrs").as_str(),
                        table,
                    ) {
                        Attrs::parse(name, global).unwrap_or_default()
                    } else {
                        Attrs::default()
                    }
                })
                .collect(),
        );
        log::debug!("got attrs: {:?}", builder.attrs);

        builder.actions(Actions::parse(table)?);
        log::debug!("got actions: {:?}", builder.actions);

        builder.ramps(
            ramp_suffixes
                .iter()
                .map(|suffix| {
                    if let Some(ramp) = remove_string_from_config(
                        format!("ramp{suffix}").as_str(),
                        table,
                    ) {
                        Ramp::parse(ramp, global)
                    } else {
                        None
                    }
                    .unwrap_or_default()
                })
                .collect(),
        );
        log::debug!("got ramps: {:?}", builder.ramps);

        builder
            .visible(remove_bool_from_config("visible", table).unwrap_or(true));

        Ok(builder.build()?)
    }
}

/// 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
            },
            Some,
        )
    })
}

/// 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
            },
            Some,
        )
    })
}

/// 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| {
                val.parse().map_or_else(
                    |_| {
                        log::warn!("Invalid color {val}");
                        None
                    },
                    Some,
                )
            },
        )
    })
}