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
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
/*
 *  Copyright 2021 QuantumBadger
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

use std::fmt::{Display, Formatter};
use std::marker::PhantomData;

use crate::dimen::Vector2;
use crate::error::{BacktraceError, ErrorMessage};
use crate::{GLRenderer, Graphics2D};

#[cfg(all(not(target_arch = "wasm32"), not(any(doc, doctest))))]
type WindowHelperInnerType<UserEventType> =
    crate::window_internal_glutin::WindowHelperGlutin<UserEventType>;

#[cfg(all(not(target_arch = "wasm32"), not(any(doc, doctest))))]
type UserEventSenderInnerType<UserEventType> =
    crate::window_internal_glutin::UserEventSenderGlutin<UserEventType>;

#[cfg(all(target_arch = "wasm32", not(any(doc, doctest))))]
type WindowHelperInnerType<UserEventType> =
    crate::window_internal_web::WindowHelperWeb<UserEventType>;

#[cfg(all(target_arch = "wasm32", not(any(doc, doctest))))]
type UserEventSenderInnerType<UserEventType> =
    crate::window_internal_web::UserEventSenderWeb<UserEventType>;

#[cfg(any(doc, doctest))]
type WindowHelperInnerType<UserEventType> = PhantomData<UserEventType>;

#[cfg(any(doc, doctest))]
type UserEventSenderInnerType<UserEventType> = PhantomData<UserEventType>;

/// Error occurring when sending a user event.
#[derive(Clone, Debug, Hash, Eq, PartialEq, Copy)]
pub enum EventLoopSendError
{
    /// Send failed as the event loop no longer exists.
    EventLoopNoLongerExists
}

/// Allows user events to be sent to the event loop from other threads.
#[derive(Clone)]
pub struct UserEventSender<UserEventType: 'static>
{
    inner: UserEventSenderInnerType<UserEventType>
}

impl<UserEventType> UserEventSender<UserEventType>
{
    pub(crate) fn new(inner: UserEventSenderInnerType<UserEventType>) -> Self
    {
        Self { inner }
    }

    /// Sends a user-defined event to the event loop. This will cause
    /// [WindowHandler::on_user_event] to be invoked on the event loop
    /// thread.
    ///
    /// This may be invoked from a different thread to the one running the event
    /// loop.
    #[inline]
    pub fn send_event(&self, event: UserEventType) -> Result<(), EventLoopSendError>
    {
        self.inner.send_event(event)
    }
}

/// Error occurring when creating a window.
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub enum WindowCreationError
{
    /// Could not find the primary monitor.
    PrimaryMonitorNotFound,
    /// Could not find a suitable graphics context. Speedy2D attempts to find
    /// the best possible context configuration by trying multiple options for
    /// vsync and multisampling.
    SuitableContextNotFound,
    /// Failed to make the graphics context current.
    MakeContextCurrentFailed,
    /// Failed to instantiate the renderer.
    RendererCreationFailed
}

impl Display for WindowCreationError
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result
    {
        match self {
            WindowCreationError::PrimaryMonitorNotFound => {
                f.write_str("Primary monitor not found")
            }
            WindowCreationError::SuitableContextNotFound => {
                f.write_str("Could not find a suitable graphics context")
            }
            WindowCreationError::MakeContextCurrentFailed => {
                f.write_str("Failed to make the graphics context current")
            }
            WindowCreationError::RendererCreationFailed => {
                f.write_str("Failed to create the renderer")
            }
        }
    }
}

/// A set of callbacks for an active window. If a callback is not implemented,
/// it will do nothing by default, so it is only necessary to implement the
/// callbacks you actually need.
pub trait WindowHandler<UserEventType = ()>
{
    /// Invoked once when the window first starts.
    #[allow(unused_variables)]
    #[inline]
    fn on_start(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        info: WindowStartupInfo
    )
    {
    }

    /// Invoked when a user-defined event is received, allowing you to wake up
    /// the event loop to handle events from other threads.
    ///
    /// See [WindowHelper::create_user_event_sender].
    #[allow(unused_variables)]
    #[inline]
    fn on_user_event(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        user_event: UserEventType
    )
    {
    }

    /// Invoked when the window is resized.
    #[allow(unused_variables)]
    #[inline]
    fn on_resize(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        size_pixels: Vector2<u32>
    )
    {
    }

    /// Invoked if the mouse cursor becomes grabbed or un-grabbed. See
    /// [WindowHelper::set_cursor_grab].
    ///
    /// Note: mouse movement events will behave differently depending on the
    /// current cursor grabbing status.
    #[allow(unused_variables)]
    #[inline]
    fn on_mouse_grab_status_changed(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        mouse_grabbed: bool
    )
    {
    }

    /// Invoked if the window enters or exits fullscreen mode. See
    /// [WindowHelper::set_fullscreen_mode].
    #[allow(unused_variables)]
    #[inline]
    fn on_fullscreen_status_changed(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        fullscreen: bool
    )
    {
    }

    /// Invoked when the window scale factor changes.
    #[allow(unused_variables)]
    #[inline]
    fn on_scale_factor_changed(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        scale_factor: f64
    )
    {
    }

    /// Invoked when the contents of the window needs to be redrawn.
    ///
    /// It is possible to request a redraw from any callback using
    /// [WindowHelper::request_redraw].
    #[allow(unused_variables)]
    #[inline]
    fn on_draw(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        graphics: &mut Graphics2D
    )
    {
    }

    /// Invoked when the mouse changes position.
    ///
    /// Normally, this provides the absolute  position of the mouse in the
    /// window/canvas. However, if the mouse cursor is grabbed, this will
    /// instead provide the amount of relative movement since the last move
    /// event.
    ///
    /// See [WindowHandler::on_mouse_grab_status_changed].
    #[allow(unused_variables)]
    #[inline]
    fn on_mouse_move(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        position: Vector2<f32>
    )
    {
    }

    /// Invoked when a mouse button is pressed.
    #[allow(unused_variables)]
    #[inline]
    fn on_mouse_button_down(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        button: MouseButton
    )
    {
    }

    /// Invoked when a mouse button is released.
    #[allow(unused_variables)]
    #[inline]
    fn on_mouse_button_up(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        button: MouseButton
    )
    {
    }

    /// Invoked when the mouse wheel moves.
    #[allow(unused_variables)]
    #[inline]
    fn on_mouse_wheel_scroll(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        distance: MouseScrollDistance
    )
    {
    }

    /// Invoked when a keyboard key is pressed.
    ///
    /// To detect when a character is typed, see the
    /// [WindowHandler::on_keyboard_char] callback.
    #[allow(unused_variables)]
    #[inline]
    fn on_key_down(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        virtual_key_code: Option<VirtualKeyCode>,
        scancode: KeyScancode
    )
    {
    }

    /// Invoked when a keyboard key is released.
    #[allow(unused_variables)]
    #[inline]
    fn on_key_up(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        virtual_key_code: Option<VirtualKeyCode>,
        scancode: KeyScancode
    )
    {
    }

    /// Invoked when a character is typed on the keyboard.
    ///
    /// This is invoked in addition to the [WindowHandler::on_key_up] and
    /// [WindowHandler::on_key_down] callbacks.
    #[allow(unused_variables)]
    #[inline]
    fn on_keyboard_char(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        unicode_codepoint: char
    )
    {
    }

    /// Invoked when the state of the modifier keys has changed.
    #[allow(unused_variables)]
    #[inline]
    fn on_keyboard_modifiers_changed(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        state: ModifiersState
    )
    {
    }
}

pub(crate) struct DrawingWindowHandler<UserEventType, H>
where
    UserEventType: 'static,
    H: WindowHandler<UserEventType>
{
    window_handler: H,
    renderer: GLRenderer,
    phantom: PhantomData<UserEventType>
}

impl<UserEventType, H> DrawingWindowHandler<UserEventType, H>
where
    H: WindowHandler<UserEventType>,
    UserEventType: 'static
{
    pub fn new(window_handler: H, renderer: GLRenderer) -> Self
    {
        DrawingWindowHandler {
            window_handler,
            renderer,
            phantom: PhantomData::default()
        }
    }

    #[inline]
    pub fn on_start(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        info: WindowStartupInfo
    )
    {
        self.window_handler.on_start(helper, info);
    }

    #[inline]
    pub fn on_user_event(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        user_event: UserEventType
    )
    {
        self.window_handler.on_user_event(helper, user_event)
    }

    #[inline]
    pub fn on_resize(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        size_pixels: Vector2<u32>
    )
    {
        self.renderer.set_viewport_size_pixels(size_pixels);
        self.window_handler.on_resize(helper, size_pixels)
    }

    #[inline]
    pub fn on_mouse_grab_status_changed(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        mouse_grabbed: bool
    )
    {
        self.window_handler
            .on_mouse_grab_status_changed(helper, mouse_grabbed)
    }

    #[inline]
    pub fn on_fullscreen_status_changed(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        fullscreen: bool
    )
    {
        self.window_handler
            .on_fullscreen_status_changed(helper, fullscreen)
    }

    #[inline]
    pub fn on_scale_factor_changed(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        scale_factor: f64
    )
    {
        self.window_handler
            .on_scale_factor_changed(helper, scale_factor)
    }

    #[inline]
    pub fn on_draw(&mut self, helper: &mut WindowHelper<UserEventType>)
    {
        let renderer = &mut self.renderer;
        let window_handler = &mut self.window_handler;

        renderer.draw_frame(|graphics| window_handler.on_draw(helper, graphics))
    }

    #[inline]
    pub fn on_mouse_move(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        position: Vector2<f32>
    )
    {
        self.window_handler.on_mouse_move(helper, position)
    }

    #[inline]
    pub fn on_mouse_button_down(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        button: MouseButton
    )
    {
        self.window_handler.on_mouse_button_down(helper, button)
    }

    #[inline]
    pub fn on_mouse_button_up(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        button: MouseButton
    )
    {
        self.window_handler.on_mouse_button_up(helper, button)
    }

    #[inline]
    pub fn on_mouse_wheel_scroll(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        distance: MouseScrollDistance
    )
    {
        self.window_handler.on_mouse_wheel_scroll(helper, distance)
    }

    #[inline]
    pub fn on_key_down(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        virtual_key_code: Option<VirtualKeyCode>,
        scancode: KeyScancode
    )
    {
        self.window_handler
            .on_key_down(helper, virtual_key_code, scancode)
    }

    #[inline]
    pub fn on_key_up(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        virtual_key_code: Option<VirtualKeyCode>,
        scancode: KeyScancode
    )
    {
        self.window_handler
            .on_key_up(helper, virtual_key_code, scancode)
    }

    #[inline]
    pub fn on_keyboard_char(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        unicode_codepoint: char
    )
    {
        self.window_handler
            .on_keyboard_char(helper, unicode_codepoint)
    }

    #[inline]
    pub fn on_keyboard_modifiers_changed(
        &mut self,
        helper: &mut WindowHelper<UserEventType>,
        state: ModifiersState
    )
    {
        self.window_handler
            .on_keyboard_modifiers_changed(helper, state)
    }
}

/// A set of helper methods to perform actions on a [crate::Window].
pub struct WindowHelper<UserEventType = ()>
where
    UserEventType: 'static
{
    inner: WindowHelperInnerType<UserEventType>
}

impl<UserEventType> WindowHelper<UserEventType>
{
    pub(crate) fn new(inner: WindowHelperInnerType<UserEventType>) -> Self
    {
        WindowHelper { inner }
    }

    #[inline]
    #[must_use]
    pub(crate) fn inner(&mut self) -> &mut WindowHelperInnerType<UserEventType>
    {
        &mut self.inner
    }

    /// Causes the event loop to stop processing events, and terminate the
    /// application.
    ///
    /// Note: The event loop will stop only once the current callback has
    /// returned, rather than terminating immediately.
    ///
    /// Once the event loop has stopped, the entire process will end with error
    /// code 0, even if other threads are running.
    ///
    /// If your `WindowHandler` struct implements `Drop`, it will be safely
    /// destructed before exiting.
    ///
    /// No further callbacks will be given once this function has been called.
    pub fn terminate_loop(&mut self)
    {
        self.inner.terminate_loop()
    }

    /// Sets the window icon from the provided RGBA pixels.
    ///
    /// On Windows, the base icon size is 16x16, however a multiple of this
    /// (e.g. 32x32) should be provided for high-resolution displays.
    ///
    /// For `WebCanvas`, this function has no effect.
    pub fn set_icon_from_rgba_pixels<S>(
        &self,
        data: Vec<u8>,
        size: S
    ) -> Result<(), BacktraceError<ErrorMessage>>
    where
        S: Into<Vector2<u32>>
    {
        self.inner.set_icon_from_rgba_pixels(data, size.into())
    }

    /// Sets the visibility of the mouse cursor.
    pub fn set_cursor_visible(&self, visible: bool)
    {
        self.inner.set_cursor_visible(visible)
    }

    /// Grabs the cursor, preventing it from leaving the window.
    pub fn set_cursor_grab(
        &self,
        grabbed: bool
    ) -> Result<(), BacktraceError<ErrorMessage>>
    {
        self.inner.set_cursor_grab(grabbed)
    }

    /// Set to false to prevent the user from resizing the window.
    ///
    /// For `WebCanvas`, this function has no effect.
    pub fn set_resizable(&self, resizable: bool)
    {
        self.inner.set_resizable(resizable)
    }

    /// Request that the window is redrawn.
    ///
    /// This will cause the [WindowHandler::on_draw] callback to be invoked on
    /// the next frame.
    #[inline]
    pub fn request_redraw(&self)
    {
        self.inner.request_redraw()
    }

    /// Sets the window title.
    pub fn set_title<S: AsRef<str>>(&self, title: S)
    {
        self.inner.set_title(title.as_ref())
    }

    /// Sets the window fullscreen mode.
    ///
    /// When using a web canvas, permission for this operation may be denied,
    /// depending on where this is called from, and the user's browser settings.
    /// If the operation is successful, the
    /// [WindowHandler::on_fullscreen_status_changed] callback will be invoked.
    pub fn set_fullscreen_mode(&self, mode: WindowFullscreenMode)
    {
        self.inner.set_fullscreen_mode(mode)
    }

    /// Sets the window size in pixels. This is the window's inner size,
    /// excluding the border.
    ///
    /// For `WebCanvas`, this function has no effect.
    pub fn set_size_pixels<S: Into<Vector2<u32>>>(&self, size: S)
    {
        self.inner.set_size_pixels(size)
    }

    /// Sets the position of the window in pixels. If multiple monitors are in
    /// use, this will be the distance from the top left of the display
    /// area, spanning all the monitors.
    ///
    /// For `WebCanvas`, this function has no effect.
    pub fn set_position_pixels<P: Into<Vector2<i32>>>(&self, position: P)
    {
        self.inner.set_position_pixels(position)
    }

    /// Sets the window size in scaled device-independent pixels. This is the
    /// window's inner size, excluding the border.
    ///
    /// For `WebCanvas`, this function has no effect.
    pub fn set_size_scaled_pixels<S: Into<Vector2<f32>>>(&self, size: S)
    {
        self.inner.set_size_scaled_pixels(size)
    }

    /// Sets the position of the window in scaled device-independent pixels. If
    /// multiple monitors are in use, this will be the distance from the top
    /// left of the display area, spanning all the monitors.
    ///
    /// For `WebCanvas`, this function has no effect.
    pub fn set_position_scaled_pixels<P: Into<Vector2<f32>>>(&self, position: P)
    {
        self.inner.set_position_scaled_pixels(position)
    }

    /// Gets the window's scale factor.
    #[inline]
    #[must_use]
    pub fn get_scale_factor(&self) -> f64
    {
        self.inner.get_scale_factor()
    }

    /// Creates a [UserEventSender], which can be used to post custom events to
    /// this event loop from another thread.
    ///
    /// See [UserEventSender::send_event], [WindowHandler::on_user_event].
    pub fn create_user_event_sender(&self) -> UserEventSender<UserEventType>
    {
        self.inner.create_user_event_sender()
    }
}

#[cfg(any(doc, doctest, not(target_arch = "wasm32")))]
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
#[must_use]
pub(crate) enum WindowEventLoopAction
{
    /// Continue running the event loop.
    Continue,

    /// Stops the event loop. This will cause the entire process to end with
    /// error code 0, even if other threads are running.
    ///
    /// No further callbacks will be given once a handler has returned this
    /// value. The handler itself will be dropped before exiting.
    Exit
}

/// Information about the starting state of the window.
#[derive(Debug, PartialEq, Clone)]
pub struct WindowStartupInfo
{
    viewport_size_pixels: Vector2<u32>,
    scale_factor: f64
}

impl WindowStartupInfo
{
    pub(crate) fn new(viewport_size_pixels: Vector2<u32>, scale_factor: f64) -> Self
    {
        WindowStartupInfo {
            viewport_size_pixels,
            scale_factor
        }
    }

    /// The scale factor of the window. When a high-dpi display is in use,
    /// this will be greater than `1.0`.
    pub fn scale_factor(&self) -> f64
    {
        self.scale_factor
    }

    /// The size of the viewport in pixels.
    pub fn viewport_size_pixels(&self) -> &Vector2<u32>
    {
        &self.viewport_size_pixels
    }
}

/// Identifies a mouse button.
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub enum MouseButton
{
    /// The left mouse button.
    Left,
    /// The middle mouse button.
    Middle,
    /// The right mouse button.
    Right,
    /// Another mouse button, identified by a number.
    Other(u16)
}

/// Describes a difference in the mouse scroll wheel position.
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum MouseScrollDistance
{
    /// Number of lines or rows to scroll in each direction. The `y` field
    /// represents the vertical scroll direction on a typical mouse wheel.
    Lines
    {
        /// The horizontal scroll distance. Negative values indicate scrolling
        /// left, and positive values indicate scrolling right.
        x: f64,
        /// The vertical scroll distance. Negative values indicate scrolling
        /// down, and positive values indicate scrolling up.
        y: f64,
        /// The forward/backward scroll distance, supported on some 3D mice.
        z: f64
    },
    /// Number of pixels to scroll in each direction. Scroll events are
    /// expressed in pixels if supported by the device (eg. a touchpad) and
    /// platform. The `y` field represents the vertical scroll direction on a
    /// typical mouse wheel.
    Pixels
    {
        /// The horizontal scroll distance. Negative values indicate scrolling
        /// left, and positive values indicate scrolling right.
        x: f64,
        /// The vertical scroll distance. Negative values indicate scrolling
        /// down, and positive values indicate scrolling up.
        y: f64,
        /// The forward/backward scroll distance, supported on some 3D mice.
        z: f64
    },
    /// Number of pages to scroll in each direction (only supported for
    /// WebCanvas). The `y` field represents the vertical scroll direction on a
    /// typical mouse wheel.
    Pages
    {
        /// The horizontal scroll distance. Negative values indicate scrolling
        /// left, and positive values indicate scrolling right.
        x: f64,
        /// The vertical scroll distance. Negative values indicate scrolling
        /// down, and positive values indicate scrolling up.
        y: f64,
        /// The forward/backward scroll distance, supported on some 3D mice.
        z: f64
    }
}

/// A virtual key code.
#[allow(missing_docs)]
#[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)]
pub enum VirtualKeyCode
{
    Key1,
    Key2,
    Key3,
    Key4,
    Key5,
    Key6,
    Key7,
    Key8,
    Key9,
    Key0,

    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H,
    I,
    J,
    K,
    L,
    M,
    N,
    O,
    P,
    Q,
    R,
    S,
    T,
    U,
    V,
    W,
    X,
    Y,
    Z,

    Escape,

    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
    F13,
    F14,
    F15,
    F16,
    F17,
    F18,
    F19,
    F20,
    F21,
    F22,
    F23,
    F24,

    PrintScreen,
    ScrollLock,
    PauseBreak,

    Insert,
    Home,
    Delete,
    End,
    PageDown,
    PageUp,

    Left,
    Up,
    Right,
    Down,

    Backspace,
    Return,
    Space,

    Compose,

    Caret,

    Numlock,
    Numpad0,
    Numpad1,
    Numpad2,
    Numpad3,
    Numpad4,
    Numpad5,
    Numpad6,
    Numpad7,
    Numpad8,
    Numpad9,
    NumpadAdd,
    NumpadDivide,
    NumpadDecimal,
    NumpadComma,
    NumpadEnter,
    NumpadEquals,
    NumpadMultiply,
    NumpadSubtract,

    AbntC1,
    AbntC2,
    Apostrophe,
    Apps,
    Asterisk,
    At,
    Ax,
    Backslash,
    Calculator,
    Capital,
    Colon,
    Comma,
    Convert,
    Equals,
    Grave,
    Kana,
    Kanji,
    LAlt,
    LBracket,
    LControl,
    LShift,
    LWin,
    Mail,
    MediaSelect,
    MediaStop,
    Minus,
    Mute,
    MyComputer,
    NavigateForward,
    NavigateBackward,
    NextTrack,
    NoConvert,
    OEM102,
    Period,
    PlayPause,
    Plus,
    Power,
    PrevTrack,
    RAlt,
    RBracket,
    RControl,
    RShift,
    RWin,
    Semicolon,
    Slash,
    Sleep,
    Stop,
    Sysrq,
    Tab,
    Underline,
    Unlabeled,
    VolumeDown,
    VolumeUp,
    Wake,
    WebBack,
    WebFavorites,
    WebForward,
    WebHome,
    WebRefresh,
    WebSearch,
    WebStop,
    Yen,
    Copy,
    Paste,
    Cut
}

/// The state of the modifier keys.
#[derive(Debug, Hash, PartialEq, Eq, Clone, Default)]
pub struct ModifiersState
{
    pub(crate) ctrl: bool,
    pub(crate) alt: bool,
    pub(crate) shift: bool,
    pub(crate) logo: bool
}

impl ModifiersState
{
    /// This is true if the CTRL key is pressed.
    #[inline]
    #[must_use]
    pub fn ctrl(&self) -> bool
    {
        self.ctrl
    }

    /// This is true if the ALT key is pressed.
    #[inline]
    #[must_use]
    pub fn alt(&self) -> bool
    {
        self.alt
    }

    /// This is true if the SHIFT key is pressed.
    #[inline]
    #[must_use]
    pub fn shift(&self) -> bool
    {
        self.shift
    }

    /// This is true if the logo key is pressed (normally the Windows key).
    #[inline]
    #[must_use]
    pub fn logo(&self) -> bool
    {
        self.logo
    }
}

/// Configuration options about the mode in which the window should be created,
/// for example fullscreen or windowed.
#[derive(Debug, PartialEq, Clone)]
pub(crate) enum WindowCreationMode
{
    /// Create the window in non-fullscreen mode.
    Windowed
    {
        /// The size of the window.
        size: WindowSize,

        /// The position of the window.
        position: Option<WindowPosition>
    },

    /// Create the window in fullscreen borderless mode.
    FullscreenBorderless
}

/// The size of the window to create.
#[derive(Debug, PartialEq, Clone)]
pub enum WindowSize
{
    /// Define the window size in pixels.
    PhysicalPixels(Vector2<u32>),
    /// Define the window size in device-independent scaled pixels.
    ScaledPixels(Vector2<f32>),
    /// Make the window fill the screen, except for a margin around the outer
    /// edges.
    MarginPhysicalPixels(u32),
    /// Make the window fill the screen, except for a margin around the outer
    /// edges.
    MarginScaledPixels(f32)
}

/// The position of the window to create.
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub enum WindowPosition
{
    /// Place the window in the center of the primary monitor.
    Center,
    /// Place the window at the specified pixel location from the top left of
    /// the primary monitor.
    PrimaryMonitorPixelsFromTopLeft(Vector2<i32>)
}

/// Whether or not the window is in fullscreen mode.
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub enum WindowFullscreenMode
{
    /// Non-fullscreen mode.
    Windowed,
    /// Fullscreen borderless mode.
    FullscreenBorderless
}

/// Options used during the creation of a window.
#[derive(Debug, Clone, PartialEq)]
pub struct WindowCreationOptions
{
    pub(crate) mode: WindowCreationMode,
    pub(crate) multisampling: u16,
    pub(crate) vsync: bool,
    pub(crate) always_on_top: bool,
    pub(crate) resizable: bool,
    pub(crate) maximized: bool,
    pub(crate) decorations: bool
}

impl WindowCreationOptions
{
    /// Instantiates a new `WindowCreationOptions` structure with the default
    /// options, in non-fullscreen mode.
    pub fn new_windowed(size: WindowSize, position: Option<WindowPosition>) -> Self
    {
        Self::new(WindowCreationMode::Windowed { size, position })
    }

    /// Instantiates a new `WindowCreationOptions` structure with the default
    /// options, in borderless fullscreen mode.
    #[inline]
    #[must_use]
    pub fn new_fullscreen_borderless() -> Self
    {
        Self::new(WindowCreationMode::FullscreenBorderless)
    }

    #[inline]
    #[must_use]
    fn new(mode: WindowCreationMode) -> Self
    {
        WindowCreationOptions {
            mode,
            multisampling: 16,
            vsync: true,
            always_on_top: false,
            resizable: true,
            maximized: false,
            decorations: true
        }
    }

    /// Sets the maximum level of multisampling which will be applied. By
    /// default this is set to `16`.
    ///
    /// Note that this depends on platform support, and setting this may have no
    /// effect.
    #[inline]
    #[must_use]
    pub fn with_multisampling(mut self, multisampling: u16) -> Self
    {
        self.multisampling = multisampling;
        self
    }

    /// Sets whether or not vsync should be enabled. This can increase latency,
    /// but should eliminate tearing. By default this is set to `true`.
    ///
    /// Note that this depends on platform support, and setting this may have no
    /// effect.
    #[inline]
    #[must_use]
    pub fn with_vsync(mut self, vsync: bool) -> Self
    {
        self.vsync = vsync;
        self
    }

    /// Sets whether or not the window can be resized by the user. The default
    /// is `true`.
    #[inline]
    #[must_use]
    pub fn with_resizable(mut self, resizable: bool) -> Self
    {
        self.resizable = resizable;
        self
    }

    /// If set to `true`, the window will be placed above other windows. The
    /// default is `false`.
    #[inline]
    #[must_use]
    pub fn with_always_on_top(mut self, always_on_top: bool) -> Self
    {
        self.always_on_top = always_on_top;
        self
    }

    /// If set to `true`, the window will be initially maximized. The default is
    /// `false`.
    #[inline]
    #[must_use]
    pub fn with_maximized(mut self, maximized: bool) -> Self
    {
        self.maximized = maximized;
        self
    }

    /// If set to `false`, the window will have no border.  The default is
    /// `true`.
    #[inline]
    #[must_use]
    pub fn with_decorations(mut self, decorations: bool) -> Self
    {
        self.decorations = decorations;
        self
    }
}

/// Type representing a keyboard scancode.
pub type KeyScancode = u32;