freya-performance-plugin 0.5.0-rc.1

Icons library for Freya.
Documentation
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
use std::{
    collections::HashMap,
    time::{
        Duration,
        Instant,
    },
};

use freya_core::prelude::{
    ModifiersExt,
    UserEvent,
};
use freya_engine::prelude::{
    Color,
    FontStyle,
    Paint,
    PaintStyle,
    ParagraphBuilder,
    ParagraphStyle,
    Rect,
    Slant,
    TextShadow,
    TextStyle,
    Weight,
    Width,
};
use freya_winit::{
    plugins::{
        FreyaPlugin,
        Key,
        Modifiers,
        PluginEvent,
        PluginHandle,
    },
    reexports::winit::window::WindowId,
    renderer::{
        NativeEvent,
        NativeWindowEvent,
        NativeWindowEventAction,
    },
};

/// Performance overlay plugin that displays FPS, timing metrics, and other
/// diagnostics on top of the rendered frame. Hidden by default, toggle with
/// Ctrl+Shift+P (Cmd+Shift+P on macOS).
pub struct PerformanceOverlayPlugin {
    enabled: bool,
    toggle_shortcut: (Key, Modifiers),
    metrics: HashMap<WindowId, WindowMetrics>,
}

impl Default for PerformanceOverlayPlugin {
    fn default() -> Self {
        Self {
            enabled: false,
            toggle_shortcut: (
                Key::Character("p".into()),
                Modifiers::ctrl_or_meta() | Modifiers::SHIFT,
            ),
            metrics: HashMap::new(),
        }
    }
}

#[derive(Default)]
struct WindowMetrics {
    graphics_driver: &'static str,
    gpu_name: Option<String>,

    frames: Vec<Instant>,
    fps_historic: Vec<usize>,
    max_fps: usize,

    started_render: Option<Instant>,

    started_layout: Option<Instant>,
    finished_layout: Option<Duration>,

    started_tree_updates: Option<Instant>,
    finished_tree_updates: Option<Duration>,

    started_tasks_poll: Option<Instant>,
    tasks_poll_time: Duration,

    started_accessibility_updates: Option<Instant>,
    finished_accessibility_updates: Option<Duration>,

    started_presenting: Option<Instant>,
    finished_presenting: Option<Duration>,
}

impl PerformanceOverlayPlugin {
    /// Set the keyboard shortcut that toggles the overlay visibility.
    pub fn with_toggle_shortcut(mut self, key: Key, modifiers: Modifiers) -> Self {
        self.toggle_shortcut = (key, modifiers);
        self
    }

    /// Set whether the overlay is visible by default.
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.enabled = visible;
        self
    }

    fn get_metrics(&mut self, id: WindowId) -> &mut WindowMetrics {
        self.metrics.entry(id).or_default()
    }
}

impl FreyaPlugin for PerformanceOverlayPlugin {
    fn plugin_id(&self) -> &'static str {
        "freya-performance-overlay"
    }

    fn on_event(&mut self, event: &mut PluginEvent, handle: PluginHandle) {
        match event {
            PluginEvent::KeyboardInput {
                window,
                key,
                modifiers,
                is_pressed,
                ..
            } => {
                let (shortcut_key, shortcut_modifiers) = &self.toggle_shortcut;
                let key_matches = match (key, shortcut_key) {
                    (Key::Character(a), Key::Character(b)) => a.eq_ignore_ascii_case(b),
                    (a, b) => a == b,
                };
                if *is_pressed && *modifiers == *shortcut_modifiers && key_matches {
                    self.enabled = !self.enabled;
                    handle.send_event_loop_event(NativeEvent::Window(NativeWindowEvent {
                        window_id: window.id(),
                        action: NativeWindowEventAction::User(UserEvent::RequestRedraw),
                    }));
                }
            }
            PluginEvent::WindowCreated {
                window,
                graphics_driver,
                gpu_name,
                ..
            }
            | PluginEvent::GraphicsDriverChanged {
                window,
                graphics_driver,
                gpu_name,
            } => {
                let metrics = self.get_metrics(window.id());
                metrics.graphics_driver = graphics_driver;
                metrics.gpu_name = gpu_name.map(str::to_string);
            }
            PluginEvent::AfterRedraw { window, .. } => {
                let metrics = self.get_metrics(window.id());
                let now = Instant::now();

                metrics
                    .frames
                    .retain(|frame| now.duration_since(*frame).as_millis() < 1000);

                metrics.frames.push(now);

                // Accumulated across the frame, so it needs a reset
                metrics.tasks_poll_time = Duration::ZERO;
            }
            PluginEvent::BeforePresenting { window, .. } => {
                self.get_metrics(window.id()).started_presenting = Some(Instant::now())
            }
            PluginEvent::AfterPresenting { window, .. } => {
                let metrics = self.get_metrics(window.id());
                metrics.finished_presenting = Some(metrics.started_presenting.unwrap().elapsed())
            }
            PluginEvent::StartedMeasuringLayout { window, .. } => {
                self.get_metrics(window.id()).started_layout = Some(Instant::now())
            }
            PluginEvent::FinishedMeasuringLayout { window, .. } => {
                let metrics = self.get_metrics(window.id());
                metrics.finished_layout = Some(metrics.started_layout.unwrap().elapsed())
            }
            PluginEvent::StartedUpdatingTree { window, .. } => {
                self.get_metrics(window.id()).started_tree_updates = Some(Instant::now())
            }
            PluginEvent::FinishedUpdatingTree { window, .. } => {
                let metrics = self.get_metrics(window.id());
                metrics.finished_tree_updates =
                    Some(metrics.started_tree_updates.unwrap().elapsed())
            }
            PluginEvent::StartedPollingTasks { window, .. } => {
                self.get_metrics(window.id()).started_tasks_poll = Some(Instant::now())
            }
            PluginEvent::FinishedPollingTasks { window, .. } => {
                let metrics = self.get_metrics(window.id());
                if let Some(started) = metrics.started_tasks_poll.take() {
                    metrics.tasks_poll_time += started.elapsed();
                }
                if self.enabled {
                    handle.send_event_loop_event(NativeEvent::Window(NativeWindowEvent {
                        window_id: window.id(),
                        action: NativeWindowEventAction::User(UserEvent::RequestRedraw),
                    }));
                }
            }
            PluginEvent::BeforeAccessibility { window, .. } => {
                self.get_metrics(window.id()).started_accessibility_updates = Some(Instant::now())
            }
            PluginEvent::AfterAccessibility { window, .. } => {
                let metrics = self.get_metrics(window.id());
                metrics.finished_accessibility_updates =
                    Some(metrics.started_accessibility_updates.unwrap().elapsed())
            }
            PluginEvent::BeforeRender { window, .. } => {
                self.get_metrics(window.id()).started_render = Some(Instant::now())
            }
            PluginEvent::AfterRender {
                window,
                canvas,
                font_collection,
                tree,
                animation_clock,
            } => {
                if !self.enabled {
                    return;
                }
                let metrics = self.get_metrics(window.id());
                let scale_factor = window.scale_factor() as f32;
                let started_render = metrics.started_render.take().unwrap();

                canvas.save();
                canvas.scale((scale_factor, scale_factor));

                let finished_render = started_render.elapsed();
                let finished_presenting = metrics.finished_presenting.unwrap_or_default();
                let finished_layout = metrics.finished_layout.unwrap();
                let finished_tree_updates = metrics.finished_tree_updates.unwrap_or_default();
                let tasks_poll_time = metrics.tasks_poll_time;
                let finished_accessibility_updates =
                    metrics.finished_accessibility_updates.unwrap_or_default();

                // Render the texts
                let mut paragraph_builder =
                    ParagraphBuilder::new(&ParagraphStyle::default(), *font_collection);
                let mut text_style = TextStyle::default();
                text_style.set_color(Color::from_rgb(63, 255, 0));
                text_style.add_shadow(TextShadow::new(
                    Color::from_rgb(60, 60, 60),
                    (0.0, 1.0),
                    1.0,
                ));
                paragraph_builder.push_style(&text_style);

                // FPS
                add_text(
                    &mut paragraph_builder,
                    format!("{} FPS\n", metrics.frames.len()),
                    30.0,
                );

                metrics.fps_historic.push(metrics.frames.len());
                if metrics.fps_historic.len() > 70 {
                    metrics.fps_historic.remove(0);
                }

                // Rendering time
                add_text(
                    &mut paragraph_builder,
                    format!(
                        "Rendering: {:.3}ms \n",
                        finished_render.as_secs_f64() * 1000.0
                    ),
                    18.0,
                );

                // Presenting time
                add_text(
                    &mut paragraph_builder,
                    format!(
                        "Presenting: {:.3}ms \n",
                        finished_presenting.as_secs_f64() * 1000.0
                    ),
                    18.0,
                );

                // Layout time
                add_text(
                    &mut paragraph_builder,
                    format!("Layout: {:.3}ms \n", finished_layout.as_secs_f64() * 1000.0),
                    18.0,
                );

                // Tree updates time
                add_text(
                    &mut paragraph_builder,
                    format!(
                        "Tree Updates: {:.3}ms \n",
                        finished_tree_updates.as_secs_f64() * 1000.0
                    ),
                    18.0,
                );

                // a11y updates time
                add_text(
                    &mut paragraph_builder,
                    format!(
                        "a11y Updates: {:.3}ms \n",
                        finished_accessibility_updates.as_secs_f64() * 1000.0
                    ),
                    18.0,
                );

                // Async tasks polling time
                add_text(
                    &mut paragraph_builder,
                    format!("Tasks: {:.3}ms \n", tasks_poll_time.as_secs_f64() * 1000.0),
                    18.0,
                );

                // Tree size
                add_text(
                    &mut paragraph_builder,
                    format!("{} Tree Nodes \n", tree.size()),
                    14.0,
                );

                // Layout size
                add_text(
                    &mut paragraph_builder,
                    format!("{} Layout Nodes \n", tree.layout.size()),
                    14.0,
                );

                // Scale Factor
                add_text(
                    &mut paragraph_builder,
                    format!("Scale Factor: {}x\n", window.scale_factor()),
                    14.0,
                );

                // TODO: Also track events measurement

                // Animation clock speed
                add_text(
                    &mut paragraph_builder,
                    format!("Animation clock speed: {}x \n", animation_clock.speed()),
                    14.0,
                );

                // Graphics driver
                add_text(
                    &mut paragraph_builder,
                    format!("Graphics: {} \n", metrics.graphics_driver),
                    14.0,
                );

                // Picked GPU
                if let Some(gpu_name) = &metrics.gpu_name {
                    add_text(&mut paragraph_builder, format!("GPU: {gpu_name} \n"), 14.0);
                }

                let mut paragraph = paragraph_builder.build();
                paragraph.layout(235.0);

                metrics.max_fps = metrics.max_fps.max(
                    metrics
                        .fps_historic
                        .iter()
                        .max()
                        .copied()
                        .unwrap_or_default(),
                );

                let start_x = 5.0;
                let start_y = paragraph.height() + 20.0 + metrics.max_fps.max(60) as f32;

                let mut paint = Paint::default();
                paint.set_anti_alias(true);
                paint.set_style(PaintStyle::Fill);
                paint.set_color(Color::from_argb(225, 225, 225, 225));
                canvas.draw_rect(Rect::new(5., 5., 245.0, start_y + 15.0), &paint);

                paragraph.paint(canvas, (5.0, 0.0));

                for (i, fps) in metrics.fps_historic.iter().enumerate() {
                    let mut paint = Paint::default();
                    paint.set_anti_alias(true);
                    paint.set_style(PaintStyle::Fill);
                    paint.set_color(Color::from_rgb(63, 255, 0));
                    paint.set_stroke_width(3.0);

                    let x = start_x + (i * 2) as f32;
                    let y = start_y - *fps as f32 + 2.0;
                    canvas.draw_circle((x, y), 2.0, &paint);
                }

                canvas.restore();
            }
            _ => {}
        }
    }
}

fn add_text(paragraph_builder: &mut ParagraphBuilder, text: String, font_size: f32) {
    let mut text_style = TextStyle::default();
    text_style.set_color(Color::from_rgb(25, 225, 35));
    let font_style = FontStyle::new(Weight::BOLD, Width::EXPANDED, Slant::Upright);
    text_style.set_font_style(font_style);
    text_style.add_shadow(TextShadow::new(
        Color::from_rgb(65, 65, 65),
        (0.0, 1.0),
        1.0,
    ));
    text_style.set_font_size(font_size);
    paragraph_builder.push_style(&text_style);
    paragraph_builder.add_text(text);
}