#async-executor #future #gtk #promise #building-block #basic #gui

gtk-future-executor

使用 Gtk-rs 编写异步 GUI 代码的基本构建块

1 个不稳定版本

0.1.0 2019年5月31日

#1573 in 异步

MIT 许可证

18KB
149

此 crate 提供使用 Gtk-rs 编写异步 GUI 代码的基本构建块

  1. GtkEventLoopAsyncExecutor - 用于执行可能操作 GUI 小部件的 futures 的 executor
  2. Promise - 一个常用于 GUI 代码的 futures::Future 实现

Promise 是一个可以通过 resolvereject 方法完成或失败的 future。

Promise 对象可以自由克隆(所有克隆都指向相同的底层对象)并且是线程安全的。

Promise 对象非常适合将基于 Future 的代码与非基于 Future 的代码集成。

GtkEventLoopAsyncExecutor 是一个在 Gtk+ 主循环上执行 futures 的 executor。这允许执行操作 Gtk+ 小部件的异步代码。

使用

  1. 使用 GtkEventLoopAsyncExecutor::new() 创建
  2. 根据需要克隆(所有克隆都指向相同的 executor)
  3. 使用 GtkEventLoopAsyncExecutor::spawn() 启动新的异步 GUI 代码

GtkEventLoopAsyncExecutor 通过不可在线程之间共享或发送来确保内存和线程安全。这是 GUI 代码的要求。

示例

use futures::prelude::*;
use futures::future;
use futures_cpupool::CpuPool;

use gtk_future_executor::GtkEventLoopAsyncExecutor;
use gtk_future_executor::Promise;
use gtk::prelude::*;

// An examples that computes Fibonacci numbers in background

fn main() -> Result<(), String> {

    gtk::init().map_err(|_| "Failed to initialize Gtk+".to_string())?;

    // Constuct new executor
    let gtk_executor = GtkEventLoopAsyncExecutor::new();
    // This examples uses CPU pool for invoking long-running computation in background
    let cpu_pool = CpuPool::new_num_cpus();

    let fut_main = gui_main(cpu_pool.clone(), gtk_executor.clone())
        .then(|_| {
            // Exit main loop when gui_main() finishes
            gtk::main_quit();

            future::ok(())
        });

    // This executes the async main function inside Gtk+ event loop
    gtk_executor.spawn(fut_main);

    gtk::main();

    Result::Ok(())
}

// An async function that shows a window. Returned future will resolve when user closes the window.
fn gui_main(cpu_pool: CpuPool, gtk_executor: GtkEventLoopAsyncExecutor) -> impl Future<Item=(), Error=String> {

    let promise = Promise::new();

    let window = gtk::Window::new(gtk::WindowType::Toplevel);
    let vbox = gtk::Box::new(gtk::Orientation::Vertical, 5);
    let label = gtk::Label::new("Enter n:");
    let result_label = gtk::Label::new("<result>");
    let textbox = gtk::Entry::new();
    let button = gtk::Button::new_with_label("OK");

    window.add(&vbox);
    vbox.pack_start(&label, false, true, 0);
    vbox.pack_start(&textbox, false, true, 0);
    vbox.pack_start(&button, false, true, 0);
    vbox.pack_start(&result_label, false, true, 0);

    window.set_title("Fib");
    window.set_position(gtk::WindowPosition::Center);

    {
        let promise = promise.clone();
        window.connect_delete_event(move |_, _| {
            promise.resolve(());

            Inhibit(false)
        });
    }

    {
        let cpu_pool = cpu_pool.clone();
        let gtk_executor = gtk_executor.clone();
        let textbox = textbox.clone();
        let result_label = result_label.clone();
        button.connect_clicked(move |_| {

            let opt_text = textbox.get_text();
            let text = opt_text.as_ref().map(|s| s.as_str()).unwrap_or("");
            let n: u64 = match text.parse() {
                Ok(x) => x,
                Err(x) => {
                    eprintln!("Error: {}", x);
                    return;
                }
            };
            result_label.set_text("computing...");
            let result_label = result_label.clone();

            // With GtkEventLoopAsyncExecutor we can await the long running async computation
            // and continue manipulating GUI widgets on the main thread.
            gtk_executor.spawn(
                // cpu_pool execute `compute_fib` in background thread_pool
                cpu_pool.spawn_fn(move || future::ok(compute_fib(n)))
                    .and_then(move |r| {
                        // this code is executed on main thread
                        result_label.set_text(&format!("fib({}) = {}", n, r));

                        future::ok(())
                    })
            );
        });
    }

    window.show_all();

    promise
}

// Fibonacci function. This function will take very long time for large values of `n`.
fn compute_fib(n: u64) -> u64 {
    if n < 2 {
        1
    } else {
        compute_fib(n - 2) + compute_fib(n - 1)
    }
}

依赖关系

~13MB
~320K SLoC