Skip to main content

desktop/
desktop.rs

1//! A whole screen drawn by this library alone: a desktop with a taskbar, a launcher, and
2//! windows that move, resize, minimize, close and come to the front, each running a small
3//! program. Nothing in it asks a system for anything. The interface renders into a screen-sized
4//! pixel buffer, mouse and keyboard arrive as events, time is supplied, and the interface draws
5//! the pointer itself: all a machine with a display, mouse and keyboard needs to provide for a
6//! desktop.
7//!
8//!   cargo run -p taut --example desktop
9//!       in a window, to try by hand (the window stands in for the screen)
10//!   cargo run -p taut --example desktop -- --frames <folder>
11//!       with no window at all: a short session plays on a screen that is only a pixel
12//!       buffer, images of it are written to the folder, and each step's cost is reported
13use std::path::Path;
14use std::time::{Duration, Instant};
15use taut::geom::{Point, Size, pt};
16use taut::{Align, Button, Color, Event, Key, Length, LocalClipboard, Mods, Panel, Role, Surface, Theme, Ui, Window};
17
18/// The programs of this desktop: each has a window of its own.
19const PROGRAMS: [&str; 4] = ["Files", "Notes", "Monitor", "Settings"];
20/// What the first of them lists.
21const FILES: [(&str, &str); 6] = [("boot.cfg", "1 KB"), ("kernel.bin", "4,218 KB"), ("fonts", "folder"), ("notes.txt", "2 KB"), ("wallpaper.png", "812 KB"), ("users", "folder")];
22/// The colours to choose from for what stands out.
23const TINTS: [(&str, u32); 3] = [("Violet", 0x8b93ff), ("Green", 0x2fb38a), ("Amber", 0xe08a3c)];
24/// How high the bar of tasks is.
25const BAR: f32 = 44.0;
26
27/// Everything the desktop keeps.
28struct Desk {
29    /// The window of each program: where it is, and whether it is open.
30    windows: [Panel; 4],
31    selected: usize,
32    notes: String,
33    light: bool,
34    tint: usize,
35    /// How long the machine has been up, as whoever runs the screen tells it.
36    up: Duration,
37    /// Nothing else draws a pointer on this screen: the desktop does.
38    own_pointer: bool,
39}
40
41fn desk() -> Desk {
42    let closed = |x: f32, y: f32, wide: f32, high: f32| Panel { open: false, ..Panel::new(x, y, wide, high) };
43    let windows = [Panel::new(60.0, 50.0, 300.0, 300.0), closed(420.0, 90.0, 380.0, 280.0), closed(840.0, 60.0, 320.0, 210.0), closed(700.0, 380.0, 300.0, 170.0)];
44    Desk { windows, selected: 1, notes: String::new(), light: false, tint: 0, up: Duration::ZERO, own_pointer: false }
45}
46
47/// The whole screen, as it is right now.
48fn describe(desk: &mut Desk, ui: &mut Ui) {
49    ui.theme = Theme { accent: Color::rgb(TINTS[desk.tint].1), ..if desk.light { Theme::light() } else { Theme::dark() } };
50    let t = ui.theme;
51    // The wall behind everything, in colours that go into each other. A right click on it
52    // opens a menu of the programs.
53    let far = if desk.light { Color::rgb(0xc9d3f2) } else { Color::rgb(0x1c2444) };
54    let wall = ui.el().grow().gradient_along(150.0, &[(0.0, t.bg), (1.0, far)]).sense().show();
55    if ui.context_menu(&wall) {
56        launcher(desk, ui);
57        ui.close();
58    }
59    // A window for each program that is open.
60    for (number, name) in PROGRAMS.iter().enumerate() {
61        if !ui.panel(&mut desk.windows[number], name) {
62            continue;
63        }
64        match number {
65            0 => files(desk, ui),
66            1 => notes(desk, ui),
67            2 => monitor(desk, ui),
68            _ => settings(desk, ui),
69        }
70        ui.close();
71    }
72    tasks(desk, ui);
73    if desk.own_pointer {
74        ui.show_pointer();
75    }
76}
77
78/// The rows of a menu that opens the programs.
79fn launcher(desk: &mut Desk, ui: &mut Ui) {
80    for (number, name) in PROGRAMS.iter().enumerate() {
81        desk.windows[number].open |= ui.menu_item(name).clicked;
82    }
83}
84
85/// The bar along the bottom of the screen, over everything: the launcher, a button for each
86/// program (down while its window is open), and how long the machine has been up.
87fn tasks(desk: &mut Desk, ui: &mut Ui) {
88    let t = ui.theme;
89    ui.pin(Align::Start, Align::End);
90    let wide = ui.size().w;
91    ui.row().w(Length::Px(wide)).h(Length::Px(BAR)).pad((8.0, 0.0)).gap(6.0).fill(t.panel).border(t.line, 1.0).open();
92    let start = ui.primary_button("Start");
93    if start.clicked {
94        ui.open_popup(start.id, start.rect);
95    }
96    if ui.menu(start.id) {
97        launcher(desk, ui);
98        ui.close();
99    }
100    for (number, name) in PROGRAMS.iter().enumerate() {
101        ui.toggle(&mut desk.windows[number].open, name);
102    }
103    ui.spacer();
104    let seconds = desk.up.as_secs();
105    ui.text(&format!("up {}:{:02}:{:02}", seconds / 3600, seconds / 60 % 60, seconds % 60), t.font, t.text_dim);
106    // (The bar says the time again when the next second starts, and not before.)
107    ui.wake_after(Duration::from_millis(1000 - desk.up.subsec_millis() as u64));
108    ui.close();
109}
110
111fn files(desk: &mut Desk, ui: &mut Ui) {
112    for (number, (name, _)) in FILES.iter().enumerate() {
113        desk.selected = if ui.selectable(desk.selected == number, name).clicked { number } else { desk.selected };
114    }
115    let (name, size) = FILES[desk.selected];
116    ui.note(&format!("{name}: {size}"));
117}
118
119fn notes(desk: &mut Desk, ui: &mut Ui) {
120    ui.text_area(&mut desk.notes, "Write something", (8, 8));
121    ui.note(&format!("{} letters", desk.notes.chars().count()));
122}
123
124/// A line that moves: drawn ten times a second for as long as its window is open, and at
125/// no cost when it is not.
126fn monitor(desk: &mut Desk, ui: &mut Ui) {
127    // (Where the line stands goes by tenths of a second: between two of them it is the
128    // same line, and nothing of it is drawn again.)
129    let along = (desk.up.as_millis() / 100) as f32 * 0.3;
130    let load: Vec<f32> = (0..64).map(|step| ((step as f32 * 0.2 + along).sin() * 0.35 + (step as f32 * 0.07 + along * 0.4).cos() * 0.25 + 0.5).clamp(0.0, 1.0)).collect();
131    ui.plot_lines(&load, 296.0, 96.0);
132    ui.progress(*load.last().unwrap_or(&0.0));
133    ui.note("Drawn ten times a second while this window is open.");
134    ui.wake_after(Duration::from_millis(100));
135}
136
137fn settings(desk: &mut Desk, ui: &mut Ui) {
138    ui.switch(&mut desk.light, "Light colours");
139    ui.segmented(&mut desk.tint, &TINTS.map(|(name, _)| name));
140    ui.note("The whole screen takes these at once.");
141}
142
143/// The desktop in a window of the system this is run on: the window stands for the screen,
144/// and the system draws the pointer.
145fn in_a_window(mut desk: Desk) {
146    let started = Instant::now();
147    let screen = Window { title: "taut desktop", width: 1280.0, height: 720.0, min_width: 640.0, min_height: 400.0, ..Default::default() };
148    taut::run(screen, move |ui| {
149        desk.up = started.elapsed();
150        describe(&mut desk, ui);
151    });
152}
153
154/// A screen that is only a block of pixels, with the desktop on it: what a machine's own
155/// code would keep, to show on its display.
156struct Screen {
157    ui: Ui,
158    desk: Desk,
159    pixels: Surface,
160    /// Where the mouse is, and what the clock says.
161    mouse: Point,
162    clock: Duration,
163    /// Each time the desktop was described and drawn: how many pixels were drawn, and how
164    /// long both took.
165    steps: Vec<(f32, Duration)>,
166}
167
168impl Screen {
169    fn new(width: f32, height: f32) -> Screen {
170        // (A machine with no system of its own would bring a font file, `AppFonts`, or use the
171        // letters built in.)
172        let mut ui = Ui::new(taut::platform::system_text(), Box::new(LocalClipboard::default()));
173        ui.resize(Size { w: width, h: height }, 1.0);
174        // (What a screen reader would be told is how this session finds its way: where the
175        // button called "Start" is, where the window called "Notes".)
176        ui.set_screen_reader(true);
177        let pixels = Surface::draw(&mut ui, 64);
178        let mut screen = Screen { ui, desk: Desk { own_pointer: true, ..desk() }, pixels, mouse: pt(width / 2.0, height / 2.0), clock: Duration::ZERO, steps: Vec::new() };
179        screen.does(Event::Move(screen.mouse));
180        screen
181    }
182
183    /// Something happened: if the interface says that changes anything, the desktop is
184    /// described again and the part of the screen that differs is drawn again.
185    fn does(&mut self, event: Event) {
186        self.clock += Duration::from_millis(16);
187        self.ui.set_time(self.clock);
188        self.desk.up = self.clock;
189        let due = self.ui.wake_in() == Some(Duration::ZERO);
190        if !self.ui.event(event) && !due && !self.steps.is_empty() {
191            return;
192        }
193        let began = Instant::now();
194        self.ui.run(&mut |ui| describe(&mut self.desk, ui));
195        // Only the places that changed are drawn again: where the pointer was and where it
196        // is now, not everything between the two.
197        let places: Vec<taut::Rect> = self.ui.changes().collect();
198        for place in &places {
199            self.pixels.redraw(&mut self.ui, *place);
200        }
201        self.steps.push((places.iter().map(|place| place.w * place.h).sum(), began.elapsed()));
202    }
203
204    /// Where the thing of this kind that is called `name` lies on the screen.
205    fn find(&self, role: Role, name: &str) -> Point {
206        let node = self.ui.visible_access_nodes().iter().find(|node| node.role == role && node.name == name).unwrap_or_else(|| panic!("nothing on the screen is called {name:?}"));
207        pt(node.rect.x + node.rect.w / 2.0, node.rect.y + node.rect.h / 2.0)
208    }
209
210    /// Takes the mouse to a place, in a dozen steps as a hand would.
211    fn mouse_to(&mut self, to: Point) {
212        let from = self.mouse;
213        for step in 1..=12 {
214            let along = step as f32 / 12.0;
215            self.does(Event::Move(pt((from.x + (to.x - from.x) * along).round(), (from.y + (to.y - from.y) * along).round())));
216        }
217        self.mouse = to;
218    }
219    fn click(&mut self, at: Point) {
220        self.mouse_to(at);
221        self.does(Event::Press(Button::Left, Mods::NONE));
222        self.does(Event::Release(Button::Left));
223    }
224    /// Presses at one place, takes the mouse to another, and lets go there.
225    fn drag(&mut self, from: Point, to: Point) {
226        self.mouse_to(from);
227        self.does(Event::Press(Button::Left, Mods::NONE));
228        self.mouse_to(to);
229        self.does(Event::Release(Button::Left));
230    }
231    /// Lets time pass, a sixtieth of a second at a time.
232    fn wait(&mut self, time: Duration) {
233        for _ in 0..time.as_millis() / 16 {
234            self.does(Event::Focused(true));
235        }
236    }
237    fn picture(&self, folder: &Path, name: &str) {
238        std::fs::write(folder.join(format!("{name}.png")), self.pixels.to_png()).unwrap_or_else(|why| panic!("{name}.png could not be written: {why}"));
239    }
240}
241
242/// Plays a short session on a screen that is only a block of pixels, writes pictures of it
243/// into `folder`, and says what it cost.
244fn play(folder: &Path) {
245    std::fs::create_dir_all(folder).expect("the folder for the pictures could not be made");
246    let mut screen = Screen::new(1280.0, 720.0);
247    screen.picture(folder, "1-started");
248    // Start, then Notes in the menu that opens: the window comes up, and takes what is typed.
249    let start = screen.find(Role::Button, "Start");
250    screen.click(start);
251    screen.picture(folder, "2-launcher");
252    let notes = screen.find(Role::MenuItem, "Notes");
253    screen.click(notes);
254    let page = screen.find(Role::TextBox, "Write something");
255    screen.click(page);
256    for line in ["Drawn by one library,", "with no window system under it."] {
257        screen.does(Event::Text(line.into()));
258        screen.does(Event::Key(Key::Enter, Mods::NONE));
259    }
260    screen.picture(folder, "3-notes");
261    // The window is carried by its title, a little down and to the left.
262    let title = screen.find(Role::Group, "Notes");
263    let held = pt(title.x, title.y - 126.0);
264    screen.drag(held, pt(held.x - 150.0, held.y + 60.0));
265    // The monitor is opened from the bar, and left to run for a second; then the colours
266    // of everything are changed in the settings.
267    let monitor = screen.find(Role::CheckBox, "Monitor");
268    screen.click(monitor);
269    screen.wait(Duration::from_secs(1));
270    screen.picture(folder, "4-monitor");
271    let settings = screen.find(Role::CheckBox, "Settings");
272    screen.click(settings);
273    let light = screen.find(Role::Switch, "Light colours");
274    screen.click(light);
275    let green = screen.find(Role::Tab, "Green");
276    screen.click(green);
277    screen.wait(Duration::from_millis(300));
278    screen.picture(folder, "5-light");
279
280    // What was drawn piece by piece is what drawing all of it at once gives.
281    let afresh = Surface::draw(&mut screen.ui, 64);
282    assert!(afresh.pixels == screen.pixels.pixels, "drawing only what changed left the screen different from drawing all of it");
283    // What a step cost as a rule (the middle one of them all: a move of the mouse), and
284    // the dearest (all of the screen in other colours).
285    let (all, count) = ((screen.pixels.width * screen.pixels.height) as f32, screen.steps.len());
286    let share = |pixels: f32| pixels / all * 100.0;
287    let millionths = |time: Duration| time.as_secs_f64() * 1e6;
288    screen.steps.sort_by_key(|step| step.1);
289    let (usual, dearest) = (screen.steps[count / 2], screen.steps[count - 1]);
290    println!("the desktop was described and drawn {count} times");
291    println!("as a rule {:.2}% of the screen was drawn again, in {:.0} millionths of a second", share(usual.0), millionths(usual.1));
292    println!("at the most {:.0}% of it, in {:.0} millionths of a second", share(dearest.0), millionths(dearest.1));
293    println!("pictures are in {}", folder.display());
294}
295
296fn main() {
297    match std::env::args().skip_while(|arg| arg != "--frames").nth(1) {
298        Some(folder) => play(Path::new(&folder)),
299        None => in_a_window(desk()),
300    }
301}