everything_plugin/ui/
winio.rs

1//! ## Design
2//! Embedding: https://github.com/compio-rs/winio/issues/24
3//!
4//! Dynamic component management: https://github.com/compio-rs/winio/issues/28
5
6use std::mem;
7
8use futures_channel::mpsc;
9use futures_util::StreamExt;
10use tracing::debug;
11use windows_sys::Win32::{Foundation::HWND, UI::WindowsAndMessaging::WS_OVERLAPPEDWINDOW};
12
13use crate::ui::{OptionsPageInternalMessage, OptionsPageLoadArgs, PageHandle};
14
15pub use winio;
16
17pub mod prelude {
18    pub use super::{super::OptionsPageMessage, OptionsPageInit};
19    pub use crate::PluginApp;
20    pub use winio::prelude::*;
21}
22use prelude::*;
23
24pub trait OptionsPageComponent<'a>:
25    Component<
26        Init<'a> = OptionsPageInit<'a, Self::App>,
27        Message: From<OptionsPageMessage<Self::App>>,
28    > + 'static
29{
30    type App: PluginApp;
31}
32
33impl<'a, T, A: PluginApp> OptionsPageComponent<'a> for T
34where
35    T: Component<Init<'a> = OptionsPageInit<'a, A>, Message: From<OptionsPageMessage<A>>> + 'static,
36{
37    type App = A;
38}
39
40pub fn spawn<'a, T: OptionsPageComponent<'a>>(args: OptionsPageLoadArgs) -> PageHandle<T::App> {
41    // *c_void, HWND: !Send
42    let parent: usize = unsafe { mem::transmute(args.parent) };
43
44    let (tx, rx) = mpsc::unbounded();
45    let thread_handle = std::thread::spawn(move || {
46        let parent: HWND = unsafe { mem::transmute(parent) };
47        run::<T>(OptionsPageInit {
48            parent: unsafe { BorrowedWindow::borrow_raw(RawWindow::Win32(parent)) }.into(),
49            rx: Some(rx),
50        });
51        // widgets::main(page_hwnd)
52    });
53    PageHandle { thread_handle, tx }
54}
55
56pub fn run<'a, T: OptionsPageComponent<'a>>(init: OptionsPageInit<'a, T::App>) -> T::Event {
57    // The name is only used on Qt and GTK
58    // https://github.com/compio-rs/winio/commit/f25828cc80fc5a39e188e7ed1c158f53ea9b5d56
59    App::new("").run::<T>(init)
60}
61
62pub struct OptionsPageInit<'a, A: PluginApp> {
63    /// `MaybeBorrowedWindow`: !Clone
64    parent: Option<BorrowedWindow<'a>>,
65
66    /// Workaround for listening to external messages.
67    ///
68    /// A new channel is used instead of [`ComponentSender<T>`] to erase the type and keep dyn compatible.
69    rx: Option<mpsc::UnboundedReceiver<OptionsPageInternalMessage<A>>>,
70}
71
72impl<'a, A: PluginApp> From<()> for OptionsPageInit<'a, A> {
73    fn from(_: ()) -> Self {
74        Self {
75            parent: None,
76            rx: None,
77        }
78    }
79}
80
81impl<'a, A: PluginApp> OptionsPageInit<'a, A> {
82    /// Do not call `set_size()` after calling this in `init()`, otherwise the initial size will be overridden.
83    pub fn window<T: OptionsPageComponent<'a, App = A>>(
84        &mut self,
85        sender: &ComponentSender<T>,
86    ) -> Child<Window> {
87        let mut window = Child::<Window>::init(self.parent.clone());
88        self.init(&mut window, sender);
89        window
90    }
91
92    /// Do not call `set_size()` after calling this in `init()`, otherwise the initial size will be overridden.
93    pub fn init<T: OptionsPageComponent<'a, App = A>>(
94        &mut self,
95        window: &mut Window,
96        sender: &ComponentSender<T>,
97    ) {
98        // Put before spawn to avoid unnecessary runtime check
99        adjust_window(window);
100
101        if let Some(mut rx) = self.rx.take() {
102            let window = window.as_raw_window();
103            let sender = sender.clone();
104            winio::compio::runtime::spawn(async move {
105                // We cannot defer initial size setting because `set_size()` will run this task many times
106                // See https://github.com/compio-rs/compio/issues/459
107                while let Some(m) = rx.next().await {
108                    if let Some(m) = m.try_into(window.as_win32()) {
109                        debug!(?m, "Options page message");
110                        sender.post(m.into());
111                    }
112                }
113                debug!("Options page message channel closed");
114            })
115            .detach();
116        }
117    }
118}
119
120/// Adjust a window to be used in an options page.
121///
122/// Should be called in [`Component::init`] for the window.
123pub fn adjust_window(window: &mut Window) {
124    // Btw, if `window` is Window instead of &mut:
125    // error[E0502]: cannot borrow `window` as immutable because it is also borrowed as mutable
126    window.set_style(window.style() & !WS_OVERLAPPEDWINDOW);
127
128    // TODO: Transparent background / background color
129
130    // Mitigate the occasional misplacement bug.
131    // It can be stably reproduced by enabling `tracing-appender` and blocking the console.
132    // The root cause is still unclear. Not because of `CW_USEDEFAULT`; probably related to multiple threading and Everything positioning behavior.
133    window.set_loc(Point::new(0.0, 0.0));
134}