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
use crate::DEFAULT_DPI;
use crate::{
    api::*,
    context::*,
    event::EventHandler,
    geometry::*,
    procedure::{window_proc, UserMessage},
    resource::*,
};
use raw_window_handle::{windows::WindowsHandle, HasRawWindowHandle, RawWindowHandle};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, Once, RwLock};
use winapi::shared::{minwindef::*, windef::*};
use winapi::um::{
    libloaderapi::GetModuleHandleW,
    shellapi::*,
    wingdi::{GetStockObject, WHITE_BRUSH},
    winuser::*,
};

#[derive(Clone, PartialEq, Eq)]
pub(crate) struct WindowHandle(HWND);

unsafe impl Send for WindowHandle {}
unsafe impl Sync for WindowHandle {}

/// A window style and the borderless window style.
pub trait Style {
    fn value(&self) -> DWORD;

    fn is_borderless(&self) -> bool {
        self.value() == WS_POPUP
    }
}

/// Represents the borderless window style.
pub struct BorderlessStyle;

impl Style for BorderlessStyle {
    fn value(&self) -> DWORD {
        WS_POPUP
    }
}

/// Represents a window style.
pub struct WindowStyle(DWORD);

impl WindowStyle {
    pub fn default() -> Self {
        Self(
            WS_OVERLAPPED
                | WS_CAPTION
                | WS_SYSMENU
                | WS_THICKFRAME
                | WS_MINIMIZEBOX
                | WS_MAXIMIZEBOX,
        )
    }

    pub fn borderless() -> BorderlessStyle {
        BorderlessStyle
    }

    pub fn resizable(mut self, resizable: bool) -> Self {
        if resizable {
            self.0 |= WS_THICKFRAME;
        } else {
            self.0 &= !WS_THICKFRAME;
        }
        self
    }

    pub fn has_minimize_box(mut self, has_minimize_box: bool) -> Self {
        if has_minimize_box {
            self.0 |= WS_MINIMIZEBOX;
        } else {
            self.0 &= !WS_MINIMIZEBOX;
        }
        self
    }

    pub fn has_maximize_box(mut self, has_maximize_box: bool) -> Self {
        if has_maximize_box {
            self.0 |= WS_MAXIMIZEBOX;
        } else {
            self.0 &= !WS_MAXIMIZEBOX;
        }
        self
    }

    pub fn is_borderless(&self) -> bool {
        self.value() == WS_POPUP
    }
}

impl Style for WindowStyle {
    fn value(&self) -> DWORD {
        self.0
    }
}

/// The object that allows you to build windows.
pub struct WindowBuilder<Ti = (), S = ()> {
    title: Ti,
    position: ScreenPosition,
    inner_size: S,
    visibility: bool,
    style: DWORD,
    visible_ime_composition_window: bool,
    visible_ime_candidate_window: bool,
    parent: Option<Window>,
    children: Vec<Window>,
    accept_drag_files: bool,
    icon: Option<Icon>,
}

impl WindowBuilder<(), ()> {
    pub fn new() -> WindowBuilder<&'static str, LogicalSize<u32>> {
        WindowBuilder {
            title: "",
            position: ScreenPosition::new(0, 0),
            inner_size: LogicalSize::new(640, 480),
            style: WindowStyle::default().value(),
            visibility: true,
            visible_ime_composition_window: true,
            visible_ime_candidate_window: true,
            parent: None,
            children: Vec::new(),
            accept_drag_files: false,
            icon: None,
        }
    }
}

impl<Ti, S> WindowBuilder<Ti, S> {
    pub fn title<T>(self, title: T) -> WindowBuilder<T, S> {
        WindowBuilder {
            title,
            position: self.position,
            inner_size: self.inner_size,
            style: self.style,
            visibility: self.visibility,
            visible_ime_composition_window: self.visible_ime_composition_window,
            visible_ime_candidate_window: self.visible_ime_candidate_window,
            parent: self.parent,
            children: self.children,
            accept_drag_files: self.accept_drag_files,
            icon: self.icon,
        }
    }

    pub fn position(mut self, position: ScreenPosition) -> Self {
        self.position = position;
        self
    }

    pub fn inner_size<T>(self, inner_size: T) -> WindowBuilder<Ti, T> {
        WindowBuilder {
            title: self.title,
            position: self.position,
            inner_size,
            style: self.style,
            visibility: self.visibility,
            visible_ime_composition_window: self.visible_ime_composition_window,
            visible_ime_candidate_window: self.visible_ime_candidate_window,
            parent: self.parent,
            children: self.children,
            accept_drag_files: self.accept_drag_files,
            icon: self.icon,
        }
    }

    pub fn style(mut self, style: impl Style) -> WindowBuilder<Ti, S> {
        self.style = style.value();
        self
    }

    pub fn visible(mut self, visibility: bool) -> WindowBuilder<Ti, S> {
        self.visibility = visibility;
        self
    }

    pub fn visible_ime_composition_window(
        mut self,
        show_ime_composition_window: bool,
    ) -> WindowBuilder<Ti, S> {
        self.visible_ime_composition_window = show_ime_composition_window;
        self
    }

    pub fn visible_ime_candidate_window(
        mut self,
        show_ime_cadidate_window: bool,
    ) -> WindowBuilder<Ti, S> {
        self.visible_ime_candidate_window = show_ime_cadidate_window;
        self
    }

    pub fn parent(mut self, parent: &Window) -> WindowBuilder<Ti, S> {
        self.parent = Some(parent.clone());
        self
    }

    pub fn child(mut self, child: &Window) -> WindowBuilder<Ti, S> {
        self.children.push(child.clone());
        self
    }

    pub fn children(mut self, children: &[&Window]) -> WindowBuilder<Ti, S> {
        for &c in children {
            self.children.push(c.clone());
        }
        self
    }

    pub fn accept_drag_files(mut self, enabled: bool) -> WindowBuilder<Ti, S> {
        self.accept_drag_files = enabled;
        self
    }

    pub fn icon(mut self, icon: Icon) -> WindowBuilder<Ti, S> {
        self.icon = Some(icon);
        self
    }
}

fn window_class_name() -> &'static Vec<u16> {
    static mut WINDOW_CLASS_NAME: Vec<u16> = Vec::new();
    static REGISTER: Once = Once::new();
    unsafe {
        REGISTER.call_once(|| {
            let class_name = "curun_window_class"
                .encode_utf16()
                .chain(Some(0))
                .collect::<Vec<_>>();
            WINDOW_CLASS_NAME = class_name;
        });
        &WINDOW_CLASS_NAME
    }
}

pub(crate) fn register_class<T: EventHandler + 'static>() {
    unsafe {
        let class_name = window_class_name();
        let wc = WNDCLASSEXW {
            cbSize: std::mem::size_of::<WNDCLASSEXW>() as UINT,
            style: CS_VREDRAW | CS_HREDRAW,
            lpfnWndProc: Some(window_proc::<T>),
            cbClsExtra: 0,
            cbWndExtra: 0,
            hInstance: GetModuleHandleW(std::ptr::null_mut()),
            hIcon: std::ptr::null_mut(),
            hCursor: LoadCursorW(std::ptr::null_mut(), IDC_ARROW),
            hbrBackground: GetStockObject(WHITE_BRUSH as i32) as HBRUSH,
            lpszMenuName: std::ptr::null_mut(),
            lpszClassName: class_name.as_ptr(),
            hIconSm: std::ptr::null_mut(),
        };
        if RegisterClassExW(&wc) == 0 {
            panic!("cannot register the window class");
        }
    }
}

impl<Ti, S> WindowBuilder<Ti, S>
where
    Ti: AsRef<str>,
    S: ToPhysicalSize<u32>,
{
    pub fn build(self) -> Window {
        let class_name = window_class_name();
        let title = self
            .title
            .as_ref()
            .encode_utf16()
            .chain(Some(0))
            .collect::<Vec<_>>();
        unsafe {
            let dpi = get_dpi_from_point(self.position.clone());
            let inner_size = self.inner_size.to_physical(dpi);
            let rc = adjust_window_rect(inner_size, WS_OVERLAPPEDWINDOW, 0, dpi);
            let hinst = GetModuleHandleW(std::ptr::null_mut()) as HINSTANCE;
            let hwnd = CreateWindowExW(
                0,
                class_name.as_ptr(),
                title.as_ptr(),
                self.style,
                self.position.x,
                self.position.y,
                (rc.right - rc.left) as i32,
                (rc.bottom - rc.top) as i32,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                hinst,
                std::ptr::null_mut(),
            );
            if hwnd == std::ptr::null_mut() {
                panic!("cannot create the window");
            }
            let window = LocalWindow::new(
                hwnd,
                WindowState {
                    title: self.title.as_ref().to_string(),
                    style: self.style,
                    set_position: self.position,
                    set_inner_size: inner_size,
                    visible_ime_composition_window: self.visible_ime_composition_window,
                    visible_ime_candidate_window: self.visible_ime_candidate_window,
                    ime_position: PhysicalPosition::new(0, 0),
                    children: self.children,
                    closed: false,
                },
            );
            let handle = window.handle.clone();
            if let Some(parent) = self.parent {
                let mut state = parent.state.write().unwrap();
                state.children.push(handle.clone());
            }
            if self.visibility {
                window.handle.show();
            }
            if self.accept_drag_files {
                DragAcceptFiles(hwnd, TRUE);
            }
            if let Some(icon) = self.icon {
                let big = load_icon(&icon, hinst);
                let small = load_small_icon(&icon, hinst);
                SendMessageW(
                    handle.raw_handle() as _,
                    WM_SETICON,
                    ICON_BIG as WPARAM,
                    big as LPARAM,
                );
                SendMessageW(
                    handle.raw_handle() as _,
                    WM_SETICON,
                    ICON_SMALL as WPARAM,
                    small as LPARAM,
                );
            }
            push_window(hwnd, window);
            handle
        }
    }
}

pub(crate) struct WindowState {
    pub title: String,
    pub style: DWORD,
    pub set_position: ScreenPosition,
    pub set_inner_size: PhysicalSize<u32>,
    pub visible_ime_composition_window: bool,
    pub visible_ime_candidate_window: bool,
    pub ime_position: PhysicalPosition<i32>,
    pub children: Vec<Window>,
    pub closed: bool,
}

/// Represents a window.
#[derive(Clone)]
pub(crate) struct LocalWindow {
    pub handle: Window,
    pub ime_context: Rc<RefCell<ImmContext>>,
}

impl LocalWindow {
    pub(crate) fn new(hwnd: HWND, state: WindowState) -> Self {
        Self {
            handle: Window {
                hwnd: WindowHandle(hwnd),
                state: Arc::new(RwLock::new(state)),
            },
            ime_context: Rc::new(RefCell::new(ImmContext::new(hwnd))),
        }
    }
}

/// The object is like Window, can send to other threads.
#[derive(Clone)]
pub struct Window {
    pub(crate) hwnd: WindowHandle,
    pub(crate) state: Arc<RwLock<WindowState>>,
}

impl Window {
    pub fn title(&self) -> String {
        let state = self.state.read().unwrap();
        state.title.clone()
    }

    pub fn set_title(&self, title: impl AsRef<str>) {
        let mut state = self.state.write().unwrap();
        state.title = title.as_ref().to_string();
        unsafe {
            PostMessageW(self.hwnd.0, WM_USER, UserMessage::SetTitle as usize, 0);
        }
    }

    pub fn position(&self) -> ScreenPosition {
        unsafe {
            let mut rc = RECT::default();
            GetWindowRect(self.hwnd.0, &mut rc);
            ScreenPosition::new(rc.left, rc.top)
        }
    }

    pub fn set_position(&self, position: ScreenPosition) {
        unsafe {
            let mut state = self.state.write().unwrap();
            state.set_position = position;
            PostMessageW(self.hwnd.0, WM_USER, UserMessage::SetPosition as usize, 0);
        }
    }

    pub fn inner_size(&self) -> PhysicalSize<u32> {
        unsafe {
            let mut rc = RECT::default();
            GetClientRect(self.hwnd.0, &mut rc);
            PhysicalSize::new((rc.right - rc.left) as u32, (rc.bottom - rc.top) as u32)
        }
    }

    pub fn set_inner_size(&self, size: impl ToPhysicalSize<u32>) {
        unsafe {
            let mut state = self.state.write().unwrap();
            state.set_inner_size = size.to_physical(self.dpi());
            PostMessageW(self.hwnd.0, WM_USER, UserMessage::SetInnerSize as usize, 0);
        }
    }

    pub fn dpi(&self) -> u32 {
        unsafe { GetDpiForWindow(self.hwnd.0) }
    }

    pub fn scale_factor(&self) -> f32 {
        unsafe { GetDpiForWindow(self.hwnd.0) as f32 / DEFAULT_DPI as f32 }
    }

    pub fn show(&self) {
        unsafe {
            ShowWindowAsync(self.hwnd.0, SW_SHOW);
        }
    }

    pub fn hide(&self) {
        unsafe {
            ShowWindowAsync(self.hwnd.0, SW_HIDE);
        }
    }

    pub fn redraw(&self) {
        unsafe {
            RedrawWindow(
                self.hwnd.0,
                std::ptr::null(),
                std::ptr::null_mut(),
                RDW_INTERNALPAINT,
            );
        }
    }

    pub fn is_closed(&self) -> bool {
        let state = self.state.read().unwrap();
        state.closed
    }

    pub fn close(&self) {
        unsafe {
            if !self.is_closed() {
                PostMessageW(self.hwnd.0, WM_CLOSE, 0, 0);
            }
        }
    }

    pub fn ime_position(&self) -> PhysicalPosition<i32> {
        let state = self.state.read().unwrap();
        PhysicalPosition {
            x: state.ime_position.x,
            y: state.ime_position.y,
        }
    }

    pub fn enable_ime(&self) {
        unsafe {
            PostMessageW(self.hwnd.0, WM_USER, UserMessage::EnableIme as usize, 0);
        }
    }

    pub fn disable_ime(&self) {
        unsafe {
            PostMessageW(self.hwnd.0, WM_USER, UserMessage::DisableIme as usize, 0);
        }
    }

    pub fn set_ime_position(&self, position: impl ToPhysicalPosition<i32>) {
        let mut state = self.state.write().unwrap();
        let position = position.to_physical(self.dpi() as i32);
        state.ime_position.x = position.x;
        state.ime_position.y = position.y;
    }

    pub fn style(&self) -> WindowStyle {
        let state = self.state.read().unwrap();
        WindowStyle(state.style as DWORD)
    }

    pub fn set_style(&self, style: impl Style) {
        unsafe {
            let mut state = self.state.write().unwrap();
            state.style = style.value();
            PostMessageW(self.hwnd.0, WM_USER, UserMessage::SetStyle as usize, 0);
        }
    }

    pub fn accept_drag_files(&self, enabled: bool) {
        unsafe {
            PostMessageW(
                self.hwnd.0,
                WM_USER,
                UserMessage::AcceptDragFiles as usize,
                (if enabled { TRUE } else { FALSE }) as LPARAM,
            );
        }
    }

    pub fn raw_handle(&self) -> *mut std::ffi::c_void {
        self.hwnd.0.clone() as _
    }
}

impl PartialEq for Window {
    fn eq(&self, other: &Self) -> bool {
        self.hwnd == other.hwnd
    }
}

impl Eq for Window {}

unsafe impl HasRawWindowHandle for Window {
    fn raw_window_handle(&self) -> RawWindowHandle {
        RawWindowHandle::Windows(WindowsHandle {
            hinstance: unsafe { GetWindowLongPtrW(self.hwnd.0, GWLP_HINSTANCE) as _ },
            hwnd: self.hwnd.0.clone() as _,
            ..WindowsHandle::empty()
        })
    }
}