PolyMeilex / rfd

Rusty File Dialog
MIT License
524 stars 60 forks source link

Opening a dialog hangs when GTK window is open #198

Open rhysd opened 1 month ago

rhysd commented 1 month ago

I'm trying to use this crate with tao; GTK fork of winit. Since GTK is already in dependencies, using gtk3 feature of this crate can avoid many dependencies (e.g. async runtime). So I added it in my Cargo.toml:

rfd = { version = "0.14.1", default-features = false, features = ["gtk3"] }
tao = "0.28.0"

However, when calling rfd::FileDialog::pick_files after opening a GTK window, the method call hung forever and eventually OS suggested to kill the application process.

Here is a reproduction. This code opens one window. Once the window is initialized, it tries to open a file dialog with FileDialog::piick_files. Expected behavior is that a file dialog opens successfully and the window can continue to work after closing the dialog. The actual behavior was that it hung forever.

use tao::{
    event::{Event, WindowEvent, StartCause},
    event_loop::{ControlFlow, EventLoop},
    window::WindowBuilder,
};

fn open_dialog() {
    let res = rfd::FileDialog::new()
        .add_filter("text", &["txt", "rs"])
        .add_filter("rust", &["rs", "toml"])
        .set_directory(".")
        .pick_files();
    println!("The user choose: {:#?}", res);
}

fn main() {
    let event_loop = EventLoop::new();

    let mut window = Some(
        WindowBuilder::new()
            .with_title("A fantastic window!")
            .with_inner_size(tao::dpi::LogicalSize::new(300.0, 300.0))
            .with_min_inner_size(tao::dpi::LogicalSize::new(200.0, 200.0))
            .build(&event_loop)
            .unwrap(),
    );

    event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Wait;

        match event {
        Event::WindowEvent {
            event: WindowEvent::CloseRequested,
            window_id: _,
            ..
        } => {
            // drop the window to fire the `Destroyed` event
            window = None;
        }
        Event::WindowEvent {
            event: WindowEvent::Destroyed,
            window_id: _,
            ..
        } => {
            *control_flow = ControlFlow::Exit;
        }
        Event::MainEventsCleared => {
            if let Some(w) = &window {
                w.request_redraw();
            }
        }
        Event::NewEvents(StartCause::Init) => {
            println!("opening dialog");
            open_dialog();
        }
        _ => (),
        }
    });
}

I'm not familiar with GTK's architecture, but it seems that gtk3 feature of this crate does not work when GTK main thread (or main loop) is already initialized and used by someone else. When using xdg-portal feature, this issue doesn't occur.

Environment:

valadaptive commented 3 weeks ago

This is my fault and also GTK's fault--see https://github.com/PolyMeilex/rfd/pull/152.

GTK can only be used from the thread that it was initialized on. AFAIK, there's no way to get this thread and tell it to do things if we didn't initialize it ourselves. There's a quote from an old version of the GTK documentation that doesn't seem to be online anymore, but you can still find references to this snippet floating around:

GTK+, however, is not thread safe. You should only use GTK+ and GDK from the thread gtk_init() and gtk_main() were called on. This is usually referred to as the "main thread".

I'm not sure how this can be fixed without some sort of cross-crate effort to share the GTK+ main thread.