deft-winit 0.36.0

Cross-platform window creation library.
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
use crate::cursor::Cursor;
use crate::error::{ExternalError, NotSupportedError};
use crate::event::{Event, WindowEvent};
use crate::icon::Icon;
use crate::platform_impl::emscripten::event::mouse::mouse_callback;
use crate::platform_impl::emscripten::event::window::window_resize_callback;
use crate::platform_impl::emscripten::event_hub::EventHub;
use crate::platform_impl::emscripten::ffi::EM_CALLBACK_THREAD_CONTEXT_CALLING_THREAD;
use crate::platform_impl::emscripten::{
    bindings, em_try, ffi, BODY_NAME, DOCUMENT_NAME, WINDOW_NAME,
};
use crate::platform_impl::platform::get_hidpi_factor;
use crate::platform_impl::{ActiveEventLoop, Fullscreen, OsError};
use crate::window::{
    CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes,
    WindowButtons, WindowLevel,
};
use dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size};
use std::collections::VecDeque;
use std::ffi::CString;
use std::iter::Empty;
use std::os::raw::c_char;
use std::ptr::null_mut;
use deft_emscripten_sys::emscripten_run_script;
use crate::platform_impl::emscripten::bindings::emscripten_get_element_css_size;
use crate::platform_impl::emscripten::event::keyboard::keyboard_callback;
use crate::platform_impl::emscripten::monitor::MonitorHandle;

#[allow(unused)]
#[derive(Clone, Debug, Default)]
pub struct PlatformSpecificWindowAttributes {
    pub(crate) prevent_default: bool,
    pub(crate) focusable: bool,
    pub(crate) append: bool,
}

#[derive(Clone, Default)]
pub struct PlatformSpecificWindowBuilderAttributes;

unsafe impl Send for PlatformSpecificWindowBuilderAttributes {}
unsafe impl Sync for PlatformSpecificWindowBuilderAttributes {}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WindowId(pub usize);

impl Into<u64> for WindowId {
    fn into(self) -> u64 {
        self.0 as u64
    }
}

impl Into<WindowId> for u64 {
    fn into(self) -> WindowId {
        WindowId(self as usize)
    }
}

impl WindowId {
    pub const fn dummy() -> Self {
        WindowId(0)
    }
}

pub struct Inner {
    id: WindowId,
}

pub struct Window {
    inner: Inner,
}

impl MonitorHandle {
    pub fn scale_factor(&self) -> f64 {
        get_hidpi_factor()
    }

    pub fn position(&self) -> PhysicalPosition<i32> {
        unreachable!()
    }

    pub fn name(&self) -> Option<String> {
        unreachable!()
    }

    pub fn refresh_rate_millihertz(&self) -> Option<u32> {
        unreachable!()
    }

    pub fn size(&self) -> PhysicalSize<u32> {
        unreachable!()
    }

    pub fn video_modes(&self) -> Empty<VideoModeHandle> {
        unreachable!()
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct VideoModeHandle;

impl VideoModeHandle {
    pub fn size(&self) -> PhysicalSize<u32> {
        unreachable!();
    }

    pub fn bit_depth(&self) -> u16 {
        unreachable!();
    }

    pub fn refresh_rate_millihertz(&self) -> u32 {
        unreachable!();
    }

    pub fn monitor(&self) -> MonitorHandle {
        unreachable!();
    }
}

impl Window {
    pub fn new(
        _active_event_loop: &ActiveEventLoop,
        _attribs: WindowAttributes,
    ) -> Result<Window, crate::error::OsError> {
        unsafe {
            let script = CString::new(include_bytes!("init-input.js")).unwrap();
            emscripten_run_script(script.as_ptr());
        }
        let window = Window { inner: Inner { id: WindowId::dummy() } };

        // TODO: set up more event callbacks
        let user_data = null_mut();
        unsafe {
            let mut width = 0.0;
            let mut height = 0.0;
            bindings::emscripten_get_element_css_size(
                BODY_NAME.as_ptr() as *const c_char,
                &mut width as *mut _,
                &mut height as *mut _,
            );
            // println!("window size: {:?}", (width, height));
            let size = LogicalSize::new(width, height).to_physical(get_hidpi_factor());
            let event = Event::WindowEvent {
                window_id: crate::window::WindowId(WindowId(0)),
                event: WindowEvent::Resized(size),
            };
            EventHub::send_event(event);

            em_try(bindings::emscripten_set_resize_callback_on_thread(
                WINDOW_NAME.as_ptr() as *const c_char,
                user_data,
                false,
                Some(window_resize_callback),
                EM_CALLBACK_THREAD_CONTEXT_CALLING_THREAD as u32,
            ))
            .unwrap();
            em_try(bindings::emscripten_set_mousemove_callback_on_thread(
                DOCUMENT_NAME.as_ptr() as *const c_char,
                user_data,
                false,
                Some(mouse_callback),
                ffi::EM_CALLBACK_THREAD_CONTEXT_CALLING_THREAD,
            ))
            .map_err(|e| OsError(format!("emscripten error: {}", e)))
            .unwrap();
            em_try(bindings::emscripten_set_mousedown_callback_on_thread(
                DOCUMENT_NAME.as_ptr() as *const c_char,
                user_data,
                false,
                Some(mouse_callback),
                ffi::EM_CALLBACK_THREAD_CONTEXT_CALLING_THREAD,
            ))
            .map_err(|e| OsError(format!("emscripten error: {}", e)))
            .unwrap();
            em_try(bindings::emscripten_set_mouseup_callback_on_thread(
                DOCUMENT_NAME.as_ptr() as *const c_char,
                user_data,
                false,
                Some(mouse_callback),
                ffi::EM_CALLBACK_THREAD_CONTEXT_CALLING_THREAD,
            ))
            .map_err(|e| OsError(format!("emscripten error: {}", e)))
            .unwrap();

            em_try(bindings::emscripten_set_keydown_callback_on_thread(
                DOCUMENT_NAME.as_ptr() as *const c_char,
                user_data,
                false,
                Some(keyboard_callback),
                ffi::EM_CALLBACK_THREAD_CONTEXT_CALLING_THREAD as u32,
            ))
            .map_err(|e| OsError(format!("emscripten error: {}", e)))
            .unwrap();
            em_try(bindings::emscripten_set_keyup_callback_on_thread(
                DOCUMENT_NAME.as_ptr() as *const c_char,
                user_data,
                false,
                Some(keyboard_callback),
                ffi::EM_CALLBACK_THREAD_CONTEXT_CALLING_THREAD as u32,
            ))
            .map_err(|e| OsError(format!("emscripten error: {}", e)))
            .unwrap();
        }
        //TODO support fullscreen attr
        Ok(window)
    }

    pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Inner) + Send + 'static) {
        f(&self.inner);
    }

    pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Inner) -> R + Send) -> R {
        f(&self.inner)
    }

    pub(crate) fn prevent_default(&self) -> bool {
        //TODO impl
        false
    }

    pub(crate) fn set_prevent_default(&self, _prevent_default: bool) {
        //TODO impl
    }

    #[cfg(feature = "rwh_06")]
    #[inline]
    pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
        Err(rwh_06::HandleError::Unavailable)
    }

    #[cfg(feature = "rwh_06")]
    #[inline]
    pub(crate) fn raw_display_handle_rwh_06(
        &self,
    ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
        Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new()))
    }
}

impl Inner {
    pub fn set_title(&self, _title: &str) {}

    pub fn set_transparent(&self, _transparent: bool) {}

    pub fn set_blur(&self, _blur: bool) {}

    pub fn set_visible(&self, _visible: bool) {
        // Intentionally a no-op
    }

    #[inline]
    pub fn is_visible(&self) -> Option<bool> {
        None
    }

    pub fn request_redraw(&self) {
        EventHub::send_event(Event::WindowEvent {
            window_id: crate::window::WindowId(self.id),
            event: WindowEvent::RedrawRequested,
        });
    }

    pub fn pre_present_notify(&self) {}

    pub fn pointer_position(&self) -> Option<PhysicalPosition<i32>> {
        None
    }

    pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
        Err(NotSupportedError::new())
    }

    pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
        // Note: the canvas element has no window decorations, so this is equal to `outer_position`.
        self.outer_position()
    }

    pub fn set_outer_position(&self, _position: Position) {
        //TODO
    }

    #[inline]
    pub fn inner_size(&self) -> PhysicalSize<u32> {
        unsafe {
            let mut width = 0.0;
            let mut height = 0.0;
            emscripten_get_element_css_size(
                BODY_NAME.as_ptr() as *const c_char,
                &mut width as *mut _,
                &mut height as *mut _,
            );
            LogicalSize::new(width as u32, height as u32).to_physical(get_hidpi_factor())
        }
    }

    #[inline]
    pub fn outer_size(&self) -> PhysicalSize<u32> {
        // Note: the canvas element has no window decorations, so this is equal to `inner_size`.
        self.inner_size()
    }

    #[inline]
    pub fn request_inner_size(&self, _size: Size) -> Option<PhysicalSize<u32>> {
        None
    }

    #[inline]
    pub fn set_min_inner_size(&self, _dimensions: Option<Size>) {
        //TODO impl
    }

    #[inline]
    pub fn set_max_inner_size(&self, _dimensions: Option<Size>) {
        //TODO impl
    }

    #[inline]
    pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> {
        None
    }

    #[inline]
    pub fn set_resize_increments(&self, _increments: Option<Size>) {
        // Intentionally a no-op: users can't resize canvas elements
    }

    #[inline]
    pub fn set_resizable(&self, _resizable: bool) {
        // Intentionally a no-op: users can't resize canvas elements
    }

    pub fn is_resizable(&self) -> bool {
        true
    }

    #[inline]
    pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {}

    #[inline]
    pub fn enabled_buttons(&self) -> WindowButtons {
        WindowButtons::all()
    }

    #[inline]
    pub fn scale_factor(&self) -> f64 {
        get_hidpi_factor()
    }

    #[inline]
    pub fn set_cursor(&self, _cursor: Cursor) {
        //TODO impl
    }

    #[inline]
    pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> {
        Err(ExternalError::NotSupported(NotSupportedError::new()))
    }

    #[inline]
    pub fn set_cursor_grab(&self, _mode: CursorGrabMode) -> Result<(), ExternalError> {
        //TODO impl
        Err(ExternalError::NotSupported(NotSupportedError::new()))
    }

    #[inline]
    pub fn set_cursor_visible(&self, _visible: bool) {
        //TODO impl
    }

    #[inline]
    pub fn drag_window(&self) -> Result<(), ExternalError> {
        Err(ExternalError::NotSupported(NotSupportedError::new()))
    }

    #[inline]
    pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> {
        Err(ExternalError::NotSupported(NotSupportedError::new()))
    }

    #[inline]
    pub fn show_window_menu(&self, _position: Position) {}

    #[inline]
    pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), ExternalError> {
        Err(ExternalError::NotSupported(NotSupportedError::new()))
    }

    #[inline]
    pub fn set_minimized(&self, _minimized: bool) {
        // Intentionally a no-op, as canvases cannot be 'minimized'
    }

    #[inline]
    pub fn is_minimized(&self) -> Option<bool> {
        // Canvas cannot be 'minimized'
        Some(false)
    }

    #[inline]
    pub fn set_maximized(&self, _maximized: bool) {
        // Intentionally a no-op, as canvases cannot be 'maximized'
    }

    #[inline]
    pub fn is_maximized(&self) -> bool {
        // Canvas cannot be 'maximized'
        false
    }

    #[inline]
    pub(crate) fn fullscreen(&self) -> Option<Fullscreen> {
        //TODO impl
        None
    }

    #[inline]
    pub(crate) fn set_fullscreen(&self, _fullscreen: Option<Fullscreen>) {
        //TODO impl
    }

    #[inline]
    pub fn set_decorations(&self, _decorations: bool) {
        // Intentionally a no-op, no canvas decorations
    }

    pub fn is_decorated(&self) -> bool {
        true
    }

    #[inline]
    pub fn set_window_level(&self, _level: WindowLevel) {
        // Intentionally a no-op, no window ordering
    }

    #[inline]
    pub fn set_window_icon(&self, _window_icon: Option<Icon>) {
        // Currently an intentional no-op
    }

    #[inline]
    pub fn set_ime_cursor_area(&self, position: Position, size: Size) {
        // Currently a no-op as it does not seem there is good support for this on web
        let hidpi_factor = get_hidpi_factor();
        let position = position.to_logical::<i32>(hidpi_factor);
        let size = size.to_logical::<i32>(hidpi_factor);
        unsafe {
            let code = format!("Module.winit.setImeCursor({}, {}, {}, {})", position.x, position.y, size.width, size.height);
            let script = CString::new(code).unwrap();
            emscripten_run_script(script.as_ptr());
        }
    }

    #[inline]
    pub fn set_ime_allowed(&self, allowed: bool) {
        unsafe {
            let code = if allowed {
                "Module.winit.allowIme(true)"
            } else {
                "Module.winit.allowIme(false)"
            };
            let script = CString::new(code).unwrap();
            emscripten_run_script(script.as_ptr());
        }
    }

    #[inline]
    pub fn set_ime_purpose(&self, _purpose: ImePurpose) {
        // Currently not implemented
    }

    #[inline]
    pub fn commit_ime(&self) {}

    #[inline]
    pub fn focus_window(&self) {
        // let _ = self.canvas.borrow().raw().focus();
    }

    #[inline]
    pub fn request_user_attention(&self, _request_type: Option<UserAttentionType>) {
        // Currently an intentional no-op
    }

    #[inline]
    pub fn current_monitor(&self) -> Option<MonitorHandle> {
        None
    }

    #[inline]
    pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
        VecDeque::new()
    }

    #[inline]
    pub fn primary_monitor(&self) -> Option<MonitorHandle> {
        None
    }

    #[inline]
    pub fn id(&self) -> WindowId {
        self.id
    }

    #[cfg(feature = "rwh_04")]
    #[inline]
    pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle {
        let mut window_handle = rwh_04::WebHandle::empty();
        window_handle.id = self.id.0;
        rwh_04::RawWindowHandle::Web(window_handle)
    }

    #[cfg(feature = "rwh_05")]
    #[inline]
    pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle {
        let mut window_handle = rwh_05::WebWindowHandle::empty();
        window_handle.id = self.id.0 as u32;
        rwh_05::RawWindowHandle::Web(window_handle)
    }

    #[cfg(feature = "rwh_05")]
    #[inline]
    pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
        rwh_05::RawDisplayHandle::Web(rwh_05::WebDisplayHandle::empty())
    }

    #[inline]
    pub fn set_theme(&self, _theme: Option<Theme>) {}

    #[inline]
    pub fn theme(&self) -> Option<Theme> {
        //TODO impl
        None
    }

    pub fn set_content_protected(&self, _protected: bool) {}

    #[inline]
    pub fn has_focus(&self) -> bool {
        //TODO impl
        true
    }

    pub fn title(&self) -> String {
        String::new()
    }

    pub fn reset_dead_keys(&self) {
        // Not supported
    }
}

impl Drop for Window {
    fn drop(&mut self) {
        //TODO release event bindings?
    }
}