aboutsummaryrefslogtreecommitdiffstats
path: root/src/cocoa_bridge.rs
blob: 265c052ef9cb12f20931d782d831bc4f637afacb (plain)
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use std::ffi::{CStr, CString};
use std::fs;
use std::mem;
use std::ptr;
use std::slice;

use autopilot::key::type_string;
// use cocoa::base::nil;
// use cocoa::foundation::{NSArray, NSAutoreleasePool, NSDictionary};
use libc::{c_char, size_t};
use stderrlog;
use xdg;

use {Action, HeadphoneButton, MapGroup, MapKind};

#[repr(C)]
struct renameMeMapGroup {
}

// pub extern "C" fn parse_mappings() {
//     let sample_maps = "map <up> k
// map <down> j";
//
//     let map_group = MapGroup::parse(sample_maps).unwrap();
//
//     unsafe {
//         let _pool = NSAutoreleasePool::new(nil);
//
//         let maps = NSDictionary::init(nil).autorelease();
//         let modes = NSDictionary::init(nil).autorelease();
//
//         for (trigger, action) in map_group.maps {
//             // let t = NSArray::arrayWithObjects(nil, &trigger).autorelease();
//
//             // maps.
//         }
//
//         for (trigger, modes) in map_group.modes {
//         }
//     }
// }

// Different method:
// Call Rust function with trigger
// Return keys to press
// or run command (from Rust?)
// Somehow: switch mode inside Rust

#[repr(C)]
#[derive(Debug)]
pub struct Trigger {
    pub buttons: *const HeadphoneButton,
    pub length: size_t,
}

#[repr(C)]
pub enum ActionKind {
    Map,
    Command,
    Mode,
}

#[repr(C)]
pub struct KeyActionResult<'a> {
    pub action: Option<CString>,
    pub kind: ActionKind,
    pub in_mode: Option<&'a [HeadphoneButton]>,
}

impl<'a> KeyActionResult<'a> {
    fn new(kind: ActionKind) -> Self {
        KeyActionResult {
            action: None,
            kind: kind,
            in_mode: None,
        }
    }

    fn with_action(mut self, action: &str) -> Self {
        let action = CString::new(action.clone()).unwrap();
        self.action = Some(action);
        self
    }

    fn in_mode(mut self, mode: &'a [HeadphoneButton]) -> Self {
        self.in_mode = Some(mode);
        self
    }
}

#[repr(C)]
#[derive(Debug)]
pub struct CKeyActionResult {
    pub action: *const c_char,
    pub kind: *const ActionKind,
    pub in_mode: *const Trigger,
}

#[derive(Default)]
pub struct State {
    in_mode: Option<Vec<HeadphoneButton>>,
    map_group: Option<MapGroup>,
}

#[no_mangle]
pub extern "C" fn logger_init() {
    stderrlog::new()
        .module(module_path!())
        .color(stderrlog::ColorChoice::Never)
        .timestamp(stderrlog::Timestamp::Millisecond)
        .init()
        .unwrap();
}

#[no_mangle]
pub extern "C" fn state_new() -> *mut State {
    Box::into_raw(Box::new(State::default()))
}

#[no_mangle]
pub extern "C" fn state_free(ptr: *mut State) {
    if ptr.is_null() { return }
    unsafe { Box::from_raw(ptr); }
}

#[no_mangle]
pub extern "C" fn state_load_map_group(ptr: *mut State) {
    match xdg::BaseDirectories::with_prefix("dome-key") {
        Ok(xdg_dirs) => {
            match xdg_dirs.find_config_file("mappings.dkmap") {
                Some(mapping_file) => {
                    let state = unsafe {
                        assert!(!ptr.is_null());
                        &mut *ptr
                    };

                    let dkmap = fs::read_to_string(mapping_file)
                        .expect("Failed to read 'mappings.dkmap'");
                    state.map_group = Some(
                        MapGroup::parse(&dkmap)
                            .expect("Failed to parse 'mappings.dkmap'")
                    );
                },
                None => {
                    match xdg_dirs.get_config_home().to_str() {
                        Some(config_home) => {
                            error!(
                                "No mapping file found at '{}{}'",
                                config_home,
                                "mappings.dkmap"
                            )
                        },
                        None => {
                            error!("Config home path contains invalid unicode")
                        }
                    }
                },
            }
        },
        Err(e) => error!("{}", e),
    }
}

#[no_mangle]
pub extern "C" fn c_run_key_action(
    state: *mut State,
    trigger: Trigger,
    mode: *const Trigger,
) -> *const CKeyActionResult {
    let trigger = unsafe {
        assert!(!trigger.buttons.is_null());

        slice::from_raw_parts(trigger.buttons, trigger.length as usize)
    };

    let mode = unsafe {
        if mode.is_null() {
            None
        } else {
            println!("In mode(110): {:?}", *mode);
            assert!(!(*mode).buttons.is_null());

            Some(
                slice::from_raw_parts((*mode).buttons, (*mode).length as usize)
            )
        }
    };
    println!("Mode after unsafe (118): {:?}", mode);

    let mut state = unsafe {
        assert!(!state.is_null());
        &mut *state
    };

    let result = run_key_action_for_mode(&mut state, trigger, mode);
    let result = match result {
        Some(k) => {
            let action = k.action.map_or_else(
                || ptr::null(),
                |a| a.into_raw(),
            );
            // let in_mode = k.in_mode.map_or_else(
            //     || ptr::null(),
            //     |m| {
            //         let trigger = Trigger {
            //             buttons: m.as_ptr(),
            //             length: m.len(),
            //         };
            //         mem::forget(m);
            //
            //         &trigger
            //     },
            // );
            let trigger;
            let in_mode = if let Some(m) = k.in_mode {
                let boink = Trigger {
                    buttons: m.as_ptr(),
                    length: m.len(),
                };

                trigger = Box::into_raw(Box::new(boink)); // TODO: memory leak
                trigger
            } else {
                ptr::null()
            };
            // mem::forget(k.in_mode);
            // mem::forget(in_mode);
            // println!("IN MODE: {:?}", &in_mode);
            // let in_mode2 = Box::new(k.in_mode);
            // let in_mode_ptr = Box::into_raw(in_mode2);

            let result = CKeyActionResult {
                action: action, // memory leak, must be freed from Rust
                kind: &k.kind,
                in_mode: in_mode,
            };
            println!("CKeyActionResult(161): {:?}", result);
            // mem::forget(result);
            result
        },
        None => {
            CKeyActionResult {
                action: ptr::null(),
                kind: ptr::null(),
                in_mode: ptr::null(),
            }
        }
    };
    // println!("hey result: {:?}", result);
    // mem::forget(result);
    println!("Result 177: {:?}", result);
    let r = Box::new(result);
    let r2 = Box::into_raw(r);
    println!("r2: {:?}", r2);

    // &result as *const CKeyActionResult
    r2 as *const CKeyActionResult
}

#[no_mangle]
pub extern "C" fn run_key_action_for_mode<'a>(
    state: &mut State,
    trigger: &'a [HeadphoneButton],
    in_mode: Option<&[HeadphoneButton]>
) -> Option<KeyActionResult<'a>> {
    let sample_maps = "map <up> k
map <down> j
map <play><down> works!
mode <play><up> {
    map <down> hello
}
";

    // Figure out how to persist this without re-parsing
    // let map_group = MapGroup::parse(sample_maps).unwrap();
    match state.map_group {
        Some(ref map_group) => {
            let map = map_group.maps.get(trigger);
            let mode = map_group.modes.get(trigger);

            if let Some(in_mode) = state.in_mode.clone() {
                if let Some(mode) = map_group.modes.get(&in_mode) {
                    // Deactivate mode by pressing current mode trigger
                    if &in_mode[..] == trigger {
                        state.in_mode = None;

                        return Some(KeyActionResult::new(ActionKind::Mode))
                    }

                    if let Some(map) = mode.get(trigger) {
                        return match map.kind {
                            MapKind::Map => {
                                if let Action::String(s) = &map.action {
                                    type_string(s, &[], 0.0, 0.0);

                                    Some(
                                        KeyActionResult::new(ActionKind::Map)
                                            .with_action(s)
                                            .in_mode(trigger)
                                    )
                                } else {
                                    None
                                }
                            },
                            MapKind::Command => {
                                Some(
                                    KeyActionResult::new(ActionKind::Command)
                                        .in_mode(trigger)
                                )
                            },
                        }
                    }
                }
            }

            // TODO: make sure this doesn't run when in_mode
            if state.in_mode.is_none() {
                if let Some(map) = map {
                    return match map.kind {
                        MapKind::Map => {
                            if let Action::String(s) = &map.action {
                                type_string(s, &[], 0.0, 0.0);

                                Some(
                                    KeyActionResult::new(ActionKind::Map)
                                        .with_action(s)
                                )
                            } else {
                                None
                            }
                        },
                        MapKind::Command => {
                            Some(
                                KeyActionResult::new(ActionKind::Command)
                            )
                        },
                        // MapKind::Mode => {
                            // TODO: Maybe make a new type just for KeyActionResult that
                            // combines regular MapKinds and Mode
                        // },
                    }
                }
            }

            if let Some(mode) = mode {
                state.in_mode = Some(trigger.to_vec());

                return Some(
                    KeyActionResult::new(ActionKind::Mode)
                        .in_mode(trigger)
                )
            }

            // match map_group.get(trigger) {
            //     Some(map_action) => {
            //         Some(KeyActionResult {
            //             action: map_action.action,
            //             kind: MapKind::Map,
            //         })
            //     },
            //     None => {
            //         // TODO: Figure out how to error
            //         None
            //     },
            // }

            None
        },
        None => None,
    }
}

// fn run_command(command: Action) -> Result {
// }


mod tests {
    use super::*;

    #[test]
    fn parse_mappings_makes_cocoa_mappings() {
        parse_mappings();
    }
}