-
Notifications
You must be signed in to change notification settings - Fork 422
/
SDL2DesktopWindow.cs
1433 lines (1127 loc) · 51.1 KB
/
SDL2DesktopWindow.cs
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
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Extensions.ImageExtensions;
using osu.Framework.Input;
using osu.Framework.Platform.SDL2;
using osu.Framework.Platform.Windows.Native;
using osu.Framework.Threading;
using osuTK;
using osuTK.Input;
using SDL2;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Image = SixLabors.ImageSharp.Image;
using Point = System.Drawing.Point;
using Rectangle = System.Drawing.Rectangle;
using Size = System.Drawing.Size;
// ReSharper disable UnusedParameter.Local (Class regularly handles native events where we don't consume all parameters)
namespace osu.Framework.Platform
{
/// <summary>
/// Default implementation of a desktop window, using SDL for windowing and graphics support.
/// </summary>
public class SDL2DesktopWindow : IWindow
{
internal IntPtr SDLWindowHandle { get; private set; } = IntPtr.Zero;
private readonly IGraphicsBackend graphicsBackend;
private bool focused;
/// <summary>
/// Whether the window currently has focus.
/// </summary>
public bool Focused
{
get => focused;
private set
{
if (value == focused)
return;
isActive.Value = focused = value;
}
}
/// <summary>
/// Enables or disables vertical sync.
/// </summary>
public bool VerticalSync
{
get => graphicsBackend.VerticalSync;
set => graphicsBackend.VerticalSync = value;
}
/// <summary>
/// Returns true if window has been created.
/// Returns false if the window has not yet been created, or has been closed.
/// </summary>
public bool Exists { get; private set; }
public WindowMode DefaultWindowMode => Configuration.WindowMode.Windowed;
/// <summary>
/// Returns the window modes that the platform should support by default.
/// </summary>
protected virtual IEnumerable<WindowMode> DefaultSupportedWindowModes => Enum.GetValues(typeof(WindowMode)).OfType<WindowMode>();
private Point position;
/// <summary>
/// Returns or sets the window's position in screen space. Only valid when in <see cref="osu.Framework.Configuration.WindowMode.Windowed"/>
/// </summary>
public Point Position
{
get => position;
set
{
position = value;
ScheduleCommand(() => SDL.SDL_SetWindowPosition(SDLWindowHandle, value.X, value.Y));
}
}
private bool resizable = true;
/// <summary>
/// Returns or sets whether the window is resizable or not. Only valid when in <see cref="osu.Framework.Platform.WindowState.Normal"/>.
/// </summary>
public bool Resizable
{
get => resizable;
set
{
if (resizable == value)
return;
resizable = value;
ScheduleCommand(() => SDL.SDL_SetWindowResizable(SDLWindowHandle, value ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
}
}
private bool relativeMouseMode;
/// <summary>
/// Set the state of SDL2's RelativeMouseMode (https://wiki.libsdl.org/SDL_SetRelativeMouseMode).
/// On all platforms, this will lock the mouse to the window (although escaping by setting <see cref="ConfineMouseMode"/> is still possible via a local implementation).
/// On windows, this will use raw input if available.
/// </summary>
public bool RelativeMouseMode
{
get => relativeMouseMode;
set
{
if (relativeMouseMode == value)
return;
if (value && !CursorState.HasFlagFast(CursorState.Hidden))
throw new InvalidOperationException($"Cannot set {nameof(RelativeMouseMode)} to true when the cursor is not hidden via {nameof(CursorState)}.");
relativeMouseMode = value;
ScheduleCommand(() => SDL.SDL_SetRelativeMouseMode(value ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
}
}
private Size size = new Size(default_width, default_height);
/// <summary>
/// Returns or sets the window's internal size, before scaling.
/// </summary>
public Size Size
{
get => size;
private set
{
if (value.Equals(size)) return;
size = value;
ScheduleEvent(() => Resized?.Invoke());
}
}
/// <summary>
/// Provides a bindable that controls the window's <see cref="CursorStateBindable"/>.
/// </summary>
public Bindable<CursorState> CursorStateBindable { get; } = new Bindable<CursorState>();
public CursorState CursorState
{
get => CursorStateBindable.Value;
set => CursorStateBindable.Value = value;
}
public Bindable<Display> CurrentDisplayBindable { get; } = new Bindable<Display>();
public Bindable<WindowMode> WindowMode { get; } = new Bindable<WindowMode>();
private readonly BindableBool isActive = new BindableBool();
public IBindable<bool> IsActive => isActive;
private readonly BindableBool cursorInWindow = new BindableBool();
public IBindable<bool> CursorInWindow => cursorInWindow;
public IBindableList<WindowMode> SupportedWindowModes { get; }
public BindableSafeArea SafeAreaPadding { get; } = new BindableSafeArea();
public virtual Point PointToClient(Point point) => point;
public virtual Point PointToScreen(Point point) => point;
private const int default_width = 1366;
private const int default_height = 768;
private const int default_icon_size = 256;
private readonly Scheduler commandScheduler = new Scheduler();
private readonly Scheduler eventScheduler = new Scheduler();
private readonly Dictionary<int, SDL2ControllerBindings> controllers = new Dictionary<int, SDL2ControllerBindings>();
private string title = string.Empty;
/// <summary>
/// Gets and sets the window title.
/// </summary>
public string Title
{
get => title;
set
{
title = value;
ScheduleCommand(() => SDL.SDL_SetWindowTitle(SDLWindowHandle, title));
}
}
private bool visible;
/// <summary>
/// Enables or disables the window visibility.
/// </summary>
public bool Visible
{
get => visible;
set
{
visible = value;
ScheduleCommand(() =>
{
if (value)
SDL.SDL_ShowWindow(SDLWindowHandle);
else
SDL.SDL_HideWindow(SDLWindowHandle);
});
}
}
private void updateCursorVisibility(bool visible) =>
ScheduleCommand(() => SDL.SDL_ShowCursor(visible ? SDL.SDL_ENABLE : SDL.SDL_DISABLE));
private void updateCursorConfined(bool confined) =>
ScheduleCommand(() => SDL.SDL_SetWindowGrab(SDLWindowHandle, confined ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
private WindowState windowState = WindowState.Normal;
private WindowState? pendingWindowState;
/// <summary>
/// Returns or sets the window's current <see cref="WindowState"/>.
/// </summary>
public WindowState WindowState
{
get => windowState;
set
{
if (pendingWindowState == null && windowState == value)
return;
pendingWindowState = value;
}
}
/// <summary>
/// Stores whether the window used to be in maximised state or not.
/// Used to properly decide what window state to pick when switching to windowed mode (see <see cref="WindowMode"/> change event)
/// </summary>
private bool windowMaximised;
/// <summary>
/// Returns the drawable area, after scaling.
/// </summary>
public Size ClientSize => new Size(Size.Width, Size.Height);
public float Scale = 1;
/// <summary>
/// Queries the physical displays and their supported resolutions.
/// </summary>
public IEnumerable<Display> Displays => Enumerable.Range(0, SDL.SDL_GetNumVideoDisplays()).Select(displayFromSDL);
/// <summary>
/// Gets the <see cref="Display"/> that has been set as "primary" or "default" in the operating system.
/// </summary>
public virtual Display PrimaryDisplay => Displays.First();
private Display currentDisplay;
private int displayIndex = -1;
/// <summary>
/// Gets or sets the <see cref="Display"/> that this window is currently on.
/// </summary>
public Display CurrentDisplay { get; private set; }
public readonly Bindable<ConfineMouseMode> ConfineMouseMode = new Bindable<ConfineMouseMode>();
private readonly Bindable<DisplayMode> currentDisplayMode = new Bindable<DisplayMode>();
/// <summary>
/// The <see cref="DisplayMode"/> for the display that this window is currently on.
/// </summary>
public IBindable<DisplayMode> CurrentDisplayMode => currentDisplayMode;
/// <summary>
/// Gets the native window handle as provided by the operating system.
/// </summary>
public IntPtr WindowHandle
{
get
{
if (SDLWindowHandle == IntPtr.Zero)
return IntPtr.Zero;
var wmInfo = getWindowWMInfo();
// Window handle is selected per subsystem as defined at:
// https://wiki.libsdl.org/SDL_SysWMinfo
switch (wmInfo.subsystem)
{
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS:
return wmInfo.info.win.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_X11:
return wmInfo.info.x11.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_DIRECTFB:
return wmInfo.info.dfb.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_COCOA:
return wmInfo.info.cocoa.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_UIKIT:
return wmInfo.info.uikit.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WAYLAND:
return wmInfo.info.wl.shell_surface;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_ANDROID:
return wmInfo.info.android.window;
default:
return IntPtr.Zero;
}
}
}
private SDL.SDL_SysWMinfo getWindowWMInfo()
{
if (SDLWindowHandle == IntPtr.Zero)
return default;
var wmInfo = new SDL.SDL_SysWMinfo();
SDL.SDL_GetWindowWMInfo(SDLWindowHandle, ref wmInfo);
return wmInfo;
}
private Rectangle windowDisplayBounds
{
get
{
SDL.SDL_GetDisplayBounds(displayIndex, out var rect);
return new Rectangle(rect.x, rect.y, rect.w, rect.h);
}
}
public bool CapsLockPressed => SDL.SDL_GetModState().HasFlagFast(SDL.SDL_Keymod.KMOD_CAPS);
private bool firstDraw = true;
private readonly BindableSize sizeFullscreen = new BindableSize();
private readonly BindableSize sizeWindowed = new BindableSize();
private readonly BindableDouble windowPositionX = new BindableDouble();
private readonly BindableDouble windowPositionY = new BindableDouble();
private readonly Bindable<DisplayIndex> windowDisplayIndexBindable = new Bindable<DisplayIndex>();
public SDL2DesktopWindow()
{
SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_GAMECONTROLLER);
graphicsBackend = CreateGraphicsBackend();
SupportedWindowModes = new BindableList<WindowMode>(DefaultSupportedWindowModes);
CursorStateBindable.ValueChanged += evt =>
{
updateCursorVisibility(!evt.NewValue.HasFlagFast(CursorState.Hidden));
updateCursorConfined(evt.NewValue.HasFlagFast(CursorState.Confined));
};
populateJoysticks();
}
/// <summary>
/// Creates the window and initialises the graphics backend.
/// </summary>
public virtual void Create()
{
SDL.SDL_WindowFlags flags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL |
SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE |
SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI |
SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN | // shown after first swap to avoid white flash on startup (windows)
WindowState.ToFlags();
SDL.SDL_SetHint(SDL.SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4, "1");
SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "1");
SDLWindowHandle = SDL.SDL_CreateWindow(title, Position.X, Position.Y, Size.Width, Size.Height, flags);
Exists = true;
MouseEntered += () => cursorInWindow.Value = true;
MouseLeft += () => cursorInWindow.Value = false;
graphicsBackend.Initialise(this);
updateWindowSpecifics();
updateWindowSize();
WindowMode.TriggerChange();
}
// reference must be kept to avoid GC, see https://stackoverflow.com/a/6193914
[UsedImplicitly]
private SDL.SDL_EventFilter eventFilterDelegate;
/// <summary>
/// Starts the window's run loop.
/// </summary>
public void Run()
{
// polling via SDL_PollEvent blocks on resizes (https://stackoverflow.com/a/50858339)
SDL.SDL_SetEventFilter(eventFilterDelegate = (_, eventPtr) =>
{
// ReSharper disable once PossibleNullReferenceException
var e = (SDL.SDL_Event)Marshal.PtrToStructure(eventPtr, typeof(SDL.SDL_Event));
if (e.type == SDL.SDL_EventType.SDL_WINDOWEVENT && e.window.windowEvent == SDL.SDL_WindowEventID.SDL_WINDOWEVENT_RESIZED)
{
updateWindowSize();
}
return 1;
}, IntPtr.Zero);
while (Exists)
{
commandScheduler.Update();
if (!Exists)
break;
if (pendingWindowState != null)
updateWindowSpecifics();
pollSDLEvents();
if (!cursorInWindow.Value)
pollMouse();
eventScheduler.Update();
Update?.Invoke();
}
Exited?.Invoke();
if (SDLWindowHandle != IntPtr.Zero)
SDL.SDL_DestroyWindow(SDLWindowHandle);
SDL.SDL_Quit();
}
/// <summary>
/// Updates the client size and the scale according to the window.
/// </summary>
/// <returns>Whether the window size has been changed after updating.</returns>
private void updateWindowSize()
{
SDL.SDL_GL_GetDrawableSize(SDLWindowHandle, out var w, out var h);
SDL.SDL_GetWindowSize(SDLWindowHandle, out var actualW, out var _);
Scale = (float)w / actualW;
Size = new Size(w, h);
// This function may be invoked before the SDL internal states are all changed. (as documented here: https://wiki.libsdl.org/SDL_SetEventFilter)
// Scheduling the store to config until after the event poll has run will ensure the window is in the correct state.
eventScheduler.Add(storeWindowSizeToConfig, true);
}
/// <summary>
/// Forcefully closes the window.
/// </summary>
public void Close() => ScheduleCommand(() => Exists = false);
/// <summary>
/// Attempts to close the window.
/// </summary>
public void RequestClose() => ScheduleEvent(() =>
{
if (ExitRequested?.Invoke() != true)
Close();
});
public void SwapBuffers()
{
graphicsBackend.SwapBuffers();
if (firstDraw)
{
Visible = true;
firstDraw = false;
}
}
/// <summary>
/// Requests that the graphics backend become the current context.
/// May not be required for some backends.
/// </summary>
public void MakeCurrent() => graphicsBackend.MakeCurrent();
/// <summary>
/// Requests that the current context be cleared.
/// </summary>
public void ClearCurrent() => graphicsBackend.ClearCurrent();
private void enqueueJoystickAxisInput(JoystickAxisSource axisSource, short axisValue)
{
// SDL reports axis values in the range short.MinValue to short.MaxValue, so we scale and clamp it to the range of -1f to 1f
var clamped = Math.Clamp((float)axisValue / short.MaxValue, -1f, 1f);
ScheduleEvent(() => JoystickAxisChanged?.Invoke(new JoystickAxis(axisSource, clamped)));
}
private void enqueueJoystickButtonInput(JoystickButton button, bool isPressed)
{
if (isPressed)
ScheduleEvent(() => JoystickButtonDown?.Invoke(button));
else
ScheduleEvent(() => JoystickButtonUp?.Invoke(button));
}
/// <summary>
/// Attempts to set the window's icon to the specified image.
/// </summary>
/// <param name="image">An <see cref="Image{Rgba32}"/> to set as the window icon.</param>
private unsafe void setSDLIcon(Image<Rgba32> image)
{
var pixelMemory = image.CreateReadOnlyPixelMemory();
var imageSize = image.Size();
ScheduleCommand(() =>
{
var pixelSpan = pixelMemory.Span;
IntPtr surface;
fixed (Rgba32* ptr = pixelSpan)
surface = SDL.SDL_CreateRGBSurfaceFrom(new IntPtr(ptr), imageSize.Width, imageSize.Height, 32, imageSize.Width * 4, 0xff, 0xff00, 0xff0000, 0xff000000);
SDL.SDL_SetWindowIcon(SDLWindowHandle, surface);
SDL.SDL_FreeSurface(surface);
});
}
private Point previousPolledPoint = Point.Empty;
private void pollMouse()
{
SDL.SDL_GetGlobalMouseState(out var x, out var y);
if (previousPolledPoint.X == x && previousPolledPoint.Y == y)
return;
previousPolledPoint = new Point(x, y);
var pos = WindowMode.Value == Configuration.WindowMode.Windowed ? Position : windowDisplayBounds.Location;
var rx = x - pos.X;
var ry = y - pos.Y;
ScheduleEvent(() => MouseMove?.Invoke(new Vector2(rx * Scale, ry * Scale)));
}
#region SDL Event Handling
/// <summary>
/// Adds an <see cref="Action"/> to the <see cref="Scheduler"/> expected to handle event callbacks.
/// </summary>
/// <param name="action">The <see cref="Action"/> to execute.</param>
protected void ScheduleEvent(Action action) => eventScheduler.Add(action, false);
protected void ScheduleCommand(Action action) => commandScheduler.Add(action, false);
private const int events_per_peep = 64;
private SDL.SDL_Event[] events = new SDL.SDL_Event[events_per_peep];
/// <summary>
/// Poll for all pending events.
/// </summary>
private void pollSDLEvents()
{
SDL.SDL_PumpEvents();
int eventsRead;
do
{
eventsRead = SDL.SDL_PeepEvents(events, events_per_peep, SDL.SDL_eventaction.SDL_GETEVENT, SDL.SDL_EventType.SDL_FIRSTEVENT, SDL.SDL_EventType.SDL_LASTEVENT);
for (int i = 0; i < eventsRead; i++)
handleSDLEvent(events[i]);
} while (eventsRead == events_per_peep);
}
private void handleSDLEvent(SDL.SDL_Event e)
{
switch (e.type)
{
case SDL.SDL_EventType.SDL_QUIT:
case SDL.SDL_EventType.SDL_APP_TERMINATING:
handleQuitEvent(e.quit);
break;
case SDL.SDL_EventType.SDL_WINDOWEVENT:
handleWindowEvent(e.window);
break;
case SDL.SDL_EventType.SDL_KEYDOWN:
case SDL.SDL_EventType.SDL_KEYUP:
handleKeyboardEvent(e.key);
break;
case SDL.SDL_EventType.SDL_TEXTEDITING:
handleTextEditingEvent(e.edit);
break;
case SDL.SDL_EventType.SDL_TEXTINPUT:
handleTextInputEvent(e.text);
break;
case SDL.SDL_EventType.SDL_MOUSEMOTION:
handleMouseMotionEvent(e.motion);
break;
case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
handleMouseButtonEvent(e.button);
break;
case SDL.SDL_EventType.SDL_MOUSEWHEEL:
handleMouseWheelEvent(e.wheel);
break;
case SDL.SDL_EventType.SDL_JOYAXISMOTION:
handleJoyAxisEvent(e.jaxis);
break;
case SDL.SDL_EventType.SDL_JOYBALLMOTION:
handleJoyBallEvent(e.jball);
break;
case SDL.SDL_EventType.SDL_JOYHATMOTION:
handleJoyHatEvent(e.jhat);
break;
case SDL.SDL_EventType.SDL_JOYBUTTONDOWN:
case SDL.SDL_EventType.SDL_JOYBUTTONUP:
handleJoyButtonEvent(e.jbutton);
break;
case SDL.SDL_EventType.SDL_JOYDEVICEADDED:
case SDL.SDL_EventType.SDL_JOYDEVICEREMOVED:
handleJoyDeviceEvent(e.jdevice);
break;
case SDL.SDL_EventType.SDL_CONTROLLERAXISMOTION:
handleControllerAxisEvent(e.caxis);
break;
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONDOWN:
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONUP:
handleControllerButtonEvent(e.cbutton);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED:
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMOVED:
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMAPPED:
handleControllerDeviceEvent(e.cdevice);
break;
case SDL.SDL_EventType.SDL_FINGERDOWN:
case SDL.SDL_EventType.SDL_FINGERUP:
case SDL.SDL_EventType.SDL_FINGERMOTION:
handleTouchFingerEvent(e.tfinger);
break;
case SDL.SDL_EventType.SDL_DROPFILE:
case SDL.SDL_EventType.SDL_DROPTEXT:
case SDL.SDL_EventType.SDL_DROPBEGIN:
case SDL.SDL_EventType.SDL_DROPCOMPLETE:
handleDropEvent(e.drop);
break;
}
}
private void handleQuitEvent(SDL.SDL_QuitEvent evtQuit) => RequestClose();
private void handleDropEvent(SDL.SDL_DropEvent evtDrop)
{
switch (evtDrop.type)
{
case SDL.SDL_EventType.SDL_DROPFILE:
var str = SDL.UTF8_ToManaged(evtDrop.file, true);
if (str != null)
ScheduleEvent(() => DragDrop?.Invoke(str));
break;
}
}
private void handleTouchFingerEvent(SDL.SDL_TouchFingerEvent evtTfinger)
{
}
private void handleControllerDeviceEvent(SDL.SDL_ControllerDeviceEvent evtCdevice)
{
switch (evtCdevice.type)
{
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED:
addJoystick(evtCdevice.which);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMOVED:
SDL.SDL_GameControllerClose(controllers[evtCdevice.which].ControllerHandle);
controllers.Remove(evtCdevice.which);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMAPPED:
if (controllers.TryGetValue(evtCdevice.which, out var state))
state.PopulateBindings();
break;
}
}
private void handleControllerButtonEvent(SDL.SDL_ControllerButtonEvent evtCbutton)
{
var button = ((SDL.SDL_GameControllerButton)evtCbutton.button).ToJoystickButton();
switch (evtCbutton.type)
{
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONDOWN:
enqueueJoystickButtonInput(button, true);
break;
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONUP:
enqueueJoystickButtonInput(button, false);
break;
}
}
private void handleControllerAxisEvent(SDL.SDL_ControllerAxisEvent evtCaxis) =>
enqueueJoystickAxisInput(((SDL.SDL_GameControllerAxis)evtCaxis.axis).ToJoystickAxisSource(), evtCaxis.axisValue);
private void addJoystick(int which)
{
var instanceID = SDL.SDL_JoystickGetDeviceInstanceID(which);
// if the joystick is already opened, ignore it
if (controllers.ContainsKey(instanceID))
return;
var joystick = SDL.SDL_JoystickOpen(which);
var controller = IntPtr.Zero;
if (SDL.SDL_IsGameController(which) == SDL.SDL_bool.SDL_TRUE)
controller = SDL.SDL_GameControllerOpen(which);
controllers[instanceID] = new SDL2ControllerBindings(joystick, controller);
}
/// <summary>
/// Populates <see cref="controllers"/> with joysticks that are already connected.
/// </summary>
private void populateJoysticks()
{
for (int i = 0; i < SDL.SDL_NumJoysticks(); i++)
{
addJoystick(i);
}
}
private void handleJoyDeviceEvent(SDL.SDL_JoyDeviceEvent evtJdevice)
{
switch (evtJdevice.type)
{
case SDL.SDL_EventType.SDL_JOYDEVICEADDED:
addJoystick(evtJdevice.which);
break;
case SDL.SDL_EventType.SDL_JOYDEVICEREMOVED:
// if the joystick is already closed, ignore it
if (!controllers.ContainsKey(evtJdevice.which))
break;
SDL.SDL_JoystickClose(controllers[evtJdevice.which].JoystickHandle);
controllers.Remove(evtJdevice.which);
break;
}
}
private void handleJoyButtonEvent(SDL.SDL_JoyButtonEvent evtJbutton)
{
// if this button exists in the controller bindings, skip it
if (controllers.TryGetValue(evtJbutton.which, out var state) && state.GetButtonForIndex(evtJbutton.button) != SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID)
return;
var button = JoystickButton.FirstButton + evtJbutton.button;
switch (evtJbutton.type)
{
case SDL.SDL_EventType.SDL_JOYBUTTONDOWN:
enqueueJoystickButtonInput(button, true);
break;
case SDL.SDL_EventType.SDL_JOYBUTTONUP:
enqueueJoystickButtonInput(button, false);
break;
}
}
private void handleJoyHatEvent(SDL.SDL_JoyHatEvent evtJhat)
{
}
private void handleJoyBallEvent(SDL.SDL_JoyBallEvent evtJball)
{
}
private void handleJoyAxisEvent(SDL.SDL_JoyAxisEvent evtJaxis)
{
// if this axis exists in the controller bindings, skip it
if (controllers.TryGetValue(evtJaxis.which, out var state) && state.GetAxisForIndex(evtJaxis.axis) != SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_INVALID)
return;
enqueueJoystickAxisInput(JoystickAxisSource.Axis1 + evtJaxis.axis, evtJaxis.axisValue);
}
private void handleMouseWheelEvent(SDL.SDL_MouseWheelEvent evtWheel) =>
ScheduleEvent(() => TriggerMouseWheel(new Vector2(evtWheel.x, evtWheel.y), false));
private void handleMouseButtonEvent(SDL.SDL_MouseButtonEvent evtButton)
{
MouseButton button = mouseButtonFromEvent(evtButton.button);
switch (evtButton.type)
{
case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
ScheduleEvent(() => MouseDown?.Invoke(button));
break;
case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
ScheduleEvent(() => MouseUp?.Invoke(button));
break;
}
}
private void handleMouseMotionEvent(SDL.SDL_MouseMotionEvent evtMotion)
{
if (SDL.SDL_GetRelativeMouseMode() == SDL.SDL_bool.SDL_FALSE)
ScheduleEvent(() => MouseMove?.Invoke(new Vector2(evtMotion.x * Scale, evtMotion.y * Scale)));
else
ScheduleEvent(() => MouseMoveRelative?.Invoke(new Vector2(evtMotion.xrel * Scale, evtMotion.yrel * Scale)));
}
private unsafe void handleTextInputEvent(SDL.SDL_TextInputEvent evtText)
{
var ptr = new IntPtr(evtText.text);
if (ptr == IntPtr.Zero)
return;
string text = Marshal.PtrToStringUTF8(ptr) ?? "";
foreach (char c in text)
ScheduleEvent(() => KeyTyped?.Invoke(c));
}
private void handleTextEditingEvent(SDL.SDL_TextEditingEvent evtEdit)
{
}
private void handleKeyboardEvent(SDL.SDL_KeyboardEvent evtKey)
{
Key key = evtKey.keysym.ToKey();
if (key == Key.Unknown)
return;
switch (evtKey.type)
{
case SDL.SDL_EventType.SDL_KEYDOWN:
ScheduleEvent(() => KeyDown?.Invoke(key));
break;
case SDL.SDL_EventType.SDL_KEYUP:
ScheduleEvent(() => KeyUp?.Invoke(key));
break;
}
}
private void handleWindowEvent(SDL.SDL_WindowEvent evtWindow)
{
updateWindowSpecifics();
switch (evtWindow.windowEvent)
{
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_MOVED:
// explicitly requery as there are occasions where what SDL has provided us with is not up-to-date.
SDL.SDL_GetWindowPosition(SDLWindowHandle, out int x, out int y);
var newPosition = new Point(x, y);
if (!newPosition.Equals(Position))
{
position = newPosition;
ScheduleEvent(() => Moved?.Invoke(newPosition));
if (WindowMode.Value == Configuration.WindowMode.Windowed)
storeWindowPositionToConfig();
}
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_SIZE_CHANGED:
updateWindowSize();
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_ENTER:
cursorInWindow.Value = true;
ScheduleEvent(() => MouseEntered?.Invoke());
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_LEAVE:
cursorInWindow.Value = false;
ScheduleEvent(() => MouseLeft?.Invoke());
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_RESTORED:
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED:
ScheduleEvent(() => Focused = true);
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_MINIMIZED:
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST:
ScheduleEvent(() => Focused = false);
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_CLOSE:
break;
}
}
/// <summary>
/// Should be run on a regular basis to check for external window state changes.
/// </summary>
private void updateWindowSpecifics()
{
// don't attempt to run before the window is initialised, as Create() will do so anyway.
if (SDLWindowHandle == IntPtr.Zero)
return;
var stateBefore = windowState;
// check for a pending user state change and give precedence.
if (pendingWindowState != null)
{
windowState = pendingWindowState.Value;
pendingWindowState = null;
updateWindowStateAndSize();
}
else
{
windowState = ((SDL.SDL_WindowFlags)SDL.SDL_GetWindowFlags(SDLWindowHandle)).ToWindowState();
}
if (windowState != stateBefore)
{
ScheduleEvent(() => WindowStateChanged?.Invoke(windowState));
updateMaximisedState();
}
int newDisplayIndex = SDL.SDL_GetWindowDisplayIndex(SDLWindowHandle);
if (displayIndex != newDisplayIndex)
{
displayIndex = newDisplayIndex;
currentDisplay = Displays.ElementAtOrDefault(displayIndex) ?? PrimaryDisplay;
ScheduleEvent(() =>
{
CurrentDisplayBindable.Value = currentDisplay;
});
}
}
/// <summary>
/// Should be run after a local window state change, to propagate the correct SDL actions.
/// </summary>
private void updateWindowStateAndSize()
{
// this reset is required even on changing from one fullscreen resolution to another.
// if it is not included, the GL context will not get the correct size.
// this is mentioned by multiple sources as an SDL issue, which seems to resolve by similar means (see https://discourse.libsdl.org/t/sdl-setwindowsize-does-not-work-in-fullscreen/20711/4).
SDL.SDL_SetWindowBordered(SDLWindowHandle, SDL.SDL_bool.SDL_TRUE);
SDL.SDL_SetWindowFullscreen(SDLWindowHandle, (uint)SDL.SDL_bool.SDL_FALSE);