forked from Rampastring/Rampastring.XNAUI
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWindowManager.cs
More file actions
981 lines (835 loc) · 34.6 KB
/
WindowManager.cs
File metadata and controls
981 lines (835 loc) · 34.6 KB
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
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Rampastring.XNAUI.XNAControls;
using Rampastring.Tools;
using Microsoft.Xna.Framework.Content;
using Color = Microsoft.Xna.Framework.Color;
using Rectangle = Microsoft.Xna.Framework.Rectangle;
using Rampastring.XNAUI.Input;
using System.Diagnostics;
using System.Linq;
using Rampastring.XNAUI.PlatformSpecific;
#if NETFRAMEWORK
using System.Reflection;
#endif
#if WINFORMS
using System.Windows.Forms;
#endif
namespace Rampastring.XNAUI;
/// <summary>
/// Manages the game window and all of the game's controls
/// inside the game window.
/// </summary>
public class WindowManager : DrawableGameComponent
{
private const int XNA_MAX_TEXTURE_SIZE = 2048;
/// <summary>
/// Creates a new WindowManager.
/// </summary>
/// <param name="game">The game.</param>
/// <param name="graphics">The game's GraphicsDeviceManager.</param>
public WindowManager(Game game, GraphicsDeviceManager graphics) : base(game)
{
this.graphics = graphics;
}
/// <summary>
/// Raised when the game window is closing.
/// </summary>
public event EventHandler GameClosing;
/// <summary>
/// Raised when the render resolution is changed.
/// </summary>
public event EventHandler RenderResolutionChanged;
#if WINFORMS
/// <summary>
/// Raised when the size of the game window has been changed by the user or the operating system.
/// This event is not raised by calling <see cref="InitGraphicsMode(int, int, bool)"/>.
/// </summary>
public event EventHandler WindowSizeChangedByUser;
#endif
/// <summary>
/// The input cursor.
/// </summary>
public Input.Cursor Cursor { get; private set; }
/// <summary>
/// The keyboard.
/// </summary>
public RKeyboard Keyboard { get; private set; }
/// <summary>
/// The SoundPlayer that is responsible for handling audio.
/// </summary>
public SoundPlayer SoundPlayer { get; private set; }
private List<XNAControl> Controls = new List<XNAControl>();
private readonly List<XNAControl> _tunnelingPath = new List<XNAControl>();
private List<Callback> Callbacks = new List<Callback>();
private readonly object locker = new object();
/// <summary>
/// Returns the width of the game window, including the window borders.
/// </summary>
public int WindowWidth { get; private set; } = 800;
/// <summary>
/// Returns the height of the game window, including the window borders.
/// </summary>
public int WindowHeight { get; private set; } = 600;
/// <summary>
/// Returns the width of the back buffer.
/// </summary>
public int RenderResolutionX { get; private set; } = 800;
/// <summary>
/// Returns the height of the back buffer.
/// </summary>
public int RenderResolutionY { get; private set; } = 600;
/// <summary>
/// Gets a boolean that determines whether the game window currently has input focus.
/// </summary>
public bool HasFocus { get; private set; } = true;
public double ScaleRatio { get; private set; } = 1.0;
public int SceneXPosition { get; private set; } = 0;
public int SceneYPosition { get; private set; } = 0;
private XNAControl _selectedControl;
/// <summary>
/// Gets or sets the control that is currently selected.
/// Usually used for controls that need input focus, like text boxes.
/// </summary>
public XNAControl SelectedControl
{
get { return _selectedControl; }
set
{
XNAControl oldSelectedControl = _selectedControl;
_selectedControl = value;
if (oldSelectedControl != _selectedControl)
{
if (_selectedControl != null)
_selectedControl.OnSelectedChanged();
if (oldSelectedControl != null)
oldSelectedControl.OnSelectedChanged();
}
}
}
/// <summary>
/// Returns a bool that determines whether input is
/// currently exclusively captured by the selected control.
/// </summary>
public bool IsInputExclusivelyCaptured => SelectedControl != null && SelectedControl.ExclusiveInputCapture;
/// <summary>
/// A list of custom control INI attribute parsers.
/// Allows extending the control INI attribute parsing
/// system with custom INI keys.
/// </summary>
public List<IControlINIAttributeParser> ControlINIAttributeParsers { get; private set; } = new List<IControlINIAttributeParser>();
/// <summary>
/// If set, only scales the rendered screen by integer scaling factors. Unfilled space is filled with black.
/// </summary>
public bool IntegerScalingOnly { get; set; }
/// <summary>
/// Object for handling Input Method Editor (IME) based input.
/// </summary>
public IIMEHandler IMEHandler { get; set; } = null;
/// <summary>
/// The control, of the highest generation, that the mouse cursor is currently positioned on.
/// </summary>
internal XNAControl ActiveControl { get; set; }
/// <summary>
/// If specified, the control blocks other controls on the screen
/// from being interacted with. Defaults to null.
/// </summary>
public XNAControl FocusedControl { get; set; } = null;
private GraphicsDeviceManager graphics;
private IGameWindowManager gameWindowManager;
private RenderTarget2D renderTarget;
private RenderTarget2D doubledRenderTarget;
private float _lastFontScaleRatio = 1.0f;
/// <summary>
/// Sets the rendering (back buffer) resolution of the game.
/// Does not affect the size of the actual game window.
/// </summary>
/// <param name="x">The width of the back buffer.</param>
/// <param name="y">The height of the back buffer.</param>
public void SetRenderResolution(int x, int y)
{
#if XNA
x = Math.Min(x, XNA_MAX_TEXTURE_SIZE);
y = Math.Min(y, XNA_MAX_TEXTURE_SIZE);
#endif
RenderResolutionX = x;
RenderResolutionY = y;
RecalculateScaling();
RenderResolutionChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Re-calculates the scaling of the rendered screen to fill the window.
/// </summary>
private void RecalculateScaling()
{
int clientAreaWidth = Game.Window.ClientBounds.Width;
int clientAreaHeight = Game.Window.ClientBounds.Height;
if (clientAreaWidth <= 0 || clientAreaHeight <= 0)
return;
double xRatio = clientAreaWidth / (double)RenderResolutionX;
double yRatio = clientAreaHeight / (double)RenderResolutionY;
if (IntegerScalingOnly && clientAreaWidth >= RenderResolutionX && clientAreaHeight >= RenderResolutionY)
{
xRatio = clientAreaWidth / RenderResolutionX;
yRatio = clientAreaHeight / RenderResolutionY;
}
double ratio;
int texturePositionX = 0;
int texturePositionY = 0;
if (xRatio > yRatio)
{
ratio = yRatio;
int textureWidth = (int)(RenderResolutionX * ratio);
texturePositionX = (clientAreaWidth - textureWidth) / 2;
if (IntegerScalingOnly)
{
int textureHeight = (int)(RenderResolutionY * ratio);
texturePositionY = (clientAreaHeight - textureHeight) / 2;
}
}
else
{
ratio = xRatio;
int textureHeight = (int)(RenderResolutionY * ratio);
texturePositionY = (clientAreaHeight - textureHeight) / 2;
if (IntegerScalingOnly)
{
int textureWidth = (int)(RenderResolutionX * ratio);
texturePositionX = (clientAreaWidth - textureWidth) / 2;
}
}
ScaleRatio = ratio;
SceneXPosition = texturePositionX;
SceneYPosition = texturePositionY;
if (renderTarget != null && !renderTarget.IsDisposed)
renderTarget.Dispose();
if (doubledRenderTarget != null && !doubledRenderTarget.IsDisposed)
doubledRenderTarget.Dispose();
renderTarget = new RenderTarget2D(GraphicsDevice, RenderResolutionX, RenderResolutionY, false, SurfaceFormat.Color,
DepthFormat.None, 0, RenderTargetUsage.PreserveContents);
RenderTargetStack.Initialize(renderTarget, GraphicsDevice);
RenderTargetStack.InitDetachedScaledControlRenderTarget(RenderResolutionX, RenderResolutionY);
if (ScaleRatio > 1.5 && ScaleRatio % 2.0 == 0)
{
#if XNA
if (RenderResolutionX * 2 > XNA_MAX_TEXTURE_SIZE || RenderResolutionY * 2 > XNA_MAX_TEXTURE_SIZE)
{
doubledRenderTarget = null;
return;
}
#endif
// Enable sharper scaling method
doubledRenderTarget = new RenderTarget2D(GraphicsDevice,
RenderResolutionX * 2, RenderResolutionY * 2, false, SurfaceFormat.Color,
DepthFormat.None, 0, RenderTargetUsage.PreserveContents);
}
else
{
doubledRenderTarget = null;
}
float floatScaleRatio = (float)ScaleRatio;
if (floatScaleRatio != _lastFontScaleRatio)
{
_lastFontScaleRatio = floatScaleRatio;
Renderer.ReloadFontsForScale(floatScaleRatio);
}
}
/// <summary>
/// Closes the game.
/// </summary>
public void CloseGame()
{
#if !WINFORMS
// When using UniversalGL both GameClosing and Game.Exiting trigger GameWindowManager_GameWindowClosing().
// To avoid executing shutdown code twice we unsubscribe here from Game.Exiting.
// The default double subscription needs to stay to handle the case of a forceful shutdown e.g. alt+F4.
Game.Exiting -= GameWindowManager_GameWindowClosing;
#endif
GameClosing?.Invoke(this, EventArgs.Empty);
SoundPlayer.StopAll();
Game.Exit();
}
/// <summary>
/// Restarts the game.
/// </summary>
public void RestartGame()
{
Logger.Log("Restarting game.");
#if !XNA
// MonoGame takes ages to unload assets compared to XNA; sometimes MonoGame
// can take over 8 seconds while XNA takes only 1 second
// This is a bit dirty, but at least it makes the MonoGame build exit quicker
GameClosing?.Invoke(this, EventArgs.Empty);
SoundPlayer.StopAll();
// TODO move Windows-specific functionality
#if WINFORMS
Application.DoEvents();
#endif
#if NETFRAMEWORK
using var process = Process.Start(Assembly.GetEntryAssembly().Location);
#else
using var process = Process.Start(new ProcessStartInfo
{
FileName = Environment.ProcessPath,
Arguments = Environment.CommandLine
});
#endif
Game.Exit();
#else
Application.Restart();
#endif
}
/// <summary>
/// Initializes the WindowManager.
/// </summary>
/// <param name="content">The game content manager.</param>
/// <param name="contentPath">The path where the ContentManager should load files from (including SpriteFont files).</param>
public void Initialize(ContentManager content, string contentPath)
{
base.Initialize();
content.RootDirectory = SafePath.GetDirectory(contentPath).FullName;
Cursor = new Input.Cursor(this);
Cursor.Initialize();
Keyboard = new RKeyboard(Game);
if (!AssetLoader.IsInitialized)
AssetLoader.Initialize(graphics.GraphicsDevice, content);
Renderer.Initialize(GraphicsDevice, content);
SoundPlayer = new SoundPlayer(Game);
gameWindowManager = new WindowsGameWindowManager(Game);
#if WINFORMS
gameWindowManager.GameWindowClosing += GameWindowManager_GameWindowClosing;
gameWindowManager.ClientSizeChanged += GameWindowManager_ClientSizeChanged;
#else
Game.Exiting += GameWindowManager_GameWindowClosing;
#endif
if (UISettings.ActiveSettings == null)
UISettings.ActiveSettings = new UISettings();
#if XNA
KeyboardEventInput.Initialize(Game.Window);
#endif
}
#if WINFORMS
private void GameWindowManager_ClientSizeChanged(object sender, EventArgs e)
{
WindowWidth = gameWindowManager.GetWindowWidth();
WindowHeight = gameWindowManager.GetWindowHeight();
RecalculateScaling();
WindowSizeChangedByUser?.Invoke(this, EventArgs.Empty);
}
#endif
private void GameWindowManager_GameWindowClosing(object sender, EventArgs e)
{
SoundPlayer.StopAll();
GameClosing?.Invoke(this, EventArgs.Empty);
}
#if WINFORMS
/// <summary>
/// Sets the border style of the game form.
/// Throws an exception if the application is running in borderless mode.
/// </summary>
/// <param name="formBorderStyle">The form border style to apply.</param>
public void SetFormBorderStyle(FormBorderStyle formBorderStyle)
{
gameWindowManager.SetFormBorderStyle(formBorderStyle);
}
#endif
/// <summary>
/// Schedules a delegate to be executed on the next game loop frame,
/// on the main game thread.
/// </summary>
/// <param name="d">The delegate.</param>
/// <param name="args">The arguments to be passed on to the delegate.</param>
public void AddCallback(Delegate d, params object[] args)
{
lock (locker)
Callbacks.Add(new Callback(d, args));
}
/// <summary>
/// Adds a control into the WindowManager, on the last place
/// in the list of controls.
/// </summary>
/// <param name="control">The control to add.</param>
public void AddAndInitializeControl(XNAControl control)
{
if (Controls.Contains(control))
{
throw new InvalidOperationException("WindowManager.AddAndInitializeControl: Control " + control.Name + " already exists!");
}
control.Initialize();
Controls.Add(control);
ReorderControls();
}
/// <summary>
/// Adds a control to the WindowManager, on the last place
/// in the list of controls. Does not call the control's
/// Initialize() method.
/// </summary>
/// <param name="control">The control to add.</param>
public void AddControl(XNAControl control)
{
if (Controls.Contains(control))
{
throw new InvalidOperationException("WindowManager.AddControl: Control " + control.Name + " already exists!");
}
Controls.Add(control);
}
/// <summary>
/// Inserts a control into the WindowManager on the first place
/// in the list of controls.
/// </summary>
/// <param name="control">The control to insert.</param>
public void InsertAndInitializeControl(XNAControl control)
{
if (Controls.Contains(control))
{
throw new Exception("WindowManager.InsertAndInitializeControl: Control " + control.Name + " already exists!");
}
Controls.Insert(0, control);
}
/// <summary>
/// Centers a control on the game window.
/// </summary>
/// <param name="control">The control to center.</param>
public void CenterControlOnScreen(XNAControl control)
{
control.ClientRectangle = new Rectangle((RenderResolutionX - control.Width) / 2,
(RenderResolutionY - control.Height) / 2, control.Width, control.Height);
}
/// <summary>
/// Centers the game window on the screen.
/// </summary>
public void CenterOnScreen()
{
gameWindowManager.CenterOnScreen();
}
/// <summary>
/// Enables or disables borderless windowed mode.
/// </summary>
/// <param name="value">A boolean that determines whether borderless
/// windowed mode should be enabled.</param>
public void SetBorderlessMode(bool value)
{
gameWindowManager.SetBorderlessMode(value);
}
#if WINFORMS
public void MinimizeWindow()
{
gameWindowManager.MinimizeWindow();
}
public void MaximizeWindow()
{
gameWindowManager.MaximizeWindow();
}
public void HideWindow()
{
gameWindowManager.HideWindow();
}
public void ShowWindow()
{
gameWindowManager.ShowWindow();
}
/// <summary>
/// Flashes the game window on the taskbar.
/// </summary>
public void FlashWindow()
{
gameWindowManager.FlashWindow();
}
/// <summary>
/// Sets the icon of the game window to an icon that exists on a specific
/// file path.
/// </summary>
/// <param name="path">The path to the icon file.</param>
public void SetIcon(string path)
{
gameWindowManager.SetIcon(path);
}
/// <summary>
/// Returns the IntPtr handle of the game window on Windows.
/// On other platforms, returns IntPtr.Zero.
/// </summary>
public IntPtr GetWindowHandle()
{
return gameWindowManager.GetWindowHandle();
}
/// <summary>
/// Enables or disables the "maximize box" for the game form.
/// </summary>
public void SetMaximizeBox(bool value) => gameWindowManager.SetMaximizeBox(value);
/// <summary>
/// Enables or disables the "control box" (minimize/maximize/close buttons) for the game form.
/// </summary>
/// <param name="value">True to enable the control box, false to disable it.</param>
public void SetControlBox(bool value)
{
gameWindowManager.SetControlBox(value);
}
/// <summary>
/// Prevents the user from closing the game form by Alt-F4.
/// </summary>
public void PreventClosing()
{
gameWindowManager.PreventClosing();
}
/// <summary>
/// Allows the user to close the game form by Alt-F4.
/// </summary>
public void AllowClosing()
{
gameWindowManager.AllowClosing();
}
#endif
/// <summary>
/// Removes a control from the window manager.
/// </summary>
/// <param name="control">The control to remove.</param>
public void RemoveControl(XNAControl control)
{
Controls.Remove(control);
}
/// <summary>
/// Enables or disables VSync.
/// </summary>
/// <param name="value">A boolean that determines whether VSync should be enabled or disabled.</param>
public void SetVSync(bool value)
{
graphics.SynchronizeWithVerticalRetrace = value;
}
public void SetFinalRenderTarget()
{
GraphicsDevice.SetRenderTarget(renderTarget);
}
public RenderTarget2D GetFinalRenderTarget()
{
return renderTarget;
}
/// <summary>
/// Re-orders controls by their update order.
/// </summary>
public void ReorderControls()
{
Controls = Controls.OrderBy(control => control.Detached).ThenBy(control => control.UpdateOrder).ToList();
}
/// <summary>
/// Attempt to set the display mode to the desired resolution. Itterates through the display
/// capabilities of the default graphics adapter to determine if the graphics adapter supports the
/// requested resolution. If so, the resolution is set and the function returns true. If not,
/// no change is made and the function returns false.
/// </summary>
/// <param name="iWidth">Desired screen width.</param>
/// <param name="iHeight">Desired screen height.</param>
/// <param name="bFullScreen">True if you wish to go to Full Screen, false for Windowed Mode.</param>
public bool InitGraphicsMode(int iWidth, int iHeight, bool bFullScreen)
{
Logger.Log("InitGraphicsMode: " + iWidth + "x" + iHeight);
WindowWidth = iWidth;
WindowHeight = iHeight;
// If we aren't using a full screen mode, the height and width of the window can
// be set to anything equal to or smaller than the actual screen size.
if (bFullScreen == false)
{
if ((iWidth <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width)
&& (iHeight <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height))
{
#if WINFORMS
gameWindowManager.ClientSizeChanged -= GameWindowManager_ClientSizeChanged;
#endif
graphics.PreferredBackBufferWidth = iWidth;
graphics.PreferredBackBufferHeight = iHeight;
graphics.IsFullScreen = bFullScreen;
graphics.ApplyChanges();
RecalculateScaling();
#if WINFORMS
gameWindowManager.ClientSizeChanged += GameWindowManager_ClientSizeChanged;
#endif
return true;
}
}
else
{
// If we are using full screen mode, we should check to make sure that the display
// adapter can handle the video mode we are trying to set. To do this, we will
// iterate thorugh the display modes supported by the adapter and check them against
// the mode we want to set.
foreach (DisplayMode dm in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
{
// Check the width and height of each mode against the passed values
if ((dm.Width == iWidth) && (dm.Height == iHeight))
{
// The mode is supported, so set the buffer formats, apply changes and return
#if WINFORMS
gameWindowManager.ClientSizeChanged -= GameWindowManager_ClientSizeChanged;
#endif
graphics.PreferredBackBufferWidth = iWidth;
graphics.PreferredBackBufferHeight = iHeight;
graphics.IsFullScreen = bFullScreen;
graphics.ApplyChanges();
RecalculateScaling();
#if WINFORMS
gameWindowManager.ClientSizeChanged += GameWindowManager_ClientSizeChanged;
#endif
return true;
}
}
}
return false;
}
/// <summary>
/// Returns whether the game is running in fullscreen mode.
/// </summary>
public bool IsFullscreen => graphics.IsFullScreen;
/// <summary>
/// Updates the WindowManager. Do not call manually; MonoGame will call
/// this automatically on every game frame.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
HasFocus = gameWindowManager.HasFocus();
lock (locker)
{
if (Callbacks.Count > 0)
{
List<Callback> callbacks = Callbacks;
Callbacks = new List<Callback>();
foreach (Callback c in callbacks)
c.Invoke();
}
}
if (HasFocus)
Keyboard.Update(gameTime);
Cursor.Update(gameTime);
SoundPlayer.Update(gameTime);
UpdateControls(gameTime);
base.Update(gameTime);
}
private void UpdateControls(GameTime gameTime)
{
ActiveControl = null;
for (int i = Controls.Count - 1; i > -1; i--)
{
XNAControl control = Controls[i];
// Before calling the control's Update, check whether the control is currently under the mouse cursor.
if (HasFocus && control.InputEnabled && control.Enabled &&
(ActiveControl == null && control.GetWindowRectangle().Contains(Cursor.Location) || control.Focused))
{
ActiveControl = control;
}
if (control.Enabled)
{
control.Update(gameTime);
// In case ActiveControl points to the control after its Update routine has been called,
// that means that none of the control's children handled input.
// In case the control is InputPassthrough, clear the active control to give
// underlying controls a chance to handle input instead.
// Also check for the control's children to enable children to be InputPassthrough.
if (ActiveControl != null && ActiveControl.InputPassthrough && (ActiveControl == control || control.IsParentOf(ActiveControl)))
{
control.IsActive = false;
ActiveControl = null;
}
// If this control or one of its children is the active control,
// then handle mouse input on the active control.
if (ActiveControl != null && control.IsActive)
{
bool isInputCaptured = IsInputExclusivelyCaptured && SelectedControl != ActiveControl;
if (Cursor.LeftPressedDown)
{
if (!isInputCaptured)
{
ActiveControl.IsLeftPressedOn = true;
var args = new InputEventArgs();
PropagateInputEventTunneling(static (c, ie) => c.OnPreviewMouseLeftDown(ie), MouseInputFlags.LeftMouseButton, args);
if (!args.Handled)
PropagateInputEvent(static (c, ie) => c.OnMouseLeftDown(ie), MouseInputFlags.LeftMouseButton, args);
}
}
else if (!Cursor.LeftDown && ActiveControl.IsLeftPressedOn)
{
ActiveControl.IsLeftPressedOn = false;
var args = new InputEventArgs();
PropagateInputEventTunneling(static (c, ie) => c.OnPreviewLeftClick(ie), MouseInputFlags.LeftMouseButton, args);
if (!args.Handled)
PropagateInputEvent(static (c, ie) => c.OnLeftClick(ie), MouseInputFlags.LeftMouseButton, args);
}
if (Cursor.RightPressedDown)
{
if (!isInputCaptured)
{
ActiveControl.IsRightPressedOn = true;
var args = new InputEventArgs();
PropagateInputEventTunneling(static (c, ie) => c.OnPreviewMouseRightDown(ie), MouseInputFlags.RightMouseButton, args);
if (!args.Handled)
PropagateInputEvent(static (c, ie) => c.OnMouseRightDown(ie), MouseInputFlags.RightMouseButton, args);
}
}
else if (!Cursor.RightDown && ActiveControl.IsRightPressedOn)
{
ActiveControl.IsRightPressedOn = false;
var args = new InputEventArgs();
PropagateInputEventTunneling(static (c, ie) => c.OnPreviewRightClick(ie), MouseInputFlags.RightMouseButton, args);
if (!args.Handled)
PropagateInputEvent(static (c, ie) => c.OnRightClick(ie), MouseInputFlags.RightMouseButton, args);
}
if (Cursor.MiddlePressedDown)
{
if (!isInputCaptured)
{
ActiveControl.IsMiddlePressedOn = true;
var args = new InputEventArgs();
PropagateInputEventTunneling(static (c, ie) => c.OnPreviewMouseMiddleDown(ie), MouseInputFlags.MiddleMouseButton, args);
if (!args.Handled)
PropagateInputEvent(static (c, ie) => c.OnMouseMiddleDown(ie), MouseInputFlags.MiddleMouseButton, args);
}
}
else if (!Cursor.MiddleDown && ActiveControl.IsMiddlePressedOn)
{
ActiveControl.IsMiddlePressedOn = false;
var args = new InputEventArgs();
PropagateInputEventTunneling(static (c, ie) => c.OnPreviewMiddleClick(ie), MouseInputFlags.MiddleMouseButton, args);
if (!args.Handled)
PropagateInputEvent(static (c, ie) => c.OnMiddleClick(ie), MouseInputFlags.MiddleMouseButton, args);
}
if (Cursor.ScrollWheelValue != 0 && !isInputCaptured)
{
var scrollArgs = new InputEventArgs();
PropagateInputEventTunneling(static (c, ie) => c.OnPreviewMouseScrolled(ie), MouseInputFlags.ScrollWheel, scrollArgs);
if (!scrollArgs.Handled)
PropagateInputEvent(static (c, ie) => c.OnMouseScrolled(ie), MouseInputFlags.ScrollWheel, scrollArgs);
}
if (Cursor.HorizontalScrollWheelValue != 0 && !isInputCaptured)
{
var scrollArgs = new InputEventArgs();
PropagateInputEventTunneling(static (c, ie) => c.OnPreviewMouseScrolledHorizontally(ie), MouseInputFlags.ScrollWheelHorizontal, scrollArgs);
if (!scrollArgs.Handled)
PropagateInputEvent(static (c, ie) => c.OnMouseScrolledHorizontally(ie), MouseInputFlags.ScrollWheelHorizontal, scrollArgs);
}
}
}
}
// Make sure that, if input is exclusively captured:
// 1) a mouse button is held down
// 2) the control that is capturing the input is visible and enabled
// If either of these conditions is not true, then release the exclusively captured input.
if (SelectedControl != null && SelectedControl.ExclusiveInputCapture)
{
if ((!Cursor.RightDown && !Cursor.LeftDown) ||
!SelectedControl.AppliesToSelfAndAllParents(p => p.Enabled && p.InputEnabled))
{
SelectedControl = null;
}
}
}
private void PropagateInputEvent(Action<XNAControl, InputEventArgs> action, MouseInputFlags mouseInputFlags)
=> PropagateInputEvent(action, mouseInputFlags, new InputEventArgs());
private void PropagateInputEvent(Action<XNAControl, InputEventArgs> action, MouseInputFlags mouseInputFlags, InputEventArgs inputEventArgs)
{
XNAControl control = ActiveControl;
while (control != null)
{
if (!control.InputPassthrough)
{
if ((control.HandledMouseInputs & mouseInputFlags) == mouseInputFlags)
inputEventArgs.Handled = true;
action(control, inputEventArgs);
if (inputEventArgs.Handled)
break;
}
control = control.Parent;
}
}
private void PropagateInputEventTunneling(Action<XNAControl, InputEventArgs> action, MouseInputFlags mouseInputFlags, InputEventArgs inputEventArgs)
{
// Fire events top-down
// Build the path from ActiveControl up to the root
_tunnelingPath.Clear();
var control = ActiveControl;
while (control != null)
{
_tunnelingPath.Add(control);
control = control.Parent;
}
for (int i = _tunnelingPath.Count - 1; i >= 0; i--)
{
var c = _tunnelingPath[i];
if (!c.InputPassthrough)
{
bool stopTunneling = (c.HandledMouseInputs & mouseInputFlags) == mouseInputFlags;
action(c, inputEventArgs);
if (inputEventArgs.Handled || stopTunneling)
break;
}
}
}
/// <summary>
/// Draws all the visible controls in the WindowManager.
/// Do not call manually; MonoGame calls this automatically.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Draw(GameTime gameTime)
{
#if XNA
// This is a workaround. Should fix this in FontStashSharp.XNA.
// In FontStashSharp.XNA 1.5.5, Texture2DManager.SetTextureData saves all 16 device. Textures slots and
// restores them after uploading glyph data. If the previous frame's blit left renderTarget
// bound in a slot, restoring it while renderTarget is the active render target throws
// InvalidOperationException. Clear all slots first to prevent that.
for (int i = 0; i < 16; i++)
GraphicsDevice.Textures[i] = null;
#endif
GraphicsDevice.SetRenderTarget(renderTarget);
GraphicsDevice.Clear(Color.Black);
Renderer.ClearStack();
Renderer.CurrentSettings = new SpriteBatchSettings(
SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null);
Renderer.BeginDraw();
for (int i = 0; i < Controls.Count; i++)
{
var control = Controls[i];
if (control.Visible)
control.DrawInternal(gameTime);
}
Renderer.EndDraw();
if (doubledRenderTarget != null)
{
GraphicsDevice.SetRenderTarget(doubledRenderTarget);
GraphicsDevice.Clear(Color.Black);
Renderer.CurrentSettings = new SpriteBatchSettings(SpriteSortMode.Deferred,
BlendState.NonPremultiplied, SamplerState.PointWrap, null, null, null);
Renderer.BeginDraw();
Renderer.DrawTexture(renderTarget, new Rectangle(0, 0,
RenderResolutionX * 2, RenderResolutionY * 2), Color.White);
Renderer.EndDraw();
}
GraphicsDevice.SetRenderTarget(null);
//if (Keyboard.PressedKeys.Contains(Microsoft.Xna.Framework.Input.Keys.F12))
//{
// FileStream fs = File.Create(Environment.CurrentDirectory + "\\image.png");
// renderTarget.SaveAsPng(fs, renderTarget.Width, renderTarget.Height);
// fs.Close();
//}
GraphicsDevice.Clear(Color.Black);
SamplerState scalingSamplerState = SamplerState.LinearClamp;
if (ScaleRatio % 1.0 == 0)
scalingSamplerState = SamplerState.PointClamp;
Renderer.CurrentSettings = new SpriteBatchSettings(SpriteSortMode.Deferred,
BlendState.NonPremultiplied, scalingSamplerState, null, null, null);
Renderer.BeginDraw();
RenderTarget2D renderTargetToDraw = doubledRenderTarget ?? renderTarget;
Renderer.DrawTexture(renderTargetToDraw, new Rectangle(SceneXPosition, SceneYPosition,
Game.Window.ClientBounds.Width - (SceneXPosition * 2), Game.Window.ClientBounds.Height - (SceneYPosition * 2)), Color.White);
#if DEBUG
Renderer.DrawString("Active control: " + (ActiveControl == null ? "none" : ActiveControl.Name), 0, Vector2.Zero, Color.Red, 1.0f);
if (IMEHandler != null && IMEHandler.TextCompositionEnabled)
{
Renderer.DrawString("IME Enabled", 0, new Vector2(0, 16), Color.Red, 1.0f);
}
#endif
if (Cursor.Visible)
Cursor.Draw(gameTime);
Renderer.EndDraw();
base.Draw(gameTime);
}
}