返回首页

winit::user_event学习笔记

在 Rust 的 winit 库中,user_event(自定义用户事件)是一个用于跨线程通信和唤醒主事件循环的核心机制。

winit 的 EventLoop(事件循环)通常运行在主线程上,并且会阻塞当前线程以等待操作系统的原生事件(如鼠标点击、窗口拖动等)。如果你的程序有后台线程(例如处理网络请求、音频播放、或繁重的物理计算),这些后台线程在完成任务后需要通知主线程去更新窗口或渲染 UI。user_event 就是为了解决这个“后台线程向主线程发消息”的需求而设计的。我的EventLoopProxy就涉及到如何对其封装和使用。

核心组件与运作流程

使用自定义事件通常涉及以下几个关键部分:

  1. 自定义事件类型 (T):通常是一个 enum,定义你需要传递的数据。

    我这里呢自定义了一个UserEvent

    enum UserEvent {
        Loop(EventLoopRequest),//   发给循环
        Window(WindowTask),//   发给窗口,执行时要提供窗口引用
    }
    

    Loop 和 Window 的意思是:GUI 执行这项请求时,需不需要提供一个目标窗口。 两者都走同一个 winit 事件循环,也都在同一个 GUI 线程处理。

  2. 带类型的事件循环 (EventLoop<T>):在创建 EventLoop 时,声明它将处理哪种类型的自定义事件。

    这里我定义了一个PendingLoop

    struct PendingLoop {
        event_loop: EventLoop<UserEvent>, //带类型的事件循环
        window: Option<RegisteredWindow<'static>>, //已注册的窗口
    }
    

    PendingLoop 是 WinitPlatform 在事件循环启动前用来保存两样东西的:一个已经创建、但还没运行的 winit 循环,以及一个可选的逻辑窗口。它自己不处理事件。 为什么这么设计?是为了把注册窗口和启动循环两步拆开,后端得有地方保存注册结果。

    为什么要分两步呢?调用方能先拿到逻辑窗口句柄,用它设置标题、取得弱句柄,然后再把主线程交给事件循环。

  3. 事件代理 (EventLoopProxy<T>):从 EventLoop 中克隆出来的发送器。它实现了 Clone 和 Send,可以被安全地传递到任意后台线程。 我是在winitplatform::new的时候创建的原生发送器

    impl WinitPlatform {
        pub fn new() -> Result<Self, PlatformError> {
            let native = NativeLoop::with_user_event()
                .build()
                .map_err(|error| PlatformError::EventLoopInitFailed(Box::new(error)))?;
            Ok(Self {
                proxy: native.create_proxy(), //创建发送器
                pending: RefCell::new(Some(PendingLoop {
                    event_loop: native,
                    window: None,
                })),
            })
        }
    }
    

    在上层调用event_loop_proxy时clone一个

    fn event_loop_proxy(&self) -> EventLoopProxy {
            let proxy = self.proxy.clone(); //clone
            EventLoopProxy::new(move |request| {
                proxy
                    .send_event(UserEvent::Loop(request))
                    .map_err(|_closed| EventLoopClosed)
            })
        }
    

    在EventLoopProxy调用invoke时,将invoke内的闭包函数封装进EventLoopRequest的Invoke(Box<dyn FnOnce() + Send>)中,Box<dyn FnOnce() + Send>也就是task,然后再把这一层给封装进UserEvent::Loop中,通过send_event发送给user_event

    以下是EventLoopProxy的实现

    pub struct EventLoopProxy {
        send: Box<dyn Fn(EventLoopRequest) -> Result<(), EventLoopClosed> + Send>,
    }
    
    impl EventLoopProxy {
        pub fn new(
            send: impl Fn(EventLoopRequest) -> Result<(), EventLoopClosed> + Send + 'static,
        ) -> Self {
            Self {
                send: Box::new(send),
            }
        }
    
        pub fn invoke(&self, task: impl FnOnce() + Send + 'static) -> Result<(), EventLoopClosed> {
            (self.send)(EventLoopRequest::Invoke(Box::new(task)))
        }
    
        pub fn invoke_with_window(
            &self,
            task: impl FnOnce(&dyn WindowAdapter) + Send + 'static,
        ) -> Result<(), EventLoopClosed> {
            (self.send)(EventLoopRequest::InvokeWithWindow(Box::new(task)))
        }
    
        pub fn quit(&self) -> Result<(), EventLoopClosed> {
            (self.send)(EventLoopRequest::Quit)
        }
    }
    
  4. 事件处理回调:在主线程的事件循环中捕获并处理这些自定义事件。

    fn user_event(&mut self, event_loop: &ActiveEventLoop, request: EventLoopRequest) {
            if event_loop.exiting() {
                return;
            }
            match request {
                EventLoopRequest::Invoke(task) => task(),
                EventLoopRequest::Quit => event_loop.exit(),
                EventLoopRequest::InvokeWithWindow(task) => {
                    if let Some(window) = &self.window {
                        task(window.adapter.as_ref());
                    }
                }
            }
        }
    

评论0

还没有评论,说点什么吧。