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
// STARK, a system for computer augmented design.
// Copyright (C) 2021 Matthew Rothlisberger

// STARK is licensed under the terms of the GNU Affero General Public
// License. See the top level LICENSE file for the license text.

// Find full copyright information in the top level COPYRIGHT file.

// <>

// src/context.rs

// Functions to acquire a window from the desktop environment and get
// user input. A Sail stack is used to send input information to other
// threads.

// <>

use crate::{Frame, sail};

use png;
use winit::{
    dpi,
    event::{self, DeviceEvent, ElementState, Event, VirtualKeyCode, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    window::{self, WindowBuilder},
};

use std::fs::File;
use std::thread;

/// Uses `winit` to acquire a graphical frame and create an event loop for it
pub fn init_context(
    title: &str,
    icon_file: &str,
    width: u32,
    height: u32,
) -> (Frame, EventLoop<()>) {
    let event_loop = EventLoop::new();
    let frame = WindowBuilder::new()
        .with_title(title)
        .with_window_icon(get_icon(icon_file))
        .with_inner_size(dpi::Size::Physical(dpi::PhysicalSize { width, height }))
        .build(&event_loop)
        .unwrap();

    (frame, event_loop)
}

/// Serves as the main loop for the context thread; occupies a `winit` event loop
pub fn run_loop<Ij: 'static>(
    event_loop: EventLoop<()>,
    threads: Ij,
    sl_reg: usize,
    m_send: usize,
    r_send: usize,
    fr_dims: usize,
    cur_pos: usize,
) where
    Ij: Iterator<Item = thread::JoinHandle<()>>,
{
    let mut joins = Some(threads);

    let _stdin = thread::Builder::new()
        .name("stdin".to_string())
        .spawn(move || {
            let sl_reg = sl_reg as *mut sail::memmgt::Region;
            let main_tx = m_send as *mut sail::SlHead;

            let mut buffer = String::new();

            loop {
                buffer.clear();
                std::io::stdin().read_line(&mut buffer).unwrap();

                let strin = sail::string_init(sl_reg, &buffer);
                let shell = sail::sym_init(sl_reg, sail::K_CX_SHELL.0);

                sail::queue::queue_tx(main_tx, shell);
                sail::queue::queue_tx(main_tx, strin);
            }
        })
        .unwrap();

    let sl_reg = sl_reg as *mut sail::memmgt::Region;

    let main_tx = m_send as *mut sail::SlHead;
    let rndr_tx = r_send as *mut sail::SlHead;

    let fr_dims = fr_dims as *mut sail::SlHead;
    let cur_pos = cur_pos as *mut sail::SlHead;

    // TODO: use a small region with space for a queue sender;
    // allocate objects to send in region, send them, and then
    // deallocate them to leave space for more

    // TODO: this will allow this thread and the stdin thread to be
    // much simpler

    let mut frame_dims: [u32; 2] = [0, 0];

    let mut focus = false;

    event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Wait;

        match event {
            Event::LoopDestroyed => {
                joins.take().unwrap().for_each(|x| x.join().unwrap());
            }

            Event::RedrawRequested(..) => {
                let redrw = sail::sym_init(sl_reg, sail::K_CX_REDRW.0);
                sail::queue::queue_tx(rndr_tx, redrw);
            }

            Event::RedrawEventsCleared => {
                // let redrw = sail::sym_init(sl_reg, sail::K_CX_REDRW.0);
                // sail::queue::queue_tx(rndr_tx, redrw);
            }

            Event::WindowEvent { event, .. } => match event {
                WindowEvent::CloseRequested => {
                    *control_flow = ControlFlow::Exit;

                    let destr = sail::sym_init(sl_reg, sail::K_CX_DESTR.0);

                    sail::queue::queue_tx(rndr_tx, destr);
                    sail::queue::queue_tx(main_tx, destr);
                }
                WindowEvent::Focused(f) => {
                    focus = f;
                }
                WindowEvent::Resized(dims) => {
                    frame_dims = [dims.width, dims.height];
                    sail::arrvec_rplc(fr_dims, &[dims.width, dims.height]);

                    let resiz = sail::sym_init(sl_reg, sail::K_CX_RESIZ.0);
                    sail::queue::queue_tx(rndr_tx, resiz);
                }
                WindowEvent::ScaleFactorChanged {
                    new_inner_size: dims,
                    ..
                } => {
                    frame_dims = [dims.width, dims.height];
                    sail::arrvec_rplc(fr_dims, &[dims.width, dims.height]);

                    let resiz = sail::sym_init(sl_reg, sail::K_CX_RESIZ.0);
                    sail::queue::queue_tx(rndr_tx, resiz);
                }
                WindowEvent::MouseInput { state, button, .. } => {
                    if state == ElementState::Pressed {
                        let recrd = sail::sym_init(sl_reg, sail::K_CX_RECRD.0);
                        sail::queue::queue_tx(main_tx, recrd);
                    }
                }
                WindowEvent::CursorMoved {
                    position: dpi::PhysicalPosition { x, y },
                    ..
                } => {
                    sail::arrvec_rplc(cur_pos, &[
                        (x / (frame_dims[0] / 2) as f64 - 1.0) as f32,
                        (y / (frame_dims[1] / 2) as f64 - 1.0) as f32,
                    ]);

                    let redrw = sail::sym_init(sl_reg, sail::K_CX_REDRW.0);
                    sail::queue::queue_tx(rndr_tx, redrw);
                }
                _ => {}
            },

            Event::DeviceEvent { event, .. } => match event {
                DeviceEvent::Key(event::KeyboardInput {
                    scancode,
                    state,
                    virtual_keycode,
                    ..
                }) => {
                    if focus && state == ElementState::Pressed {
                        match virtual_keycode {
                            Some(VirtualKeyCode::U) => {
                                // move up
                                let key_u = sail::sym_init(sl_reg, sail::K_CX_KEY_U.0);
                                sail::queue::queue_tx(main_tx, key_u);
                            }
                            Some(VirtualKeyCode::D) => {
                                // move down
                                let key_d = sail::sym_init(sl_reg, sail::K_CX_KEY_D.0);
                                sail::queue::queue_tx(main_tx, key_d);
                            }
                            Some(VirtualKeyCode::F) => {
                                // move forward (right)
                                let key_f = sail::sym_init(sl_reg, sail::K_CX_KEY_F.0);
                                sail::queue::queue_tx(main_tx, key_f);
                            }
                            Some(VirtualKeyCode::B) => {
                                // move backward (left)
                                let key_b = sail::sym_init(sl_reg, sail::K_CX_KEY_B.0);
                                sail::queue::queue_tx(main_tx, key_b);
                            }
                            Some(VirtualKeyCode::L) => {
                                // make step longer
                                let key_l = sail::sym_init(sl_reg, sail::K_CX_KEY_L.0);
                                sail::queue::queue_tx(main_tx, key_l);
                            }
                            Some(VirtualKeyCode::S) => {
                                // make step shorter
                                let key_s = sail::sym_init(sl_reg, sail::K_CX_KEY_S.0);
                                sail::queue::queue_tx(main_tx, key_s);
                            }
                            Some(VirtualKeyCode::E) => {
                                // escape line in progress
                                let key_e = sail::sym_init(sl_reg, sail::K_CX_KEY_E.0);
                                sail::queue::queue_tx(main_tx, key_e);
                            }
                            Some(VirtualKeyCode::K) => {
                                // kill last line drawn
                                let key_k = sail::sym_init(sl_reg, sail::K_CX_KEY_K.0);
                                sail::queue::queue_tx(main_tx, key_k);
                            }
                            Some(VirtualKeyCode::M) => {
                                // switch drawing mode
                                let key_m = sail::sym_init(sl_reg, sail::K_CX_KEY_M.0);
                                sail::queue::queue_tx(main_tx, key_m);
                            }
                            Some(VirtualKeyCode::Space) => {
                                // enter the point
                                let recrd = sail::sym_init(sl_reg, sail::K_CX_RECRD.0);
                                sail::queue::queue_tx(main_tx, recrd);
                            }
                            _ => {}
                        }
                    }
                }
                // DeviceEvent::MouseWheel {
                //     delta: event::MouseScrollDelta::LineDelta(xdel, ydel),
                // } => {}
                // DeviceEvent::MouseMotion {
                //     delta: (xdel, ydel),
                // } => {}
                _ => {}
            },

            _ => {}
        }
    });
}

/// Retrieves an icon from a PNG file and outputs it in the format desired by `winit`
fn get_icon(filename: &str) -> Option<window::Icon> {
    let decoder = png::Decoder::new(File::open(filename).unwrap());
    let (info, mut reader) = decoder.read_info().unwrap();

    let mut buf = vec![0; info.buffer_size()];

    reader.next_frame(&mut buf).unwrap();

    Some(window::Icon::from_rgba(buf, info.width, info.height).unwrap())
}