orbclient 0.3.53

The Orbital Client Library
Documentation
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
// SPDX-License-Identifier: MIT

use std::cell::{Cell, RefCell};
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{mem, ptr, slice};

use crate::color::Color;
use crate::renderer::Renderer;
use crate::Mode;
use crate::WindowFlag;
use crate::{event::*, SurfaceFlag};

static SDL_USAGES: AtomicUsize = AtomicUsize::new(0);
/// SDL2 Context
static mut SDL_CTX: *mut sdl2::Sdl = ptr::null_mut();
/// Video Context
static mut VIDEO_CTX: *mut sdl2::VideoSubsystem = ptr::null_mut();
/// Event Pump
static mut EVENT_PUMP: *mut sdl2::EventPump = ptr::null_mut();

//Call this when the CTX needs to be used is created
#[inline]
unsafe fn init() {
    if SDL_USAGES.fetch_add(1, Ordering::Relaxed) == 0 {
        SDL_CTX = Box::into_raw(Box::new(sdl2::init().unwrap()));
        VIDEO_CTX = Box::into_raw(Box::new((*SDL_CTX).video().unwrap()));
        EVENT_PUMP = Box::into_raw(Box::new((*SDL_CTX).event_pump().unwrap()));
    }
}

// Call this when drop the sdl2 CTX.
#[inline]
unsafe fn cleanup() {
    if SDL_USAGES.fetch_sub(1, Ordering::Relaxed) == 0 {
        return;
    }

    drop(Box::from_raw(SDL_CTX));
    drop(Box::from_raw(VIDEO_CTX));
    drop(Box::from_raw(EVENT_PUMP));
}

/// Return the (width, height) of the display in pixels
pub fn get_display_size() -> Result<(u32, u32), String> {
    unsafe { init() };
    unsafe { &*VIDEO_CTX }
        .display_bounds(0)
        .map(|rect| (rect.width(), rect.height()))
}

/// A window
#[allow(dead_code)]
pub struct Window {
    /// The x coordinate of the window
    x: i32,
    /// The y coordinate of the window
    y: i32,
    /// The width of the window
    w: u32,
    /// The height of the window
    h: u32,
    /// The title of the window
    t: String,
    /// True if the window should not wait for events
    window_async: bool,
    /// Drawing mode
    mode: Cell<Mode>,
    /// The inner renderer
    inner: sdl2::render::WindowCanvas,
    /// Mouse in relative mode
    mouse_relative: bool,
    /// Content of the last drop (file | text) operation
    drop_content: RefCell<Option<String>>,
}

impl Drop for Window {
    fn drop(&mut self) {
        unsafe {
            cleanup();
        }
    }
}

impl AsRawFd for Window {
    fn as_raw_fd(&self) -> RawFd {
        unimplemented!()
    }
}

impl FromRawFd for Window {
    unsafe fn from_raw_fd(_fd: RawFd) -> Window {
        unimplemented!()
    }
}

impl IntoRawFd for Window {
    fn into_raw_fd(self) -> RawFd {
        unimplemented!()
    }
}

impl Renderer for Window {
    /// Get width
    fn width(&self) -> u32 {
        self.w
    }

    /// Get height
    fn height(&self) -> u32 {
        self.h
    }

    /// Access pixel buffer
    fn data(&self) -> &[Color] {
        let window = self.inner.window();
        let surface = window.surface(unsafe { &*EVENT_PUMP }).unwrap();
        let bytes = surface.without_lock().unwrap();
        unsafe {
            slice::from_raw_parts(
                bytes.as_ptr() as *const Color,
                bytes.len() / mem::size_of::<Color>(),
            )
        }
    }

    /// Access pixel buffer mutably
    fn data_mut(&mut self) -> &mut [Color] {
        let window = self.inner.window_mut();
        let mut surface = window.surface(unsafe { &*EVENT_PUMP }).unwrap();
        let bytes = surface.without_lock_mut().unwrap();
        unsafe {
            slice::from_raw_parts_mut(
                bytes.as_mut_ptr() as *mut Color,
                bytes.len() / mem::size_of::<Color>(),
            )
        }
    }

    /// Update the window buffer
    fn sync(&mut self) -> bool {
        self.inner.present();
        true
    }

    /// Update the window buffer
    fn update(&mut self) -> bool {
        let window = self.inner.window_mut();
        let surface = window.surface(unsafe { &*EVENT_PUMP }).unwrap();
        surface.update_window().is_ok()
    }

    /// Update the window buffer
    fn update_rects(&mut self, rects: &[(i32, i32, u32, u32)]) -> bool {
        let window = self.inner.window_mut();
        let surface = window.surface(unsafe { &*EVENT_PUMP }).unwrap();
        surface
            .update_window_rects(
                &rects
                    .iter()
                    .cloned()
                    .map(|(x, y, w, h)| sdl2::rect::Rect::new(x, y, w, h))
                    .collect::<Vec<_>>()[..],
            )
            .is_ok()
    }

    /// Set/get mode
    fn mode(&self) -> &Cell<Mode> {
        &self.mode
    }
}

impl Window {
    /// Create a new window
    pub fn new(x: i32, y: i32, w: u32, h: u32, title: &str) -> Option<Self> {
        Window::new_flags(x, y, w, h, title, &[])
    }

    /// Create a new window with flags
    pub fn new_flags(
        x: i32,
        y: i32,
        w: u32,
        h: u32,
        title: &str,
        flags: &[WindowFlag],
    ) -> Option<Self> {
        //Insure that init has been called
        unsafe { init() };

        let mut window_async = false;
        //TODO: Use z-order
        let mut _back = false;
        let mut _front = false;
        let mut borderless = false;
        let mut resizable = false;
        //TODO: Transparent
        let mut _transparent = false;
        //TODO: Hide exit button
        let mut _unclosable = false;
        for &flag in flags.iter() {
            match flag {
                WindowFlag::Async => window_async = true,
                WindowFlag::Back => _back = true,
                WindowFlag::Front => _front = true,
                WindowFlag::Borderless => borderless = true,
                WindowFlag::Resizable => resizable = true,
                WindowFlag::Transparent => _transparent = true,
                WindowFlag::Unclosable => _unclosable = true,
            }
        }

        let mut builder = unsafe { &*VIDEO_CTX }.window(title, w, h);

        {
            builder.allow_highdpi();
        }

        if borderless {
            builder.borderless();
        }

        if resizable {
            builder.resizable();
        }

        if x >= 0 || y >= 0 {
            builder.position(x, y);
        }

        match builder.build() {
            Ok(window) => Some(Window {
                x,
                y,
                w,
                h,
                t: title.to_string(),
                window_async,
                mode: Cell::new(Mode::Blend),
                inner: window.into_canvas().software().build().unwrap(),
                mouse_relative: false,
                drop_content: RefCell::new(None),
            }),
            Err(_) => None,
        }
    }

    pub fn event_sender(&self) -> sdl2::event::EventSender {
        unsafe { &mut *SDL_CTX }.event().unwrap().event_sender()
    }

    pub fn clipboard(&self) -> String {
        let result = unsafe { &*VIDEO_CTX }.clipboard().clipboard_text();

        match result {
            Ok(value) => return value,
            Err(message) => println!("{}", message),
        }

        String::default()
    }

    pub fn set_clipboard(&mut self, text: &str) {
        let result = unsafe { &*VIDEO_CTX }.clipboard().set_clipboard_text(text);

        if let Err(message) = result {
            println!("{}", message);
        }
    }

    /// Pops the content of the last drop event from the window.
    pub fn pop_drop_content(&self) -> Option<String> {
        let result = self.drop_content.borrow().clone();
        *self.drop_content.borrow_mut() = None;

        result
    }

    pub fn sync_path(&mut self) {
        let window = self.inner.window();
        let pos = window.position();
        let size = window.size();
        let title = window.title();
        self.x = pos.0;
        self.y = pos.1;
        self.w = size.0;
        self.h = size.1;
        self.t = title.to_string();
    }

    /// Get x
    // TODO: Sync with window movements
    pub fn x(&self) -> i32 {
        self.x
    }

    /// Get y
    // TODO: Sync with window movements
    pub fn y(&self) -> i32 {
        self.y
    }

    /// Get title
    pub fn title(&self) -> String {
        self.t.clone()
    }

    /// Get async
    pub fn is_async(&self) -> bool {
        self.window_async
    }

    /// Set async
    pub fn set_async(&mut self, is_async: bool) {
        self.window_async = is_async;
    }

    /// Set cursor visibility
    pub fn set_mouse_cursor(&mut self, visible: bool) {
        unsafe { &mut *SDL_CTX }.mouse().show_cursor(visible);
    }

    /// Set mouse grabbing
    pub fn set_mouse_grab(&mut self, grab: bool) {
        unsafe { &mut *SDL_CTX }.mouse().capture(grab);
    }

    /// Set mouse relative mode
    pub fn set_mouse_relative(&mut self, relative: bool) {
        unsafe { &mut *SDL_CTX }
            .mouse()
            .set_relative_mouse_mode(relative);
        self.mouse_relative = relative;
    }

    /// Set position
    pub fn set_pos(&mut self, x: i32, y: i32) {
        self.inner.window_mut().set_position(
            sdl2::video::WindowPos::Positioned(x),
            sdl2::video::WindowPos::Positioned(y),
        );
        self.sync_path();
    }

    /// Set size
    pub fn set_size(&mut self, width: u32, height: u32) {
        let _ = self.inner.window_mut().set_size(width, height);
        self.sync_path();
    }

    /// Set title
    pub fn set_title(&mut self, title: &str) {
        let _ = self.inner.window_mut().set_title(title);
        self.sync_path();
    }

    fn convert_scancode(
        &self,
        scancode_option: Option<sdl2::keyboard::Scancode>,
        shift: bool,
    ) -> Option<(char, u8)> {
        if let Some(scancode) = scancode_option {
            match scancode {
                sdl2::keyboard::Scancode::A => Some((if shift { 'A' } else { 'a' }, K_A)),
                sdl2::keyboard::Scancode::B => Some((if shift { 'B' } else { 'b' }, K_B)),
                sdl2::keyboard::Scancode::C => Some((if shift { 'C' } else { 'c' }, K_C)),
                sdl2::keyboard::Scancode::D => Some((if shift { 'D' } else { 'd' }, K_D)),
                sdl2::keyboard::Scancode::E => Some((if shift { 'E' } else { 'e' }, K_E)),
                sdl2::keyboard::Scancode::F => Some((if shift { 'F' } else { 'f' }, K_F)),
                sdl2::keyboard::Scancode::G => Some((if shift { 'G' } else { 'g' }, K_G)),
                sdl2::keyboard::Scancode::H => Some((if shift { 'H' } else { 'h' }, K_H)),
                sdl2::keyboard::Scancode::I => Some((if shift { 'I' } else { 'i' }, K_I)),
                sdl2::keyboard::Scancode::J => Some((if shift { 'J' } else { 'j' }, K_J)),
                sdl2::keyboard::Scancode::K => Some((if shift { 'K' } else { 'k' }, K_K)),
                sdl2::keyboard::Scancode::L => Some((if shift { 'L' } else { 'l' }, K_L)),
                sdl2::keyboard::Scancode::M => Some((if shift { 'M' } else { 'm' }, K_M)),
                sdl2::keyboard::Scancode::N => Some((if shift { 'N' } else { 'n' }, K_N)),
                sdl2::keyboard::Scancode::O => Some((if shift { 'O' } else { 'o' }, K_O)),
                sdl2::keyboard::Scancode::P => Some((if shift { 'P' } else { 'p' }, K_P)),
                sdl2::keyboard::Scancode::Q => Some((if shift { 'Q' } else { 'q' }, K_Q)),
                sdl2::keyboard::Scancode::R => Some((if shift { 'R' } else { 'r' }, K_R)),
                sdl2::keyboard::Scancode::S => Some((if shift { 'S' } else { 's' }, K_S)),
                sdl2::keyboard::Scancode::T => Some((if shift { 'T' } else { 't' }, K_T)),
                sdl2::keyboard::Scancode::U => Some((if shift { 'U' } else { 'u' }, K_U)),
                sdl2::keyboard::Scancode::V => Some((if shift { 'V' } else { 'v' }, K_V)),
                sdl2::keyboard::Scancode::W => Some((if shift { 'W' } else { 'w' }, K_W)),
                sdl2::keyboard::Scancode::X => Some((if shift { 'X' } else { 'x' }, K_X)),
                sdl2::keyboard::Scancode::Y => Some((if shift { 'Y' } else { 'y' }, K_Y)),
                sdl2::keyboard::Scancode::Z => Some((if shift { 'Z' } else { 'z' }, K_Z)),
                sdl2::keyboard::Scancode::Num0 => Some((if shift { ')' } else { '0' }, K_0)),
                sdl2::keyboard::Scancode::Num1 => Some((if shift { '!' } else { '1' }, K_1)),
                sdl2::keyboard::Scancode::Num2 => Some((if shift { '@' } else { '2' }, K_2)),
                sdl2::keyboard::Scancode::Num3 => Some((if shift { '#' } else { '3' }, K_3)),
                sdl2::keyboard::Scancode::Num4 => Some((if shift { '$' } else { '4' }, K_4)),
                sdl2::keyboard::Scancode::Num5 => Some((if shift { '%' } else { '5' }, K_5)),
                sdl2::keyboard::Scancode::Num6 => Some((if shift { '^' } else { '6' }, K_6)),
                sdl2::keyboard::Scancode::Num7 => Some((if shift { '&' } else { '7' }, K_7)),
                sdl2::keyboard::Scancode::Num8 => Some((if shift { '*' } else { '8' }, K_8)),
                sdl2::keyboard::Scancode::Num9 => Some((if shift { '(' } else { '9' }, K_9)),
                sdl2::keyboard::Scancode::Grave => Some((if shift { '~' } else { '`' }, K_TICK)),
                sdl2::keyboard::Scancode::Minus => Some((if shift { '_' } else { '-' }, K_MINUS)),
                sdl2::keyboard::Scancode::Equals => Some((if shift { '+' } else { '=' }, K_EQUALS)),
                sdl2::keyboard::Scancode::LeftBracket => {
                    Some((if shift { '{' } else { '[' }, K_BRACE_OPEN))
                }
                sdl2::keyboard::Scancode::RightBracket => {
                    Some((if shift { '}' } else { ']' }, K_BRACE_CLOSE))
                }
                sdl2::keyboard::Scancode::Backslash => {
                    Some((if shift { '|' } else { '\\' }, K_BACKSLASH))
                }
                sdl2::keyboard::Scancode::Semicolon => {
                    Some((if shift { ':' } else { ';' }, K_SEMICOLON))
                }
                sdl2::keyboard::Scancode::Apostrophe => {
                    Some((if shift { '"' } else { '\'' }, K_QUOTE))
                }
                sdl2::keyboard::Scancode::Comma => Some((if shift { '<' } else { ',' }, K_COMMA)),
                sdl2::keyboard::Scancode::Period => Some((if shift { '>' } else { '.' }, K_PERIOD)),
                sdl2::keyboard::Scancode::Slash => Some((if shift { '?' } else { '/' }, K_SLASH)),
                sdl2::keyboard::Scancode::Space => Some((' ', K_SPACE)),
                sdl2::keyboard::Scancode::Backspace => Some(('\0', K_BKSP)),
                sdl2::keyboard::Scancode::Tab => Some(('\t', K_TAB)),
                sdl2::keyboard::Scancode::LCtrl => Some(('\0', K_CTRL)),
                sdl2::keyboard::Scancode::RCtrl => Some(('\0', K_CTRL)),
                sdl2::keyboard::Scancode::LAlt => Some(('\0', K_ALT)),
                sdl2::keyboard::Scancode::RAlt => Some(('\0', K_ALT)),
                sdl2::keyboard::Scancode::Return => Some(('\n', K_ENTER)),
                sdl2::keyboard::Scancode::Escape => Some(('\x1B', K_ESC)),
                sdl2::keyboard::Scancode::F1 => Some(('\0', K_F1)),
                sdl2::keyboard::Scancode::F2 => Some(('\0', K_F2)),
                sdl2::keyboard::Scancode::F3 => Some(('\0', K_F3)),
                sdl2::keyboard::Scancode::F4 => Some(('\0', K_F4)),
                sdl2::keyboard::Scancode::F5 => Some(('\0', K_F5)),
                sdl2::keyboard::Scancode::F6 => Some(('\0', K_F6)),
                sdl2::keyboard::Scancode::F7 => Some(('\0', K_F7)),
                sdl2::keyboard::Scancode::F8 => Some(('\0', K_F8)),
                sdl2::keyboard::Scancode::F9 => Some(('\0', K_F9)),
                sdl2::keyboard::Scancode::F10 => Some(('\0', K_F10)),
                sdl2::keyboard::Scancode::Home => Some(('\0', K_HOME)),
                sdl2::keyboard::Scancode::LGui => Some(('\0', K_HOME)),
                sdl2::keyboard::Scancode::Up => Some(('\0', K_UP)),
                sdl2::keyboard::Scancode::PageUp => Some(('\0', K_PGUP)),
                sdl2::keyboard::Scancode::Left => Some(('\0', K_LEFT)),
                sdl2::keyboard::Scancode::Right => Some(('\0', K_RIGHT)),
                sdl2::keyboard::Scancode::End => Some(('\0', K_END)),
                sdl2::keyboard::Scancode::Down => Some(('\0', K_DOWN)),
                sdl2::keyboard::Scancode::PageDown => Some(('\0', K_PGDN)),
                sdl2::keyboard::Scancode::Delete => Some(('\0', K_DEL)),
                sdl2::keyboard::Scancode::F11 => Some(('\0', K_F11)),
                sdl2::keyboard::Scancode::F12 => Some(('\0', K_F12)),
                sdl2::keyboard::Scancode::LShift => Some(('\0', K_LEFT_SHIFT)),
                sdl2::keyboard::Scancode::RShift => Some(('\0', K_RIGHT_SHIFT)),
                _ => None,
            }
        } else {
            None
        }
    }

    fn get_mouse_position(&self) -> (i32, i32) {
        let mouse_state = unsafe { &mut *EVENT_PUMP }.mouse_state();
        (mouse_state.x(), mouse_state.y())
    }

    fn convert_event(&self, event: sdl2::event::Event) -> Vec<Event> {
        let mut events = Vec::new();

        let button_event = || -> Event {
            let mouse = unsafe { &mut *EVENT_PUMP }.mouse_state();
            ButtonEvent {
                left: mouse.left(),
                middle: mouse.middle(),
                right: mouse.right(),
            }
            .to_event()
        };

        let mods = unsafe { &mut *SDL_CTX }.keyboard().mod_state();
        let shift = mods.contains(sdl2::keyboard::Mod::CAPSMOD)
            || mods.contains(sdl2::keyboard::Mod::LSHIFTMOD)
            || mods.contains(sdl2::keyboard::Mod::RSHIFTMOD);

        match event {
            sdl2::event::Event::RenderTargetsReset { .. } => {
                events.push(Event::new());
            }
            sdl2::event::Event::Window { win_event, .. } => match win_event {
                sdl2::event::WindowEvent::Moved(x, y) => events.push(MoveEvent { x, y }.to_event()),
                sdl2::event::WindowEvent::Resized(w, h) => events.push(
                    ResizeEvent {
                        width: w as u32,
                        height: h as u32,
                    }
                    .to_event(),
                ),
                sdl2::event::WindowEvent::FocusGained => {
                    events.push(FocusEvent { focused: true }.to_event())
                }
                sdl2::event::WindowEvent::FocusLost => {
                    events.push(FocusEvent { focused: false }.to_event())
                }
                sdl2::event::WindowEvent::Enter => {
                    events.push(HoverEvent { entered: true }.to_event())
                }
                sdl2::event::WindowEvent::Leave => {
                    events.push(HoverEvent { entered: false }.to_event())
                }
                sdl2::event::WindowEvent::None => events.push(Event::new()),
                _ => (),
            },
            sdl2::event::Event::ClipboardUpdate { .. } => {
                events.push(ClipboardUpdateEvent.to_event())
            }
            sdl2::event::Event::MouseMotion {
                x, y, xrel, yrel, ..
            } => {
                if self.mouse_relative {
                    events.push(MouseRelativeEvent { dx: xrel, dy: yrel }.to_event())
                } else {
                    events.push(MouseEvent { x, y }.to_event())
                }
            }
            sdl2::event::Event::MouseButtonDown { .. } => events.push(button_event()),
            sdl2::event::Event::MouseButtonUp { .. } => events.push(button_event()),
            sdl2::event::Event::MouseWheel { x, y, .. } => {
                events.push(ScrollEvent { x, y }.to_event())
            }
            sdl2::event::Event::TextInput { text, .. } => {
                for character in text.chars() {
                    events.push(TextInputEvent { character }.to_event());
                }
            }
            sdl2::event::Event::KeyDown { scancode, .. } => {
                if let Some(code) = self.convert_scancode(scancode, shift) {
                    events.push(
                        KeyEvent {
                            character: code.0,
                            scancode: code.1,
                            pressed: true,
                        }
                        .to_event(),
                    );
                }
            }
            sdl2::event::Event::DropFile { filename, .. } => {
                *self.drop_content.borrow_mut() = Some(filename);

                let (x, y) = self.get_mouse_position();

                events.push(MouseEvent { x, y }.to_event());

                events.push(DropEvent { kind: DROP_FILE }.to_event())
            }
            sdl2::event::Event::DropText { filename, .. } => {
                *self.drop_content.borrow_mut() = Some(filename);

                let (x, y) = self.get_mouse_position();

                events.push(MouseEvent { x, y }.to_event());
                events.push(DropEvent { kind: DROP_TEXT }.to_event())
            }
            sdl2::event::Event::KeyUp { scancode, .. } => {
                if let Some(code) = self.convert_scancode(scancode, shift) {
                    events.push(
                        KeyEvent {
                            character: code.0,
                            scancode: code.1,
                            pressed: false,
                        }
                        .to_event(),
                    );
                }
            }
            sdl2::event::Event::Quit { .. } => events.push(QuitEvent.to_event()),
            _ => (),
        }

        events
    }

    /// Blocking iterator over events
    pub fn events(&mut self) -> EventIter {
        let mut iter = EventIter {
            events: [Event::new(); 16],
            i: 0,
            count: 0,
        };

        if !self.window_async {
            let event = unsafe { &mut *EVENT_PUMP }.wait_event();
            if let sdl2::event::Event::Window { .. } = event {
                self.sync_path();
            }
            for converted_event in self.convert_event(event) {
                if iter.count < iter.events.len() {
                    iter.events[iter.count] = converted_event;
                    iter.count += 1;
                } else {
                    break;
                }
            }
        }

        while let Some(event) = unsafe { &mut *EVENT_PUMP }.poll_event() {
            if let sdl2::event::Event::Window { .. } = event {
                self.sync_path();
            }
            for converted_event in self.convert_event(event) {
                if iter.count < iter.events.len() {
                    iter.events[iter.count] = converted_event;
                    iter.count += 1;
                } else {
                    break;
                }
            }
            if iter.count + 2 < iter.events.len() {
                break;
            }
        }

        iter
    }

    /// Returns the id
    pub fn id(&self) -> u32 {
        self.inner.window().id()
    }
}

/// Event iterator
pub struct EventIter {
    events: [Event; 16],
    i: usize,
    count: usize,
}

impl Iterator for EventIter {
    type Item = Event;
    fn next(&mut self) -> Option<Event> {
        if self.i < self.count {
            if let Some(event) = self.events.get(self.i) {
                self.i += 1;
                Some(*event)
            } else {
                None
            }
        } else {
            None
        }
    }
}

// General surface
pub struct Surface {
    /// The width of the surface
    w: u32,
    /// The height of the surface
    h: u32,
    /// Drawing mode
    mode: Cell<Mode>,
    /// The surface object
    file_opt: Option<sdl2::surface::Surface<'static>>,
}

impl Renderer for Surface {
    /// Get width
    fn width(&self) -> u32 {
        self.w
    }

    /// Get height
    fn height(&self) -> u32 {
        self.h
    }

    /// Access pixel buffer
    fn data(&self) -> &[Color] {
        let raw = self.file().without_lock().unwrap();
        unsafe {
            let raw_pixels = core::ptr::from_ref(raw) as *const Color;
            std::slice::from_raw_parts(raw_pixels, raw.len() / 4)
        }
    }

    /// Access pixel buffer mutably
    fn data_mut(&mut self) -> &mut [Color] {
        let file = self.file_opt.as_mut().unwrap();
        let raw = file.without_lock_mut().unwrap();
        unsafe {
            let raw_pixels = core::ptr::from_mut(raw) as *mut Color;
            std::slice::from_raw_parts_mut(raw_pixels, raw.len() / 4)
        }
    }

    /// Flip the hardware buffer
    fn sync(&mut self) -> bool {
        true
    }

    /// Update the software buffer
    fn update(&mut self) -> bool {
        true
    }

    /// Update the specified software buffer region
    fn update_rects(&mut self, _rects: &[(i32, i32, u32, u32)]) -> bool {
        true
    }

    /// Set/get mode
    fn mode(&self) -> &Cell<Mode> {
        &self.mode
    }
}

impl Surface {
    /// Create a new surface
    pub fn new(w: u32, h: u32) -> Option<Self> {
        Surface::new_flags(w, h, &[])
    }

    /// Create a new surface with flags
    pub fn new_flags(w: u32, h: u32, _flags: &[SurfaceFlag]) -> Option<Self> {
        let mut surface = Surface {
            w,
            h,
            mode: Cell::new(Mode::Blend),
            file_opt: None,
        };
        unsafe {
            surface.remap();
        }
        if surface.file_opt.is_some() {
            Some(surface)
        } else {
            None
        }
    }

    fn file(&self) -> &sdl2::surface::Surface<'static> {
        self.file_opt.as_ref().unwrap()
    }

    /// Set size
    pub fn set_size(&mut self, width: u32, height: u32) {
        // SAFETY: We hold mut here, so this is safe
        unsafe {
            self.unmap();
        }
        self.w = width;
        self.h = height;
        unsafe {
            self.remap();
        }
    }

    unsafe fn remap(&mut self) {
        if let Ok(shm) =
            sdl2::surface::Surface::new(self.w, self.h, sdl2::pixels::PixelFormatEnum::ARGB8888)
        {
            self.file_opt = Some(shm)
        }
    }

    unsafe fn unmap(&mut self) {
        self.file_opt.take();
    }
}

impl Drop for Surface {
    fn drop(&mut self) {
        unsafe {
            self.unmap();
        }
    }
}

/*
impl AsRawFd for Surface {
    fn as_raw_fd(&self) -> RawFd {
        self.file().as_raw_fd()
    }
}

impl FromRawFd for Surface {
    unsafe fn from_raw_fd(fd: RawFd) -> Surface {
        let mut window = Surface {
            w: 0,
            h: 0,
            mode: Cell::new(Mode::Blend),
            file_opt: Some(File::from_raw_fd(fd)),
        };
        window.remap();
        window
    }
}

impl IntoRawFd for Surface {
    fn into_raw_fd(mut self) -> RawFd {
        self.file_opt.take().unwrap().into_raw_fd()
    }
}
*/