canary-rs/scripts/sao-ui/src/widgets/palette.rs

110 lines
2.7 KiB
Rust

// Copyright (c) 2022 Marceline Crmaer
// SPDX-License-Identifier: AGPL-3.0-or-later
use super::prelude::*;
use shell::Offset;
use text::{HorizontalAlignment, Label, LabelText};
pub struct PaletteStyle {
pub bg: Color,
pub text: Color,
pub rounding: f32,
pub text_size: f32,
pub line_spacing: f32,
pub color_radius: f32,
pub margin: Rect,
}
impl Default for PaletteStyle {
fn default() -> Self {
Self {
bg: THEME.palette.surface,
text: THEME.palette.text,
rounding: THEME.metrics.surface_rounding,
text_size: 5.0,
line_spacing: 8.0,
color_radius: 3.0,
margin: Rect::from_xy_size(Vec2::splat(10.0), Vec2::ZERO),
}
}
}
/// A widget that displays all the colors in the global palette.
pub struct Palette {
body: Rect,
style: PaletteStyle,
labels: Vec<Offset<Label>>,
colors: Vec<(Vec2, Color)>,
}
impl Palette {
pub fn new(style: PaletteStyle) -> Self {
let width = 70.0;
let pairs = THEME.palette.make_label_pairs();
let label_font = Font::new(crate::CONTENT_FONT);
let mut label_cursor = Vec2::new(0.0, style.line_spacing) + style.margin.tl;
let mut color_cursor = Vec2::new(
width - style.margin.br.x,
style.line_spacing / 2.0 + style.margin.tl.y,
);
let mut labels = Vec::new();
let mut colors = Vec::new();
for (text, color) in pairs {
let text = LabelText {
font: label_font,
text: text.to_string(),
};
let label = Label::new(
text,
HorizontalAlignment::Left,
style.text_size,
style.text,
0.0,
0.0,
0.0,
);
let label = Offset::new(label, label_cursor);
labels.push(label);
colors.push((color_cursor, color));
label_cursor.y += style.line_spacing;
color_cursor.y += style.line_spacing;
}
let height = label_cursor.y + style.margin.br.y;
Self {
body: Rect::from_xy_size(Vec2::ZERO, Vec2::new(width, height)),
style,
labels,
colors,
}
}
}
impl RectBounds for Palette {
fn get_bounds(&self) -> Rect {
self.body
}
}
impl Widget for Palette {
fn draw(&mut self, ctx: &DrawContext) {
ctx.draw_rounded_rect(self.body, self.style.rounding, self.style.bg);
for label in self.labels.iter_mut() {
label.draw(ctx);
}
for (center, color) in self.colors.iter() {
ctx.draw_circle(*center, self.style.color_radius, *color);
}
}
}