garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /ui/src/theme.rs

raw

//! The system's look: colours, sizes, fonts, and the few shapes every app
//! draws the same way.

use core::cell::UnsafeCell;
use core::mem::MaybeUninit;
use core::sync::atomic::{AtomicU8, Ordering};
use pinnacle_gfx::Font;
use pinnacle_gfx::font::Face;
use pinnacle_gfx::{Canvas, Color, Rect};

/// The app icon's ground (`docs/brand/`).
pub const BACKGROUND: Color = Color::rgb(0x0f, 0x14, 0x16);
pub const SURFACE: Color = Color::rgb(0x19, 0x20, 0x23);
pub const SURFACE_PRESSED: Color = Color::rgb(0x2a, 0x34, 0x39);
pub const TEXT: Color = Color::rgb(0xec, 0xee, 0xec);
pub const TEXT_DIM: Color = Color::rgb(0x8f, 0x9a, 0x9b);
/// The mark's orange.
pub const ACCENT: Color = Color::rgb(0xe8, 0x5a, 0x12);
pub const GOOD: Color = Color::rgb(0x3f, 0xb9, 0x7a);
/// What failed: an error line, a command that ended badly.
pub const BAD: Color = Color::rgb(0xe5, 0x6b, 0x6b);

pub const RADIUS: i32 = 18;

/// The system font: Adwaita Sans (based on Inter; SIL Open Font License).
pub const FONT_PATH: &str = "system:/fonts/sans.ttf";

/// The system's fixed-width font: Adwaita Mono (based on Iosevka; the same
/// licence), for the terminal and anything set in columns of characters.
pub const MONO_PATH: &str = "system:/fonts/mono.ttf";

/// The sizes the system draws text at.
struct Fonts {
    small: Font,
    body: Font,
    heading: Font,
    title: Font,
    huge: Font,
}

/// A value made the first time it is wanted: the fonts, read and parsed
/// the first time a program draws text.
struct Lazy<T> {
    /// 0: not yet, 1: being made, 2: ready.
    state: AtomicU8,
    value: UnsafeCell<MaybeUninit<T>>,
}

// SAFETY: `value` is written once, by whoever moves `state` from 0 to 1,
// and read only once `state` is 2.
unsafe impl<T> Sync for Lazy<T> {}

impl<T> Lazy<T> {
    const fn new() -> Lazy<T> {
        Lazy {
            state: AtomicU8::new(0),
            value: UnsafeCell::new(MaybeUninit::uninit()),
        }
    }

    fn get(&self, make: impl FnOnce() -> T) -> &T {
        let mut make = Some(make);
        loop {
            match self
                .state
                .compare_exchange(0, 1, Ordering::Acquire, Ordering::Acquire)
            {
                Ok(_) => {
                    let value = (make.take().unwrap())();
                    // SAFETY: only this caller got state 1.
                    unsafe { (*self.value.get()).write(value) };
                    self.state.store(2, Ordering::Release);
                }
                // SAFETY: state 2: written, and never again.
                Err(2) => return unsafe { (*self.value.get()).assume_init_ref() },
                Err(_) => pinnacle_rt::yield_now(),
            }
        }
    }
}

static FACE: Lazy<&'static Face<'static>> = Lazy::new();
static FONTS: Lazy<Fonts> = Lazy::new();
/// Apart from the others: only a few programs draw in it.
static MONO: Lazy<Font> = Lazy::new();

/// A font file's face, kept as long as the program.
fn face(path: &str) -> Option<&'static Face<'static>> {
    let data = pinnacle_rt::fs::read(path)?;
    let face = Face::parse(data.leak())?;
    Some(alloc::boxed::Box::leak(alloc::boxed::Box::new(face)))
}

fn system_face() -> &'static Face<'static> {
    FACE.get(|| {
        pinnacle_gfx::font::set_fallbacks(&FALLBACKS);
        face(FONT_PATH).unwrap_or_else(|| panic!("no TrueType font at {FONT_PATH}"))
    })
}

/// The fonts that draw what the system's lack, in the order they are
/// tried: Arabic (Noto Sans Arabic), Hebrew (Noto Sans Hebrew), Chinese,
/// Japanese and Korean (Droid Sans Fallback), emoji (Noto Emoji, in
/// outline). Each is read the first time a character needs it.
pub const FALLBACK_PATHS: [&str; 4] = [
    "system:/fonts/arabic.ttf",
    "system:/fonts/hebrew.ttf",
    "system:/fonts/cjk.ttf",
    "system:/fonts/emoji.ttf",
];

static FALLBACK_FACES: [Lazy<Option<&'static Face<'static>>>; 4] =
    [Lazy::new(), Lazy::new(), Lazy::new(), Lazy::new()];

fn fallback(i: usize) -> Option<&'static Face<'static>> {
    *FALLBACK_FACES.get(i)?.get(|| face(FALLBACK_PATHS[i]))
}

static FALLBACKS: pinnacle_gfx::font::Fallbacks = pinnacle_gfx::font::Fallbacks {
    count: FALLBACK_PATHS.len(),
    emoji: Some(3),
    face: fallback,
};

fn fonts() -> &'static Fonts {
    FONTS.get(|| {
        let face = system_face();
        Fonts {
            small: Font::new(face, 16.0),
            body: Font::new(face, 20.0),
            heading: Font::new(face, 28.0),
            title: Font::new(face, 40.0),
            huge: Font::new(face, 96.0),
        }
    })
}

pub fn small() -> &'static Font {
    &fonts().small
}

pub fn body() -> &'static Font {
    &fonts().body
}

/// Fixed-width, at the terminal's size; the system font on a disk made
/// before there was a fixed-width one.
pub fn mono() -> &'static Font {
    MONO.get(|| Font::new(face(MONO_PATH).unwrap_or_else(system_face), 18.0))
}

pub fn heading() -> &'static Font {
    &fonts().heading
}

pub fn title() -> &'static Font {
    &fonts().title
}

pub fn huge() -> &'static Font {
    &fonts().huge
}

/// An app's colour, the same every time for the same name.
pub fn color_for(name: &str) -> Color {
    const PALETTE: [Color; 8] = [
        Color::rgb(0x4c, 0x9a, 0xff),
        Color::rgb(0x3f, 0xb9, 0x7a),
        Color::rgb(0xf0, 0x8a, 0x3c),
        Color::rgb(0xd9, 0x5b, 0x8e),
        Color::rgb(0x8f, 0x6c, 0xf0),
        Color::rgb(0x2f, 0xb5, 0xc4),
        Color::rgb(0xe6, 0xb4, 0x2e),
        Color::rgb(0xe0, 0x5a, 0x4f),
    ];
    let hash = name
        .bytes()
        .fold(5381u32, |h, b| h.wrapping_mul(33) ^ u32::from(b));
    PALETTE[hash as usize % PALETTE.len()]
}

/// A button: a rounded surface with a centred label.
pub fn button(canvas: &mut Canvas, rect: Rect, label: &str, pressed: bool, color: Option<Color>) {
    let fill = color.unwrap_or(if pressed { SURFACE_PRESSED } else { SURFACE });
    canvas.fill_rounded(rect, RADIUS, fill);
    canvas.text_centered(body(), rect, label, TEXT);
}

/// A program name as people read it: "clock" → "Clock".
pub fn display_name(name: &str) -> alloc::string::String {
    let mut out = alloc::string::String::new();
    for (i, ch) in name.chars().enumerate() {
        if i == 0 {
            out.extend(ch.to_uppercase());
        } else {
            out.push(if ch == '-' { ' ' } else { ch });
        }
    }
    out
}