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
use image::RgbaImage;

use super::*;
use crate::component::Component;
use anyhow::{Context, Error, Result};
use std::pin::Pin;

type RgbaImageFuture = Pin<Box<dyn Future<Output = Result<RgbaImage>>>>;
type DataFuture = Pin<Box<dyn Future<Output = Result<Vec<u8>>>>>;

/// Builds a style.
#[derive(Default)]
pub struct StyleBuilder {
    pub(crate) images: HashMap<String, RgbaImageFuture>,
    pub(crate) patches: HashMap<String, RgbaImageFuture>,
    pub(crate) fonts: HashMap<String, DataFuture>,
    pub(crate) rule_tree: tree::RuleTreeBuilder,
}

/// Handle to an image in a `StyleBuilder`.
#[derive(Debug)]
pub struct ImageId(pub(crate) String);
/// Handle to a patch in a `StyleBuilder`.
#[derive(Debug)]
pub struct PatchId(pub(crate) String);
/// Handle to a font in a `StyleBuilder`.
#[derive(Debug)]
pub struct FontId(pub(crate) String);

/// Builder that adds style declarations to a selected rule.
pub struct RuleBuilder {
    selector: Vec<Selector>,
    declarations: Vec<Declaration<ImageId, PatchId, FontId>>,
}

impl StyleBuilder {
    fn base(foreground: Color, background: Color, primary: Color) -> Self {
        Self::default()
            .rule(RuleBuilder::new("*").color(foreground))
            .rule(
                RuleBuilder::new("button")
                    .padding_all(5.0)
                    .margin_all(5.0)
                    .background_color(background),
            )
            .rule(RuleBuilder::new("button:hover").background_color(background.blend(primary, 0.5)))
            .rule(RuleBuilder::new("button:pressed").background_color(primary))
            .rule(
                RuleBuilder::new("dropdown")
                    .background_color(background)
                    .color(background.blend(primary, 0.5))
                    .padding_all(5.0)
                    .margin_all(5.0),
            )
            .rule(
                RuleBuilder::new("input")
                    .width(300.0)
                    .background_color(Color::white())
                    .color(Color::black())
                    .padding_all(5.0)
                    .margin_all(5.0),
            )
            .rule(RuleBuilder::new("layers").fill_width().fill_height())
            .rule(
                RuleBuilder::new("menu")
                    .background_color(background)
                    .color(background.blend(primary, 0.5))
                    .padding_all(5.0),
            )
            .rule(RuleBuilder::new("spacer").fill_width().fill_height())
            .rule(
                RuleBuilder::new("window")
                    .background_color(background.blend(foreground, 0.2))
                    .padding_all(2.0),
            )
            .rule(RuleBuilder::new("window > *:nth-child(0)").background_color(background.blend(primary, 0.2)))
    }

    /// Add a rule defined in a [`RuleBuilder`](struct.RuleBuilder.html) to the `StyleBuilder`.
    pub fn rule(mut self, builder: RuleBuilder) -> Self {
        self.rule_tree.insert(builder.selector.as_slice(), builder.declarations);
        self
    }

    /// Prepend the given selector to all rules in this `StyleBuilder`.
    pub fn scope<S: AsRef<str>>(mut self, selector: S) -> Self {
        let mut old = std::mem::take(&mut self.rule_tree);

        let selector = parse_selectors(tokenize(selector.as_ref().to_string()).unwrap()).unwrap();
        if let Some(new_root) = selector.as_slice().last() {
            old.selector = new_root.clone();
        }
        self.rule_tree.select(selector.as_slice()).merge(old);

        self
    }

    /// Merge with another `StyleBuilder`.
    pub fn merge(mut self, builder: StyleBuilder) -> Self {
        self.images.extend(builder.images);
        self.patches.extend(builder.patches);
        self.fonts.extend(builder.fonts);
        self.rule_tree.merge(builder.rule_tree);
        self
    }

    /// Include the scoped style of a `Component` in this `StyleBuilder`.
    pub fn component<C: Component>(mut self) -> Self {
        let mut builder = C::style();
        self.images.extend(builder.images);
        self.patches.extend(builder.patches);
        self.fonts.extend(builder.fonts);
        let name = std::any::type_name::<C>().to_string();
        builder.rule_tree.selector = Selector::Widget(SelectorWidget::Some(name.clone()));
        self.rule_tree
            .select(&[Selector::Widget(SelectorWidget::Some(name))])
            .merge(builder.rule_tree);
        self
    }

    /// Asynchronously load a stylesheet from a .pwss file. See the [style module documentation](../index.html) on how to write
    /// .pwss files.
    pub async fn from_read_fn<P, R>(path: P, read: R) -> anyhow::Result<Self>
    where
        P: AsRef<Path>,
        R: ReadFn,
    {
        let text = String::from_utf8(read.read(path.as_ref()).await?).unwrap();
        Ok(parse(tokenize(text)?, read).await?)
    }

    /// Synchronously load a stylesheet from a .pwss file. See the [style module documentation](../index.html) on how to write
    /// .pwss files.
    pub fn from_file<P>(path: P) -> anyhow::Result<Self>
    where
        P: AsRef<Path>,
    {
        futures::executor::block_on(Self::from_read_fn(path, |path: &Path| {
            std::future::ready(std::fs::read(path))
        }))
    }

    /// Returns an `ImageId` for the `key`.
    /// When the style is built, the image is loaded using the closure.
    pub fn load_image(
        &mut self,
        key: impl Into<String>,
        load: impl FnOnce() -> Result<RgbaImage> + 'static,
    ) -> ImageId {
        self.load_image_async(key, async move { load() })
    }

    /// Returns a `PatchId` for the `key`.
    /// When the style is built, the 9-patch is loaded using the closure.
    pub fn load_patch(
        &mut self,
        key: impl Into<String>,
        load: impl FnOnce() -> Result<RgbaImage> + 'static,
    ) -> PatchId {
        self.load_patch_async(key, async move { load() })
    }

    /// Returns a `FontId` for the `key`.
    /// When the style is built, the font is loaded using the closure.
    /// The closure must return the bytes of a .ttf file.
    pub fn load_font(&mut self, key: impl Into<String>, load: impl FnOnce() -> Result<Vec<u8>> + 'static) -> FontId {
        self.load_font_async(key, async move { load() })
    }

    /// Returns an `ImageId` for the `key`.
    /// When the style is built, the image is loaded by awaiting the future.
    pub fn load_image_async(
        &mut self,
        key: impl Into<String>,
        fut: impl Future<Output = Result<RgbaImage>> + 'static,
    ) -> ImageId {
        let key = key.into();
        if let std::collections::hash_map::Entry::Vacant(v) = self.images.entry(key.clone()) {
            v.insert(Box::pin(fut));
        }
        ImageId(key)
    }

    /// Returns a `PatchId` for the `key`.
    /// When the style is built, the 9-patch is loaded by awaiting the future.
    pub fn load_patch_async(
        &mut self,
        key: impl Into<String>,
        fut: impl Future<Output = Result<RgbaImage>> + 'static,
    ) -> PatchId {
        let key = key.into();
        if let std::collections::hash_map::Entry::Vacant(v) = self.patches.entry(key.clone()) {
            v.insert(Box::pin(fut));
        }
        PatchId(key)
    }

    /// Returns a `FontId` for the `key`.
    /// When the style is built, the font is loaded by awaiting the future.
    /// The future must output the bytes of a .ttf file.
    pub fn load_font_async(
        &mut self,
        key: impl Into<String>,
        fut: impl Future<Output = Result<Vec<u8>>> + 'static,
    ) -> FontId {
        let key = key.into();
        if let std::collections::hash_map::Entry::Vacant(v) = self.fonts.entry(key.clone()) {
            v.insert(Box::pin(fut));
        }
        FontId(key)
    }

    /// Builds the `Style`. All loading of images, 9 patches and fonts happens in this method.
    /// If any of them fail, an error is returned.
    pub async fn build_async(mut self) -> Result<Style> {
        self = Self::base(Color::white(), Color::rgb(0.3, 0.3, 0.3), Color::blue()).merge(self);

        let mut cache = Cache::new(512);

        let font = cache.load_font(include_bytes!("default_font.ttf").to_vec()).unwrap();

        let mut images = HashMap::new();
        for (key, value) in self.images {
            images.insert(
                key.clone(),
                cache.load_image(
                    value
                        .await
                        .with_context(|| format!("Failed to load image \"{}\": ", key))?,
                ),
            );
        }

        let mut patches = HashMap::new();
        for (key, value) in self.patches {
            patches.insert(
                key.clone(),
                cache.load_patch(
                    value
                        .await
                        .with_context(|| format!("Failed to load 9 patch \"{}\": ", key))?,
                ),
            );
        }

        let mut fonts = HashMap::new();
        for (key, value) in self.fonts {
            let load = async { Result::<_, Error>::Ok(cache.load_font(value.await?)?) };
            fonts.insert(
                key.clone(),
                load.await
                    .with_context(|| format!("Failed to load font \"{}\": ", key))?,
            );
        }

        Ok(Style {
            cache: Arc::new(Mutex::new(cache)),
            resolved: Default::default(),
            default: Stylesheet {
                background: Background::None,
                font,
                color: Color::white(),
                padding: Rectangle::zero(),
                margin: Rectangle::zero(),
                text_size: 16.0,
                text_wrap: TextWrap::NoWrap,
                width: Size::Shrink,
                height: Size::Shrink,
                direction: Direction::LeftToRight,
                align_horizontal: Align::Begin,
                align_vertical: Align::Begin,
                flags: Vec::new(),
            },
            rule_tree: self.rule_tree.build(&images, &patches, &fonts),
        })
    }

    /// Builds the `Style`. All loading of images, 9 patches and fonts happens in this method.
    /// If any of them fail, an error is returned.
    pub fn build(self) -> Result<Style> {
        futures::executor::block_on(self.build_async())
    }
}

impl TryInto<Style> for StyleBuilder {
    type Error = Error;

    fn try_into(self) -> Result<Style> {
        self.build()
    }
}

impl RuleBuilder {
    /// Constructs a new `RuleBuilder` for the given selector.
    /// The selector must follow the same syntax as the [.pwss file format](../index.html).
    ///
    /// Panics if the selector can't be parsed.
    ///
    /// ```rust
    /// use pixel_widgets::prelude::*;
    ///
    /// // Sets the background of the first direct child of any window widget
    /// RuleBuilder::new("window > * :nth-child(0)").background_color(Color::red());
    /// ```
    pub fn new<S: AsRef<str>>(selector: S) -> Self {
        Self {
            selector: parse_selectors(tokenize(selector.as_ref().to_string()).unwrap()).unwrap(),
            declarations: Vec::new(),
        }
    }
    /// Clears the background
    pub fn background_none(mut self) -> Self {
        self.declarations.push(Declaration::BackgroundNone);
        self
    }
    /// Sets the background to a color
    pub fn background_color(mut self, color: Color) -> Self {
        self.declarations.push(Declaration::BackgroundColor(color));
        self
    }
    /// Sets the background to a colored image
    pub fn background_image(mut self, image_data: ImageId, color: Color) -> Self {
        self.declarations.push(Declaration::BackgroundImage(image_data, color));
        self
    }
    /// Sets the background to a colored patch
    pub fn background_patch(mut self, patch: PatchId, color: Color) -> Self {
        self.declarations.push(Declaration::BackgroundPatch(patch, color));
        self
    }
    /// Sets the font
    pub fn font(mut self, value: FontId) -> Self {
        self.declarations.push(Declaration::Font(value));
        self
    }
    /// Sets the foreground color
    pub fn color(mut self, value: Color) -> Self {
        self.declarations.push(Declaration::Color(value));
        self
    }
    /// Sets padding
    pub fn padding(mut self, value: Rectangle) -> Self {
        self.declarations.push(Declaration::Padding(value));
        self
    }
    /// Sets all padding values to the same value
    pub fn padding_all(self, value: f32) -> Self {
        self.padding(Rectangle {
            left: value,
            top: value,
            right: value,
            bottom: value,
        })
    }
    /// Sets horizontal padding values to the same value
    pub fn padding_horizontal(self, value: f32) -> Self {
        self.padding_left(value).padding_right(value)
    }
    /// Sets vertical padding values to the same value
    pub fn padding_vertical(self, value: f32) -> Self {
        self.padding_top(value).padding_bottom(value)
    }
    /// Sets left padding
    pub fn padding_left(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::PaddingLeft(value));
        self
    }
    /// Sets right padding
    pub fn padding_right(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::PaddingRight(value));
        self
    }
    /// Sets top padding
    pub fn padding_top(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::PaddingTop(value));
        self
    }
    /// Sets bottom padding
    pub fn padding_bottom(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::PaddingBottom(value));
        self
    }
    /// Sets the margins
    pub fn margin(mut self, value: Rectangle) -> Self {
        self.declarations.push(Declaration::Margin(value));
        self
    }
    /// Sets all margin values to the same value
    pub fn margin_all(self, value: f32) -> Self {
        self.margin(Rectangle {
            left: value,
            top: value,
            right: value,
            bottom: value,
        })
    }
    /// Sets horizontal margin values to the same value
    pub fn margin_horizontal(self, value: f32) -> Self {
        self.margin_left(value).margin_right(value)
    }
    /// Sets vertical margin values to the same value
    pub fn margin_vertical(self, value: f32) -> Self {
        self.margin_top(value).margin_bottom(value)
    }
    /// Sets the left margin
    pub fn margin_left(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::MarginLeft(value));
        self
    }
    /// Sets the right margin
    pub fn margin_right(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::MarginRight(value));
        self
    }
    /// Sets the top margin
    pub fn margin_top(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::MarginTop(value));
        self
    }
    /// Sets the bottom margin
    pub fn margin_bottom(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::MarginBottom(value));
        self
    }
    /// Sets the text size
    pub fn text_size(mut self, value: f32) -> Self {
        self.declarations.push(Declaration::TextSize(value));
        self
    }
    /// Sets the way text wraps
    pub fn text_wrap(mut self, value: TextWrap) -> Self {
        self.declarations.push(Declaration::TextWrap(value));
        self
    }
    /// Sets the preferred width
    pub fn width(mut self, value: impl Into<Size>) -> Self {
        self.declarations.push(Declaration::Width(value.into()));
        self
    }
    /// Sets the preferred width to Size::Fill(1)
    pub fn fill_width(mut self) -> Self {
        self.declarations.push(Declaration::Width(Size::Fill(1)));
        self
    }
    /// Sets the preferred height
    pub fn height(mut self, value: impl Into<Size>) -> Self {
        self.declarations.push(Declaration::Height(value.into()));
        self
    }
    /// Sets the preferred height to Size::Fill(1)
    pub fn fill_height(mut self) -> Self {
        self.declarations.push(Declaration::Height(Size::Fill(1)));
        self
    }
    /// Sets the direction for layouting
    pub fn layout_direction(mut self, value: Direction) -> Self {
        self.declarations.push(Declaration::LayoutDirection(value));
        self
    }
    /// Sets the horizontal alignment
    pub fn align_horizontal(mut self, value: Align) -> Self {
        self.declarations.push(Declaration::AlignHorizontal(value));
        self
    }
    /// Sets the vertical alignment
    pub fn align_vertical(mut self, value: Align) -> Self {
        self.declarations.push(Declaration::AlignVertical(value));
        self
    }
    /// Adds a flag to the stylesheet
    pub fn add_flag(mut self, value: String) -> Self {
        self.declarations.push(Declaration::AddFlag(value));
        self
    }
    /// Removes a flag from the stylesheet
    pub fn remove_flag(mut self, value: String) -> Self {
        self.declarations.push(Declaration::RemoveFlag(value));
        self
    }
}