Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix AsyncFileDialog blocking on Windows #191

Merged
merged 1 commit into from
May 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased
- Move from `objc` crates to `objc2` crates.
- Fix `AsyncFileDialog` blocking the executor on Windows (#191)

## 0.14.0
- i18n for GTK and XDG Portal
Expand Down
51 changes: 30 additions & 21 deletions src/backend/win_cid/thread_future.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,32 @@
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, TryLockError};

use std::task::{Context, Poll, Waker};

struct FutureState<R> {
waker: Option<Waker>,
data: Option<R>,
waker: Mutex<Option<Waker>>,
data: Mutex<Option<R>>,
}

unsafe impl<R> Send for FutureState<R> {}

pub struct ThreadFuture<R> {
state: Arc<Mutex<FutureState<R>>>,
state: Arc<FutureState<R>>,
}

unsafe impl<R> Send for ThreadFuture<R> {}

impl<R: 'static> ThreadFuture<R> {
impl<R: Send + 'static> ThreadFuture<R> {
pub fn new<F: FnOnce(&mut Option<R>) + Send + 'static>(f: F) -> Self {
let state = Arc::new(Mutex::new(FutureState {
waker: None,
data: None,
}));
let state = Arc::new(FutureState {
waker: Mutex::new(None),
data: Mutex::new(None),
});

{
let state = state.clone();
std::thread::spawn(move || {
let mut state = state.lock().unwrap();

f(&mut state.data);
f(&mut state.data.lock().unwrap());

if let Some(waker) = state.waker.take() {
if let Some(waker) = state.waker.lock().unwrap().take() {
waker.wake();
}
});
Expand All @@ -44,13 +40,26 @@ impl<R> std::future::Future for ThreadFuture<R> {
type Output = R;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = self.state.lock().unwrap();
let state = &self.state;
let data = state.data.try_lock();

if state.data.is_some() {
Poll::Ready(state.data.take().unwrap())
} else {
state.waker = Some(cx.waker().clone());
Poll::Pending
match data {
Ok(mut data) => {
match data.take() {
Some(data) => Poll::Ready(data),
None => {
*state.waker.lock().unwrap() = Some(cx.waker().clone());
Poll::Pending
}
}
}
Err(TryLockError::Poisoned(err)) => {
panic!("{}", err);
}
Err(TryLockError::WouldBlock) => {
*state.waker.lock().unwrap() = Some(cx.waker().clone());
Poll::Pending
}
}
}
}
Loading