Skip to main content

gpui/
native_profiling.rs

1//! Optional drawing-thread spans supplied by an embedding application.
2
3use std::{
4    cell::Cell,
5    marker::PhantomData,
6    panic::Location,
7    rc::Rc,
8    sync::{
9        RwLock,
10        atomic::{AtomicBool, Ordering},
11    },
12};
13
14use crate::PlatformWindow;
15use raw_window_handle::RawWindowHandle;
16
17thread_local! {
18    static CURRENT_TARGET: Cell<usize> = const { Cell::new(0) };
19}
20
21/// The target is an opaque native window key (HWND on Windows).
22/// The callbacks run on the drawing thread and must not invoke UI or JS code.
23#[derive(Clone, Copy)]
24pub struct FrameProfilerCallbacks {
25    /// Starts a span and returns zero when the target is not being recorded.
26    pub begin: fn(usize, &'static str, &'static str, &'static str, u32, u32) -> u64,
27    /// Ends a nonzero token on the same thread that started it.
28    pub end: fn(u64),
29}
30static ENABLED: AtomicBool = AtomicBool::new(false);
31static CALLBACKS: RwLock<Option<FrameProfilerCallbacks>> = RwLock::new(None);
32
33/// Installs or removes optional CPU span hooks without linking an embedder into GPUI.
34pub fn set_frame_profiler(callbacks: Option<FrameProfilerCallbacks>) {
35    ENABLED.store(false, Ordering::Relaxed);
36    let enabled = callbacks.is_some();
37    *CALLBACKS.write().unwrap_or_else(|error| error.into_inner()) = callbacks;
38    ENABLED.store(enabled, Ordering::Relaxed);
39}
40/// A drawing-thread span that ends when dropped.
41#[doc(hidden)]
42pub struct Span {
43    token: u64,
44    end: Option<fn(u64)>,
45    _thread: PhantomData<Rc<()>>,
46}
47impl Drop for Span {
48    fn drop(&mut self) {
49        if let Some(end) = self.end {
50            if self.token != 0 {
51                end(self.token);
52            }
53        }
54    }
55}
56#[track_caller]
57#[inline]
58#[doc(hidden)]
59pub fn span(target: usize, category: &'static str, name: &'static str) -> Span {
60    if !ENABLED.load(Ordering::Relaxed) {
61        return Span {
62            token: 0,
63            end: None,
64            _thread: PhantomData,
65        };
66    }
67    let callbacks = *CALLBACKS.read().unwrap_or_else(|error| error.into_inner());
68    let Some(callbacks) = callbacks else {
69        return Span {
70            token: 0,
71            end: None,
72            _thread: PhantomData,
73        };
74    };
75    let caller = Location::caller();
76    Span {
77        token: (callbacks.begin)(
78            target,
79            category,
80            name,
81            caller.file(),
82            caller.line(),
83            caller.column(),
84        ),
85        end: Some(callbacks.end),
86        _thread: PhantomData,
87    }
88}
89
90/// Starts a span for the window whose GPUI draw is active on this thread.
91/// Disabled hooks do not access thread-local state or read the clock.
92#[track_caller]
93#[inline]
94pub fn current_span(category: &'static str, name: &'static str) -> Span {
95    if !ENABLED.load(Ordering::Relaxed) {
96        return Span {
97            token: 0,
98            end: None,
99            _thread: PhantomData,
100        };
101    }
102    span(CURRENT_TARGET.with(Cell::get), category, name)
103}
104
105pub(crate) struct WindowScope {
106    previous: Option<usize>,
107    _thread: PhantomData<Rc<()>>,
108}
109
110impl Drop for WindowScope {
111    fn drop(&mut self) {
112        if let Some(previous) = self.previous {
113            CURRENT_TARGET.with(|target| target.set(previous));
114        }
115    }
116}
117
118fn target_scope(target: usize) -> WindowScope {
119    WindowScope {
120        previous: Some(CURRENT_TARGET.with(|current| current.replace(target))),
121        _thread: PhantomData,
122    }
123}
124
125#[inline]
126pub(crate) fn window_scope(window: &dyn PlatformWindow) -> WindowScope {
127    if !ENABLED.load(Ordering::Relaxed) {
128        return WindowScope {
129            previous: None,
130            _thread: PhantomData,
131        };
132    }
133    let target = match window.window_handle().ok().map(|handle| handle.as_raw()) {
134        Some(RawWindowHandle::Win32(handle)) => handle.hwnd.get() as usize,
135        _ => 0,
136    };
137    target_scope(target)
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use std::sync::Mutex;
144
145    static EVENTS: Mutex<Vec<(usize, &'static str)>> = Mutex::new(Vec::new());
146
147    fn begin(
148        target: usize,
149        _: &'static str,
150        name: &'static str,
151        _: &'static str,
152        _: u32,
153        _: u32,
154    ) -> u64 {
155        EVENTS.lock().unwrap().push((target, name));
156        target as u64
157    }
158
159    fn end(token: u64) {
160        EVENTS.lock().unwrap().push((token as usize, "end"));
161    }
162
163    #[test]
164    fn spans_follow_nested_window_scopes_and_ignore_disabled_or_zero_tokens() {
165        set_frame_profiler(None);
166        EVENTS.lock().unwrap().clear();
167        drop(current_span("native", "disabled"));
168        assert!(EVENTS.lock().unwrap().is_empty());
169
170        set_frame_profiler(Some(FrameProfilerCallbacks { begin, end }));
171        {
172            let _outer = target_scope(11);
173            drop(current_span("native", "outer"));
174            {
175                let _inner = target_scope(22);
176                drop(current_span("native", "inner"));
177            }
178            drop(current_span("native", "restored"));
179        }
180        drop(current_span("native", "outside"));
181        set_frame_profiler(None);
182        assert_eq!(
183            *EVENTS.lock().unwrap(),
184            vec![
185                (11, "outer"),
186                (11, "end"),
187                (22, "inner"),
188                (22, "end"),
189                (11, "restored"),
190                (11, "end"),
191                (0, "outside"),
192            ]
193        );
194    }
195}