use std::{
cell::{Cell, RefCell},
collections::VecDeque,
rc::Rc,
};
use crate::{
AnyWindowHandle, App, AppContext as _, AsyncApp, DispatchEventResult, PlatformInput,
PlatformWindow, Window, WindowControlArea,
};
thread_local! {
static FRAMES_WAITING: RefCell<Vec<AnyWindowHandle>> = const { RefCell::new(Vec::new()) };
}
pub(crate) fn defer_frame_request(handle: AnyWindowHandle, cx: &AsyncApp) -> bool {
if crate::window::draw_in_progress() {
return true;
}
if app_is_free(cx) {
return false;
}
log::debug!(
"deferring frame request for window {:?} made while the app is borrowed",
handle.window_id()
);
let waiting = FRAMES_WAITING.with_borrow_mut(|frames| {
let waiting = frames.contains(&handle);
if !waiting {
frames.push(handle);
}
waiting
});
if !waiting {
refresh_when_free(handle, cx.clone());
}
true
}
fn refresh_when_free(handle: AnyWindowHandle, cx: AsyncApp) {
cx.foreground_executor()
.clone()
.spawn(async move {
if cx.app.strong_count() != 0 && !app_is_free(&cx) {
refresh_when_free(handle, cx);
return;
}
FRAMES_WAITING.with_borrow_mut(|frames| frames.retain(|waiting| *waiting != handle));
if cx.app.strong_count() != 0 {
let _ = cx
.clone()
.update_window(handle, |_, window, _| window.refresh());
}
})
.detach();
}
fn app_is_free(cx: &AsyncApp) -> bool {
cx.app
.upgrade()
.is_none_or(|app| app.try_borrow_mut().is_ok())
}
#[derive(Default)]
struct Pending {
bounds_changed: bool,
display_changed: bool,
input: VecDeque<PlatformInput>,
}
impl Pending {
fn is_empty(&self) -> bool {
!self.bounds_changed && !self.display_changed && self.input.is_empty()
}
}
struct ReentrantWindowCallbacks {
handle: AnyWindowHandle,
cx: AsyncApp,
pending: RefCell<Pending>,
retry_scheduled: Cell<bool>,
}
pub(crate) fn register(
platform_window: &dyn PlatformWindow,
handle: AnyWindowHandle,
cx: AsyncApp,
) {
let this = Rc::new(ReentrantWindowCallbacks {
handle,
cx,
pending: RefCell::default(),
retry_scheduled: Cell::new(false),
});
platform_window.on_resize(Box::new({
let this = this.clone();
move |_, _| ReentrantWindowCallbacks::bounds_changed(&this)
}));
platform_window.on_moved(Box::new({
let this = this.clone();
move || ReentrantWindowCallbacks::bounds_changed(&this)
}));
platform_window.on_display_changed(Box::new({
let this = this.clone();
move || ReentrantWindowCallbacks::display_changed(&this)
}));
platform_window.on_input(Box::new({
let this = this.clone();
move |event| ReentrantWindowCallbacks::input(&this, event)
}));
platform_window.on_hit_test_window_control(Box::new(move || {
ReentrantWindowCallbacks::hit_test_window_control(&this)
}));
}
impl ReentrantWindowCallbacks {
fn app_is_free(&self) -> bool {
app_is_free(&self.cx)
}
fn bounds_changed(this: &Rc<Self>) {
if this.defer(|pending| pending.bounds_changed = true) {
return;
}
this.update_window("handling bounds change", |window, cx| {
window.bounds_changed(cx)
});
}
fn display_changed(this: &Rc<Self>) {
if this.defer(|pending| pending.display_changed = true) {
return;
}
this.run_display_changed();
}
fn input(this: &Rc<Self>, event: PlatformInput) -> DispatchEventResult {
let mut event = Some(event);
if this.defer(|pending| pending.input.extend(event.take())) {
log::debug!(
"deferring input for window {:?} dispatched while the app is borrowed",
this.handle.window_id()
);
return DispatchEventResult::default();
}
let event = event.expect("event is only taken when deferred");
this.update_window("dispatching input", |window, cx| {
window.dispatch_event(event, cx)
})
.unwrap_or_default()
}
fn hit_test_window_control(this: &Rc<Self>) -> Option<WindowControlArea> {
if !this.app_is_free() {
return None;
}
this.update_window("hit-testing window controls", |window, _| {
window
.rendered_frame
.window_control_hitboxes
.iter()
.find(|(_, hitbox)| window.mouse_hit_test.ids.contains(&hitbox.id))
.map(|(area, _)| *area)
})
.flatten()
}
fn defer(self: &Rc<Self>, record: impl FnOnce(&mut Pending)) -> bool {
if !self.app_is_free() {
record(&mut self.pending.borrow_mut());
self.schedule_retry();
return true;
}
if self.pending.borrow().is_empty() {
return false;
}
record(&mut self.pending.borrow_mut());
self.deliver_pending();
true
}
fn deliver_pending(self: &Rc<Self>) {
loop {
if !self.app_is_free() {
self.schedule_retry();
return;
}
let mut pending = self.pending.borrow_mut();
if std::mem::take(&mut pending.bounds_changed) {
drop(pending);
self.update_window("handling bounds change", |window, cx| {
window.bounds_changed(cx)
});
} else if std::mem::take(&mut pending.display_changed) {
drop(pending);
self.run_display_changed();
} else if let Some(event) = pending.input.pop_front() {
drop(pending);
self.update_window("dispatching input", |window, cx| {
window.dispatch_event(event, cx);
});
} else {
return;
}
}
}
fn schedule_retry(self: &Rc<Self>) {
if self.retry_scheduled.replace(true) {
return;
}
let this = self.clone();
self.cx
.foreground_executor()
.spawn(async move {
this.retry_scheduled.set(false);
if this.cx.app.strong_count() == 0 {
return;
}
this.deliver_pending();
})
.detach();
}
fn run_display_changed(&self) {
if self.cx.app.strong_count() == 0 {
return;
}
let handle = self.handle;
self.cx
.update(|cx: &mut App| Window::display_changed(handle, cx));
}
fn update_window<R>(
&self,
what: &str,
update: impl FnOnce(&mut Window, &mut App) -> R,
) -> Option<R> {
let mut cx = self.cx.clone();
let result = cx.update_window(self.handle, |_, window, cx| update(window, cx));
if let Err(error) = &result {
log::error!("{what} for window {:?}: {error:#}", self.handle.window_id());
}
result.ok()
}
}