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
//! Bindings to the Legacy/gauges.h API

use crate::sys;

#[doc(hidden)]
pub trait SimVarF64 {
    fn to(self) -> f64;
    fn from(v: f64) -> Self;
}

impl SimVarF64 for f64 {
    fn to(self) -> f64 {
        self
    }

    fn from(v: f64) -> Self {
        v
    }
}

impl SimVarF64 for bool {
    fn to(self) -> f64 {
        if self {
            1.0
        } else {
            0.0
        }
    }

    fn from(v: f64) -> Self {
        v != 0.0
    }
}

impl SimVarF64 for u8 {
    fn to(self) -> f64 {
        self as f64
    }

    fn from(v: f64) -> Self {
        v as Self
    }
}

/// aircraft_varget
/// get_aircraft_var_enum
#[derive(Debug)]
pub struct AircraftVariable {
    simvar: sys::ENUM,
    units: sys::ENUM,
    index: sys::SINT32,
}
impl AircraftVariable {
    pub fn from(name: &str, units: &str, index: usize) -> Result<Self, Box<dyn std::error::Error>> {
        let name = std::ffi::CString::new(name).unwrap();
        let units = std::ffi::CString::new(units).unwrap();

        let simvar = unsafe { sys::get_aircraft_var_enum(name.as_ptr()) };
        if simvar == -1 {
            return Err(Box::new(std::io::Error::new(
                std::io::ErrorKind::Other,
                "invalid name",
            )));
        }

        let units = unsafe { sys::get_units_enum(units.as_ptr()) };
        if units == -1 {
            return Err(Box::new(std::io::Error::new(
                std::io::ErrorKind::Other,
                "invalid units",
            )));
        }
        Ok(Self {
            simvar,
            units,
            index: index as sys::SINT32,
        })
    }

    pub fn get<T: SimVarF64>(&self) -> T {
        let v = unsafe { sys::aircraft_varget(self.simvar, self.units, self.index) };
        T::from(v)
    }
}

/// register_named_variable
/// set_named_variable_typed_value
/// get_named_variable_value
/// set_named_variable_value
#[derive(Debug)]
pub struct NamedVariable(sys::ID);
impl NamedVariable {
    pub fn from(name: &str) -> Self {
        Self(unsafe {
            let name = std::ffi::CString::new(name).unwrap();
            sys::register_named_variable(name.as_ptr())
        })
    }

    pub fn get_value<T: SimVarF64>(&self) -> T {
        let v = unsafe { sys::get_named_variable_value(self.0) };
        T::from(v)
    }

    pub fn set_value(&self, v: impl SimVarF64) {
        let v = v.to();
        unsafe { sys::set_named_variable_value(self.0, v) }
    }
}

/// trigger_key_event
pub fn trigger_key_event(event_id: sys::ID32, value: sys::UINT32) {
    unsafe {
        sys::trigger_key_event(event_id, value);
    }
}

/// trigger_key_event_EX1
pub fn trigger_key_event_ex1(
    event_id: sys::ID32,
    value0: sys::UINT32,
    value1: sys::UINT32,
    value2: sys::UINT32,
    value3: sys::UINT32,
    value4: sys::UINT32,
) {
    unsafe {
        sys::trigger_key_event_EX1(event_id, value0, value1, value2, value3, value4);
    }
}

#[doc(hidden)]
pub trait ExecuteCalculatorCodeImpl {
    fn execute(code: &std::ffi::CStr) -> Option<Self>
    where
        Self: Sized;
}

#[doc(hidden)]
impl ExecuteCalculatorCodeImpl for f64 {
    fn execute(code: &std::ffi::CStr) -> Option<Self> {
        unsafe {
            let mut n = 0.0;
            if sys::execute_calculator_code(
                code.as_ptr(),
                &mut n,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            ) == 1
            {
                Some(n)
            } else {
                None
            }
        }
    }
}

#[doc(hidden)]
impl ExecuteCalculatorCodeImpl for i32 {
    fn execute(code: &std::ffi::CStr) -> Option<Self> {
        unsafe {
            let mut n = 0;
            if sys::execute_calculator_code(
                code.as_ptr(),
                std::ptr::null_mut(),
                &mut n,
                std::ptr::null_mut(),
            ) == 1
            {
                Some(n)
            } else {
                None
            }
        }
    }
}

#[doc(hidden)]
impl ExecuteCalculatorCodeImpl for String {
    fn execute(code: &std::ffi::CStr) -> Option<Self> {
        unsafe {
            let mut s = std::ptr::null();
            if sys::execute_calculator_code(
                code.as_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                &mut s,
            ) == 1
            {
                Some(std::ffi::CStr::from_ptr(s).to_str().unwrap().to_owned())
            } else {
                None
            }
        }
    }
}

#[doc(hidden)]
impl ExecuteCalculatorCodeImpl for () {
    fn execute(code: &std::ffi::CStr) -> Option<Self> {
        unsafe {
            if sys::execute_calculator_code(
                code.as_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            ) == 1
            {
                Some(())
            } else {
                None
            }
        }
    }
}

/// execute_calculator_code
pub fn execute_calculator_code<T: ExecuteCalculatorCodeImpl>(code: &str) -> Option<T> {
    let code = std::ffi::CString::new(code).unwrap();
    ExecuteCalculatorCodeImpl::execute(code.as_c_str())
}

/// Holds compiled calculator code, wraps `gauge_calculator_code_precompile`.
#[derive(Debug)]
pub struct CompiledCalculatorCode {
    p_compiled: sys::PCSTRINGZ,
    _p_compiled_size: sys::UINT32,
}

impl CompiledCalculatorCode {
    /// Create a new CompiledCalculatorCode instance.
    pub fn new(code: &str) -> Option<Self> {
        let mut p_compiled = std::mem::MaybeUninit::uninit();
        let mut p_compiled_size = std::mem::MaybeUninit::uninit();
        unsafe {
            let code = std::ffi::CString::new(code).unwrap();
            if sys::gauge_calculator_code_precompile(
                p_compiled.as_mut_ptr(),
                p_compiled_size.as_mut_ptr(),
                code.as_ptr(),
            ) != 0
            {
                Some(CompiledCalculatorCode {
                    p_compiled: p_compiled.assume_init(),
                    _p_compiled_size: p_compiled_size.assume_init(),
                })
            } else {
                None
            }
        }
    }

    /// Execute this CompiledCalculatorCode instance.
    pub fn execute<T: ExecuteCalculatorCodeImpl>(&self) -> Option<T> {
        ExecuteCalculatorCodeImpl::execute(unsafe { std::ffi::CStr::from_ptr(self.p_compiled) })
    }
}