1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/* Copyright (C) 2020,2022 Purism SPC
 * SPDX-License-Identifier: GPL-3.0+
 */

/*! Glue for the main loop. */
use crate::actors;
use crate::actors::external::debug;
use crate::animation;
use crate::data::loading;
use crate::event_loop;
use crate::panel;
use crate::state;
use glib::{Continue, MainContext, PRIORITY_DEFAULT, Receiver};


mod c {
    use super::*;
    use std::ffi::CString;
    use std::os::raw::{c_char, c_void};
    use std::ptr;
    use std::rc::Rc;
    use std::time::Instant;

    use crate::actors::Destination;
    use crate::actors::popover;
    use crate::event_loop::driver;
    use crate::imservice::IMService;
    use crate::imservice::c::InputMethod;
    use crate::layout;
    use crate::outputs::Outputs;
    use crate::state;
    use crate::submission::Submission;
    use crate::util::c::{ArcWrapped, Wrapped};
    use crate::vkeyboard::c::ZwpVirtualKeyboardV1;
    
    /// DbusHandler*
    #[repr(transparent)]
    pub struct DBusHandler(*const c_void);

    /// EekboardContextService* in the role of a hint receiver
    // The clone/copy is a concession to C style of programming.
    // It would be hard to get rid of it.
    #[repr(transparent)]
    #[derive(Clone, Copy)]
    pub struct HintManager(*const c_void);
    
    /// Holds the Rust structures that are interesting from C.
    #[repr(C)]
    pub struct RsObjects {
        /// The handle to which Commands should be sent
        /// for processing in the main loop.
        receiver: Wrapped<Receiver<Commands>>,
        state_manager: Wrapped<EventLoop>,
        submission: Wrapped<Submission>,
        /// Not wrapped, because C needs to access this.
        wayland: *mut Wayland,
        popover: actors::popover::c::Actor,
    }

    /// Corresponds to wayland.h::squeek_wayland.
    /// Fields unused by Rust are marked as generic data types.
    #[repr(C)]
    pub struct Wayland {
        layer_shell: *const c_void,
        virtual_keyboard_manager: *const c_void,
        input_method_manager: *const c_void,
        outputs: Wrapped<Outputs>,
        seat: *const c_void,
        input_method: InputMethod,
        virtual_keyboard: ZwpVirtualKeyboardV1,
    }

    impl Wayland {
        fn new(outputs_manager: Outputs) -> Self {
            Wayland {
                layer_shell: ptr::null(),
                virtual_keyboard_manager: ptr::null(),
                input_method_manager: ptr::null(),
                outputs: Wrapped::new(outputs_manager),
                seat: ptr::null(),
                input_method: InputMethod::null(),
                virtual_keyboard: ZwpVirtualKeyboardV1::null(),
            }
        }
    }
    
    extern "C" {
        #[allow(improper_ctypes)]
        fn init_wayland(wayland: *mut Wayland);
        #[allow(improper_ctypes)]
        fn eekboard_context_service_set_layout(service: HintManager, name: *const c_char, layout: *const layout::Layout, timestamp: u32);
        // This should probably only get called from the gtk main loop,
        // given that dbus handler is using glib.
        fn dbus_handler_set_visible(dbus: *const DBusHandler, visible: u8);
    }
    
    // INITIALIZATION

    /// Creates what's possible in Rust to eliminate as many FFI calls as possible,
    /// because types aren't getting checked across their boundaries,
    /// and that leads to suffering.
    #[no_mangle]
    pub extern "C"
    fn squeek_init() -> RsObjects {
        // Set up channels
        let (sender, receiver) = MainContext::channel(PRIORITY_DEFAULT);
        let now = Instant::now();
        let state_manager = driver::Threaded::new(sender, state::Application::new(now));

        debug::init(state_manager.clone());

        let outputs = Outputs::new(state_manager.clone());
        let mut wayland = Box::new(Wayland::new(outputs));
        let wayland_raw = &mut *wayland as *mut _;
        unsafe { init_wayland(wayland_raw); }

        let vk = wayland.virtual_keyboard;

        let imservice = if wayland.input_method.is_null() {
            None
        } else {
            Some(IMService::new(wayland.input_method, state_manager.clone()))
        };
        let submission = Submission::new(vk, imservice);
        
        let popover = ArcWrapped::new(actors::popover::State::new(true));

        #[cfg(feature = "zbus_v1_5")]
        crate::actors::external::screensaver::init(popover.clone_ref());
        
        RsObjects {
            submission: Wrapped::new(submission),
            state_manager: Wrapped::new(state_manager),
            receiver: Wrapped::new(receiver),
            wayland: Box::into_raw(wayland),
             popover,
        }
    }

    /// Places the UI loop callback in the glib main loop.
    #[no_mangle]
    pub extern "C"
    fn register_ui_loop_handler(
        receiver: Wrapped<Receiver<Commands>>,
        panel_manager: panel::c::PanelManager,
        popover: actors::popover::c::Actor,
        hint_manager: HintManager,
        dbus_handler: *const DBusHandler,
    ) {
        let receiver = unsafe { receiver.unwrap() };
        let receiver = Rc::try_unwrap(receiver).expect("References still present");
        let receiver = receiver.into_inner();
        let panel_manager = Wrapped::new(panel::Manager::new(panel_manager));
        let ctx = MainContext::default();
        let _acqu = ctx.acquire();
        receiver.attach(
            Some(&ctx),
            move |msg| {
                main_loop_handle_message(
                    msg,
                    panel_manager.clone(),
                    &popover.clone_ref(),
                    hint_manager,
                    dbus_handler,
                );
                Continue(true)
            },
        );
        #[cfg(not(feature = "glib_v0_14"))]
        ctx.release();
    }

    /// A single iteration of the UI loop.
    /// Applies state outcomes to external portions of the program.
    /// This is the outest layer of the imperative shell,
    /// and doesn't lend itself to testing other than integration.
    fn main_loop_handle_message(
        msg: Commands,
        panel_manager: Wrapped<panel::Manager>,
        popover: &actors::popover::Destination,
        hint_manager: HintManager,
        dbus_handler: *const DBusHandler,
    ) {
        if let Some(visibility) = msg.panel_visibility {
            panel::Manager::update(panel_manager, visibility);
        }

        if let Some(visible) = msg.dbus_visible_set {
            if dbus_handler != std::ptr::null() {
                unsafe { dbus_handler_set_visible(dbus_handler, visible as u8) };
            }
        }
        
        if let Some(commands::SetLayout { description }) = msg.layout_selection {
            let animation::Contents {
                name,
                kind,
                overlay_name,
                purpose,
            } = description;
            popover.send(popover::Event::Overlay(overlay_name.clone()));
            let layout = loading::load_layout(&name, kind, purpose, &overlay_name);
            let layout = Box::into_raw(Box::new(layout));
            // CSS can't express "+" in the class
            let name = overlay_name.unwrap_or(name).replace('+', "_");
            let name = CString::new(name).unwrap_or(
                CString::new("").unwrap()
            );
            unsafe {
                // Take out the pointer to a temp variable so that it outlives the set_layout call.
                let name = name.as_ptr();
                eekboard_context_service_set_layout(hint_manager, name, layout, 0);
            }
        }
    }
    
    // EVENT PASSING    

    use crate::logging;
    use crate::state::{Event, Presence};
    use crate::state::LayoutChoice;
    use crate::state::visibility;
    use crate::util;
    
    use crate::logging::Warn;
    
    #[no_mangle]
    pub extern "C"
    fn squeek_state_send_force_visible(mgr: Wrapped<EventLoop>) {
        let sender = mgr.clone_ref();
        let sender = sender.borrow();
        sender.send(Event::Visibility(visibility::Event::ForceVisible))
            .or_warn(&mut logging::Print, logging::Problem::Warning, "Can't send to state manager");
    }
    
    #[no_mangle]
    pub extern "C"
    fn squeek_state_send_force_hidden(sender: Wrapped<EventLoop>) {
        let sender = sender.clone_ref();
        let sender = sender.borrow();
        sender.send(Event::Visibility(visibility::Event::ForceHidden))
            .or_warn(&mut logging::Print, logging::Problem::Warning, "Can't send to state manager");
    }

    #[no_mangle]
    pub extern "C"
    fn squeek_state_send_keyboard_present(sender: Wrapped<EventLoop>, present: u32) {
        let sender = sender.clone_ref();
        let sender = sender.borrow();
        let state =
            if present == 0 { Presence::Missing }
            else { Presence::Present };
        sender.send(Event::PhysicalKeyboard(state))
            .or_warn(&mut logging::Print, logging::Problem::Warning, "Can't send to state manager");
    }
    
    #[no_mangle]
    pub extern "C"
    fn squeek_state_send_layout_set(
        sender: Wrapped<EventLoop>,
        name: *const c_char,
        source: *const c_char,
        // TODO: use when synthetic events are needed
        _timestamp: u32,
    ) {
        let sender = sender.clone_ref();
        let sender = sender.borrow();
        let string_or_empty = |v| String::from(
            util::c::as_str(v)
            .unwrap_or(Some(""))
            .unwrap_or("")
        );
        sender
            .send(Event::LayoutChoice(LayoutChoice {
                name: string_or_empty(&name),
                source: string_or_empty(&source).into(),
            }))
            .or_warn(&mut logging::Print, logging::Problem::Warning, "Can't send to state manager");
    }
}


pub type EventLoop = event_loop::driver::Threaded<state::Application>;


pub mod commands {
    use crate::animation;
    #[derive(Clone, Debug)]
    pub struct SetLayout {
        pub description: animation::Contents,
    }
}

/// The commands consumed by the main loop,
/// to be sent out to external components.
#[derive(Clone)]
pub struct Commands {
    pub panel_visibility: Option<panel::Command>,
    pub dbus_visible_set: Option<bool>,
    pub layout_selection: Option<commands::SetLayout>,
}