submission.rs 11.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*! Managing the state of text input in the application.
 * 
 * This is a library module.
 * 
 * It needs to combine text-input and virtual-keyboard protocols
 * to achieve a consistent view of the text-input state,
 * and to submit exactly what the user wanted.
 * 
 * It must also not get tripped up by sudden disappearances of interfaces.
 * 
 * The virtual-keyboard interface is always present.
 * 
 * The text-input interface may not be presented,
 * and, for simplicity, no further attempt to claim it is made.
 * 
 * The text-input interface may be enabled and disabled at arbitrary times,
 * and those events SHOULD NOT cause any lost events.
 * */
19
20

use std::collections::HashSet;
21
use std::ffi::CString;
22
use ::action::Modifier;
23
use ::imservice;
24
use ::imservice::IMService;
25
use ::keyboard::{ KeyCode, KeyStateId, Modifiers, PressType };
26
use ::layout;
27
use ::ui_manager::VisibilityManager;
28
use ::util::vec_remove;
29
use ::vkeyboard;
30
use ::vkeyboard::VirtualKeyboard;
31

32
33
34
// traits
use std::iter::FromIterator;

35
36
37
38
39
40
41
/// Gathers stuff defined in C or called by C
pub mod c {
    use super::*;
    
    use std::os::raw::c_void;

    use ::imservice::c::InputMethod;
42
    use ::util::c::Wrapped;
43
    use ::vkeyboard::c::ZwpVirtualKeyboardV1;
44
45
46
47
48
49
50
51
52
53
54

    // The following defined in C

    /// EekboardContextService*
    #[repr(transparent)]
    pub struct StateManager(*const c_void);

    #[no_mangle]
    pub extern "C"
    fn submission_new(
        im: *mut InputMethod,
55
        vk: ZwpVirtualKeyboardV1,
56
57
        state_manager: *const StateManager,
        visibility_manager: Wrapped<VisibilityManager>,
58
59
60
61
    ) -> *mut Submission {
        let imservice = if im.is_null() {
            None
        } else {
62
63
64
65
66
67
            let visibility_manager = visibility_manager.clone_ref();
            Some(IMService::new(
                im,
                state_manager,
                Box::new(move |active| visibility_manager.borrow_mut().set_im_active(active)),
            ))
68
69
70
71
72
        };
        // TODO: add vkeyboard too
        Box::<Submission>::into_raw(Box::new(
            Submission {
                imservice,
73
                modifiers_active: Vec::new(),
74
                virtual_keyboard: VirtualKeyboard(vk),
75
                pressed: Vec::new(),
76
77
                keymap_fds: Vec::new(),
                keymap_idx: None,
78
79
80
81
            }
        ))
    }

82
83
    #[no_mangle]
    pub extern "C"
84
    fn submission_use_layout(
85
        submission: *mut Submission,
86
        layout: *const layout::Layout,
87
88
        time: u32,
    ) {
89
90
91
92
        if submission.is_null() {
            panic!("Null submission pointer");
        }
        let submission: &mut Submission = unsafe { &mut *submission };
93
94
        let layout = unsafe { &*layout };
        submission.use_layout(layout, Timestamp(time));
95
    }
96
97
98
99
100
101
102
103
104
105
106
107

    #[no_mangle]
    pub extern "C"
    fn submission_hint_available(submission: *mut Submission) -> u8 {
        if submission.is_null() {
            panic!("Null submission pointer");
        }
        let submission: &mut Submission = unsafe { &mut *submission };
        let active = submission.imservice.as_ref()
            .map(|imservice| imservice.is_active());
        (Some(true) == active) as u8
    }
108
109
}

110
111
112
#[derive(Clone, Copy)]
pub struct Timestamp(pub u32);

113
#[derive(Clone)]
114
115
116
117
118
119
enum SubmittedAction {
    /// A collection of keycodes that were pressed
    VirtualKeyboard(Vec<KeyCode>),
    IMService,
}

120
121
pub struct Submission {
    imservice: Option<Box<IMService>>,
122
    virtual_keyboard: VirtualKeyboard,
123
    modifiers_active: Vec<(KeyStateId, Modifier)>,
124
    pressed: Vec<(KeyStateId, SubmittedAction)>,
125
126
    keymap_fds: Vec<vkeyboard::c::KeyMap>,
    keymap_idx: Option<usize>,
127
128
}

129
130
131
132
133
134
pub enum SubmitData<'a> {
    Text(&'a CString),
    Erase,
    Keycodes,
}

135
136
137
138
139
impl Submission {
    /// Sends a submit text event if possible;
    /// otherwise sends key press and makes a note of it
    pub fn handle_press(
        &mut self,
140
141
142
        key_id: KeyStateId,
        data: SubmitData,
        keycodes: &Vec<KeyCode>,
143
144
        time: Timestamp,
    ) {
145
146
147
148
        let mods_are_on = !self.modifiers_active.is_empty();

        let was_committed_as_text = match (&mut self.imservice, mods_are_on) {
            (Some(imservice), false) => {
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
                enum Outcome {
                    Submitted(Result<(), imservice::SubmitError>),
                    NotSubmitted,
                };

                let submit_outcome = match data {
                    SubmitData::Text(text) => {
                        Outcome::Submitted(imservice.commit_string(text))
                    },
                    SubmitData::Erase => {
                        /* Delete_surrounding_text takes byte offsets,
                         * so cannot work without get_surrounding_text.
                         * This is a bug in the protocol.
                         */
                        // imservice.delete_surrounding_text(1, 0),
                        Outcome::NotSubmitted
                    },
                    SubmitData::Keycodes => Outcome::NotSubmitted,
                };
168

169
170
171
172
173
174
175
176
                match submit_outcome {
                    Outcome::Submitted(result) => {
                        match result.and_then(|()| imservice.commit()) {
                            Ok(()) => true,
                            Err(imservice::SubmitError::NotActive) => false,
                        }
                    },
                    Outcome::NotSubmitted => false,
177
178
                }
            },
179
            (_, _) => false,
180
        };
181

182
        let submit_action = match was_committed_as_text {
183
184
            true => SubmittedAction::IMService,
            false => {
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
                let keycodes_count = keycodes.len();
                for keycode in keycodes.iter() {
                    self.select_keymap(keycode.keymap_idx, time);
                    let keycode = keycode.code;
                    match keycodes_count {
                        // Pressing a key made out of a single keycode is simple:
                        // press on press, release on release.
                        1 => self.virtual_keyboard.switch(
                            keycode,
                            PressType::Pressed,
                            time,
                        ),
                        // A key made of multiple keycodes
                        // has to submit them one after the other.
                        _ => {
                            self.virtual_keyboard.switch(
                                keycode.clone(),
                                PressType::Pressed,
                                time,
                            );
                            self.virtual_keyboard.switch(
                                keycode.clone(),
                                PressType::Released,
                                time,
                            );
                        },
                    };
                }
213
                SubmittedAction::VirtualKeyboard(keycodes.clone())
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
            },
        };
        
        self.pressed.push((key_id, submit_action));
    }
    
    pub fn handle_release(&mut self, key_id: KeyStateId, time: Timestamp) {
        let index = self.pressed.iter().position(|(id, _)| *id == key_id);
        if let Some(index) = index {
            let (_id, action) = self.pressed.remove(index);
            match action {
                // string already sent, nothing to do
                SubmittedAction::IMService => {},
                // no matter if the imservice got activated,
                // keys must be released
                SubmittedAction::VirtualKeyboard(keycodes) => {
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
                    let keycodes_count = keycodes.len();
                    match keycodes_count {
                        1 => {
                            let keycode = &keycodes[0];
                            self.select_keymap(keycode.keymap_idx, time);
                            self.virtual_keyboard.switch(
                                keycode.code,
                                PressType::Released,
                                time,
                            );
                        },
                        // Design choice here: submit multiple all at press time
                        // and do nothing at release time.
                        _ => {},
                    };
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
    
    pub fn handle_add_modifier(
        &mut self,
        key_id: KeyStateId,
        modifier: Modifier, _time: Timestamp,
    ) {
        self.modifiers_active.push((key_id, modifier));
        self.update_modifiers();
    }

    pub fn handle_drop_modifier(
        &mut self,
        key_id: KeyStateId,
        _time: Timestamp,
    ) {
        vec_remove(&mut self.modifiers_active, |(id, _)| *id == key_id);
        self.update_modifiers();
    }

    fn update_modifiers(&mut self) {
        let raw_modifiers = self.modifiers_active.iter()
            .map(|(_id, m)| match m {
                Modifier::Control => Modifiers::CONTROL,
                Modifier::Alt => Modifiers::MOD1,
            })
            .fold(Modifiers::empty(), |m, n| m | n);
        self.virtual_keyboard.set_modifiers_state(raw_modifiers);
    }

    pub fn is_modifier_active(&self, modifier: Modifier) -> bool {
        self.modifiers_active.iter()
            .position(|(_id, m)| *m == modifier)
            .is_some()
    }

    pub fn get_active_modifiers(&self) -> HashSet<Modifier> {
        HashSet::from_iter(
            self.modifiers_active.iter().map(|(_id, m)| m.clone())
        )
    }
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314

    fn clear_all_modifiers(&mut self) {
        // Looks like an optimization,
        // but preemptive cleaning is needed before setting a new keymap,
        // so removing this check would break keymap setting.
        if self.modifiers_active.is_empty() {
            return;
        }
        self.modifiers_active = Vec::new();
        self.virtual_keyboard.set_modifiers_state(Modifiers::empty())
    }

    fn release_all_virtual_keys(&mut self, time: Timestamp) {
        let virtual_pressed = self.pressed
            .clone().into_iter()
            .filter_map(|(id, action)| {
                match action {
                    SubmittedAction::VirtualKeyboard(_) => Some(id),
                    _ => None,
                }
            });
        for id in virtual_pressed {
            self.handle_release(id, time);
        }
    }

315

316
317
318
319
320
321
322
323
324
    /// Changes keymap and clears pressed keys and modifiers.
    ///
    /// It's not obvious if clearing is the right thing to do, 
    /// but keymap update may (or may not) do that,
    /// possibly putting self.modifiers_active and self.pressed out of sync,
    /// so a consistent stance is adopted to avoid that.
    /// Alternatively, modifiers could be restored on the new keymap.
    /// That approach might be difficult
    /// due to modifiers meaning different things in different keymaps.
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    fn select_keymap(&mut self, idx: usize, time: Timestamp) {
        if self.keymap_idx != Some(idx) {
            self.keymap_idx = Some(idx);
            self.clear_all_modifiers();
            self.release_all_virtual_keys(time);
            let keymap = &self.keymap_fds[idx];
            self.virtual_keyboard.update_keymap(keymap);
        }
    }
    
    pub fn use_layout(&mut self, layout: &layout::Layout, time: Timestamp) {
        self.keymap_fds = layout.keymaps.iter()
            .map(|keymap_str| vkeyboard::c::KeyMap::from_cstr(
                keymap_str.as_c_str()
            ))
            .collect();
        self.keymap_idx = None;

        // This can probably be eliminated,
        // because key presses can trigger an update anyway.
        // However, self.keymap_idx needs to become Option<>
        // in order to force update on new layouts.
        self.select_keymap(0, time);
348
    }
349
}