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
use acrylic::app::Application;
use acrylic::node::Event;
use acrylic::node::EventType;
use acrylic::node::Direction;
use acrylic::bitmap::RGBA;
use acrylic::Spot;
use acrylic::Point;
use acrylic::Size;

use log::{error, set_logger, set_max_level, Record, LevelFilter, Level, Metadata};
use std::fmt::Write;

extern "C" {
    fn raw_error(s: *const u8, l: usize);
    fn raw_warn(s: *const u8, l: usize);
    fn raw_info(s: *const u8, l: usize);
    fn raw_debug(s: *const u8, l: usize);
    fn raw_trace(s: *const u8, l: usize);
    fn raw_set_request_url(s: *const u8, l: usize);
    fn raw_set_request_url_prefix(s: *const u8, l: usize);
    fn raw_set_buffer_address(
        framebuffer: *const u8,
    );
    fn raw_is_request_pending() -> usize;
}

struct ConsoleLog;

impl log::Log for ConsoleLog {
    fn enabled(&self, _metadata: &Metadata) -> bool {
        true
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            let mut s = String::new();
            let _ = write!(&mut s, "{}", record.args());
            unsafe {
                use Level::*;
                match record.level() {
                    Error => raw_error(s.as_ptr(), s.len()),
                    Warn => raw_warn(s.as_ptr(), s.len()),
                    Info => raw_info(s.as_ptr(), s.len()),
                    Debug => raw_debug(s.as_ptr(), s.len()),
                    Trace => raw_trace(s.as_ptr(), s.len()),
                }
            }
        }
    }

    fn flush(&self) {}
}

static LOGGER: ConsoleLog = ConsoleLog;

pub fn set_request_url(s: &str) {
    unsafe { raw_set_request_url(s.as_ptr(), s.len()) };
}

pub fn set_request_url_prefix(s: &str) {
    unsafe { raw_set_request_url_prefix(s.as_ptr(), s.len()) };
}

pub fn is_request_pending() -> bool {
    unsafe { raw_is_request_pending() != 0 }
}

pub fn ensure_pending_request(app: &Application) {
    if !is_request_pending() {
        if let Some(data_request) = app.data_requests.last() {
            set_request_url(&data_request.name);
        }
    }
}

#[allow(dead_code)]
pub static mut APPLICATION: Option<Application> = None;
pub static mut RESPONSE_BYTES: Option<Vec<u8>> = None;

#[export_name = "alloc_response_bytes"]
pub extern "C" fn alloc_response_bytes(len: usize) -> *const u8 {
    let mut vec = Vec::with_capacity(len);
    unsafe { vec.set_len(len) };
    let ptr = vec.as_ptr();
    unsafe { RESPONSE_BYTES = Some(vec) };
    ptr
}

#[export_name = "process_response"]
pub extern "C" fn process_response(app: &mut Application) {
    let request = app.data_requests.len() - 1;
    let data = unsafe { RESPONSE_BYTES.as_ref().unwrap() };
    app.data_response(request, data).unwrap();
}

#[export_name = "drop_response_bytes"]
pub extern "C" fn drop_response_bytes() {
    unsafe {
        RESPONSE_BYTES = None;
    }
}

#[export_name = "discard_request"]
pub extern "C" fn discard_request(app: &mut Application) {
    app.data_requests.pop().unwrap();
}

pub static mut MAIN_FB: Option<Vec<u8>> = None;
pub static mut SCRATCH: Option<Vec<u8>> = None;
pub static mut FB_SIZE: Size = Size::zero();

#[export_name = "set_output_size"]
pub extern "C" fn set_output_size(app: &mut Application, w: usize, h: usize) {
    let fb_size = Size::new(w, h);
    app.set_fb_size(fb_size);
    let pixels = w * h;
    let subpx = pixels * RGBA;
    unsafe {
        FB_SIZE = fb_size;
        if MAIN_FB.is_some() {
            MAIN_FB.as_mut().unwrap().resize(subpx, 0);
        } else {
            MAIN_FB = Some(vec![0; subpx]);
            SCRATCH = Some(Vec::new());
        }
        raw_set_buffer_address(
            MAIN_FB.as_ref().unwrap().as_ptr(),
        );
    };
}

#[export_name = "frame"]
pub extern "C" fn frame(app: &mut Application, age_ms: usize) {
    app.set_age(age_ms);
    let size = unsafe { FB_SIZE };
    let mut spot = Spot {
        window: (Point::zero(), size, None),
        framebuffer: unsafe { &mut MAIN_FB.as_mut().unwrap() },
        fb_size: size,
    };
    app.render(&mut spot, &mut Vec::new());
    ensure_pending_request(app);
}

pub static mut TEXT_INPUT: [u8; 16] = [0; 16];
pub static mut FOCUS_GRABBED: bool = false;
pub static mut FOCUS_POINT: Point = Point {
    x: 0,
    y: 0,
};

#[export_name = "get_text_input_buffer"]
pub extern "C" fn get_text_input_buffer() -> *const u8 {
    unsafe { TEXT_INPUT.as_ptr() }
}

#[export_name = "send_text_input"]
pub extern "C" fn send_text_input(app: &mut Application, len: usize, replace: bool) {
    let bytes = unsafe { &TEXT_INPUT[..len] }.to_vec();
    if let Ok(string) = String::from_utf8(bytes) {
        let event = match replace {
            true => Event::TextReplace(string),
            false => Event::TextInsert(string),
        };
        let _ = app.fire_event(&event);
    }
}

#[export_name = "send_text_delete"]
pub extern "C" fn send_text_delete(app: &mut Application, delete: isize) {
    let _ = app.fire_event(&Event::TextDelete(delete));
}

#[export_name = "send_dir_input"]
pub extern "C" fn send_dir_input(app: &mut Application, dir: usize) {
    let direction = [
        Direction::Up,
        Direction::Left,
        Direction::Down,
        Direction::Right,
    ][dir];
    let _ = app.fire_event(&Event::DirInput(direction));
}

#[export_name = "pointing_at"]
pub extern "C" fn pointing_at(app: &mut Application, x: isize, y: isize) {
    let p = Point::new(x, y);
    if unsafe { !FOCUS_GRABBED } {
        app.pointing_at(p);
    }
    unsafe { FOCUS_POINT = p };
}

#[export_name = "quick_action"]
pub extern "C" fn quick_action(app: &mut Application, action: usize) {
    let mut event = match action {
        1 => Event::QuickAction1,
        2 => Event::QuickAction2,
        3 => Event::QuickAction3,
        4 => Event::QuickAction4,
        5 => Event::QuickAction5,
        6 => Event::QuickAction6,
        _ => unreachable!(),
    };
    let grabbed = unsafe { FOCUS_GRABBED };
    if action == 1 {
        if app.can_grab_focus(Some(EventType::QUICK_ACTION_1)) {
            unsafe { FOCUS_GRABBED = !grabbed };
            event = Event::FocusGrab(!grabbed);
        }
    }
    let _ = app.fire_event(&event);
    if grabbed {
        app.pointing_at(unsafe { FOCUS_POINT });
        quick_action(app, action)
    }
}

pub fn pre_init() {
    set_max_level(LevelFilter::Trace);
    set_logger(&LOGGER).unwrap();
    std::panic::set_hook(Box::new(|panic_info| error!("PANIC! {}", panic_info)));
}

pub fn wasm_init(assets: &str, app: Application) -> &'static Application {
    unsafe {
        set_request_url_prefix(&String::from(assets));
        APPLICATION = Some(app);
        &APPLICATION.as_ref().unwrap()
    }
}

#[macro_export]
macro_rules! app {
    ($path: literal, $init: block) => {
        #[export_name = "init"]
        pub extern "C" fn init() -> &'static Application {
            platform::pre_init();
            platform::wasm_init($path, $init)
        }
    };
}