forked from ppy/osu-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AndroidGameView.cs
385 lines (317 loc) · 14.4 KB
/
AndroidGameView.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
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Runtime.Versioning;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Text;
using Android.Util;
using Android.Views;
using Android.Views.InputMethods;
using osu.Framework.Android.Input;
using osu.Framework.Logging;
using osu.Framework.Bindables;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Platform;
using osuTK.Graphics;
namespace osu.Framework.Android
{
public class AndroidGameView : osuTK.Android.AndroidGameView
{
public AndroidGameHost? Host { get; private set; }
public AndroidGameActivity Activity { get; } = null!;
public BindableSafeArea SafeAreaPadding { get; } = new BindableSafeArea();
/// <summary>
/// Represents whether the mouse pointer is captured, as reported by Android through <see cref="OnPointerCaptureChange"/>.
/// </summary>
private bool pointerCaptured;
/// <summary>
/// Set Android's pointer capture.
/// </summary>
/// <remarks>
/// Only available in Android 8.0 Oreo (<see cref="BuildVersionCodes.O"/>) and up.
/// </remarks>
public bool PointerCapture
{
get => pointerCaptured;
set
{
if (!OperatingSystem.IsAndroidVersionAtLeast(26))
{
Logger.Log($"Tried to set {nameof(PointerCapture)} on an unsupported Android version.", level: LogLevel.Important);
return;
}
if (pointerCaptured == value) return;
if (value)
RequestPointerCapture();
else
ReleasePointerCapture();
}
}
private readonly Game game = null!;
private InputMethodManager? inputMethodManager;
/// <summary>
/// Whether <see cref="AndroidTextInput"/> is active.
/// </summary>
private bool textInputActive;
public AndroidGameView(AndroidGameActivity activity, Game game)
: base(activity)
{
Activity = activity;
this.game = game;
init();
}
public AndroidGameView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
init();
}
public AndroidGameView(IntPtr handle, JniHandleOwnership transfer)
: base(handle, transfer)
{
init();
}
private void init()
{
AutoSetContextOnRenderFrame = true;
ContextRenderingApi = GLVersion.ES3;
// enable soft and hardware keyboard
// this needs to happen in the constructor
Focusable = true;
FocusableInTouchMode = true;
if (OperatingSystem.IsAndroidVersionAtLeast(26))
{
// disable ugly green border when view is focused via hardware keyboard/mouse.
DefaultFocusHighlightEnabled = false;
}
inputMethodManager = Activity.GetSystemService(Context.InputMethodService) as InputMethodManager;
}
protected override void CreateFrameBuffer()
{
try
{
base.CreateFrameBuffer();
Log.Verbose("AndroidGameView", "Successfully created the framebuffer");
}
catch (Exception e)
{
Log.Verbose("AndroidGameView", "{0}", e);
throw new InvalidOperationException("Can't load egl, aborting", e);
}
}
public bool OnCommitText(string text)
{
CommitText?.Invoke(text);
return false;
}
public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent? e)
{
if (e == null) return base.OnKeyDown(keyCode, e);
switch (keyCode)
{
// Do not consume Volume keys, so the system can handle them
case Keycode.VolumeDown:
case Keycode.VolumeUp:
case Keycode.VolumeMute:
return false;
default:
KeyDown?.Invoke(keyCode, e);
// Releasing backspace on a physical keyboard when text input is active will not send a key up event.
// Manually send one to prevent the key from getting stuck.
// This does mean that key repeat is handled by the OS, instead of by the usual `InputManager` handling.
if (keyCode == Keycode.Del && e.IsFromSource(InputSourceType.Keyboard) && textInputActive)
KeyUp?.Invoke(Keycode.Del, new KeyEvent(e.DownTime, e.EventTime, KeyEventActions.Up, Keycode.Del, 0, e.MetaState, e.DeviceId, e.ScanCode, e.Flags, e.Source));
return true;
}
}
public override bool OnKeyLongPress([GeneratedEnum] Keycode keyCode, KeyEvent? e)
{
if (e == null) return base.OnKeyLongPress(keyCode, e);
KeyLongPress?.Invoke(keyCode, e);
return true;
}
public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent? e)
{
if (e == null) return base.OnKeyUp(keyCode, e);
KeyUp?.Invoke(keyCode, e);
return true;
}
[SupportedOSPlatform("android26.0")]
public override void OnPointerCaptureChange(bool hasCapture)
{
base.OnPointerCaptureChange(hasCapture);
pointerCaptured = hasCapture;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// osuTK calls `OnLoad()` every time the application surface is created, which will also happen upon a resume,
// at which point the host is already present and running, so there is no reason to create another one.
if (Host == null)
RenderGame();
}
[STAThread]
public void RenderGame()
{
// request focus so that joystick input can immediately work.
RequestFocus();
LayoutChange += (_, _) => updateSafeArea();
Activity.IsActive.BindValueChanged(active =>
{
// When rotating device 180 degrees in the background,
// LayoutChange doesn't trigger after returning to game.
// So update safe area once active again.
if (active.NewValue)
updateSafeArea();
});
updateSafeArea();
Host = new AndroidGameHost(this);
Host.ExceptionThrown += handleException;
Host.Run(game);
HostStarted?.Invoke(Host);
}
private bool handleException(Exception ex)
{
// suppress exceptions related to MobileAuthenticatedStream disposal
// (see: https://github.com/ppy/osu/issues/6264 and linked related mono/xamarin issues)
// to be removed when upstream fixes come in
return ex is AggregateException ae
&& ae.InnerException is ObjectDisposedException ode
&& ode.ObjectName == "MobileAuthenticatedStream";
}
/// <summary>
/// Updates the <see cref="IWindow.SafeAreaPadding"/>, taking into account screen insets that may be obstructing this <see cref="AndroidGameView"/>.
/// </summary>
private void updateSafeArea()
{
// compute the usable screen area.
var screenSize = new Point();
#pragma warning disable 618 // GetRealSize is deprecated
Display.AsNonNull().GetRealSize(screenSize);
#pragma warning restore 618
var screenArea = new RectangleI(0, 0, screenSize.X, screenSize.Y);
var usableScreenArea = screenArea;
if (OperatingSystem.IsAndroidVersionAtLeast(28))
{
var cutout = RootWindowInsets?.DisplayCutout;
if (cutout != null)
usableScreenArea = usableScreenArea.Shrink(cutout.SafeInsetLeft, cutout.SafeInsetRight, cutout.SafeInsetTop, cutout.SafeInsetBottom);
}
if (OperatingSystem.IsAndroidVersionAtLeast(31) && RootWindowInsets != null)
{
var topLeftCorner = RootWindowInsets.GetRoundedCorner((int)RoundedCornerPosition.TopLeft);
var topRightCorner = RootWindowInsets.GetRoundedCorner((int)RoundedCornerPosition.TopRight);
var bottomLeftCorner = RootWindowInsets.GetRoundedCorner((int)RoundedCornerPosition.BottomLeft);
var bottomRightCorner = RootWindowInsets.GetRoundedCorner((int)RoundedCornerPosition.BottomRight);
int cornerInsetLeft = Math.Max(topLeftCorner?.Radius ?? 0, bottomLeftCorner?.Radius ?? 0);
int cornerInsetRight = Math.Max(topRightCorner?.Radius ?? 0, bottomRightCorner?.Radius ?? 0);
int cornerInsetTop = Math.Max(topLeftCorner?.Radius ?? 0, topRightCorner?.Radius ?? 0);
int cornerInsetBottom = Math.Max(bottomLeftCorner?.Radius ?? 0, bottomRightCorner?.Radius ?? 0);
var radiusInsetArea = screenArea.Width >= screenArea.Height
? screenArea.Shrink(cornerInsetLeft, cornerInsetRight, 0, 0)
: screenArea.Shrink(0, 0, cornerInsetTop, cornerInsetBottom);
usableScreenArea = usableScreenArea.Intersect(radiusInsetArea);
}
if (OperatingSystem.IsAndroidVersionAtLeast(24) && Activity.IsInMultiWindowMode)
{
// if we are in multi-window mode, the status bar is always visible (even if we request to hide it) and could be obstructing our view.
// if multi-window mode is not active, we can assume the status bar is hidden so we shouldn't consider it for safe area calculations.
// `SystemWindowInsetTop` should be the correct inset here, but it doesn't correctly work (gives `0` even if the view is obstructed).
#pragma warning disable 618 // StableInsetTop is deprecated
int statusBarHeight = RootWindowInsets?.StableInsetTop ?? 0;
#pragma warning restore 618 //
usableScreenArea = usableScreenArea.Intersect(screenArea.Shrink(0, 0, statusBarHeight, 0));
}
// compute the location/area of this view on the screen.
int[] location = new int[2];
GetLocationOnScreen(location);
var viewArea = new RectangleI(location[0], location[1], ((View)this).Width, ((View)this).Height);
// intersect with the usable area and treat the the difference as unsafe.
var usableViewArea = viewArea.Intersect(usableScreenArea);
SafeAreaPadding.Value = new MarginPadding
{
Left = usableViewArea.Left - viewArea.Left,
Top = usableViewArea.Top - viewArea.Top,
Right = viewArea.Right - usableViewArea.Right,
Bottom = viewArea.Bottom - usableViewArea.Bottom,
};
}
public override bool OnCheckIsTextEditor() => textInputActive;
/// <returns><c>null</c> to disable input methods</returns>
public override IInputConnection? OnCreateInputConnection(EditorInfo? outAttrs)
{
ArgumentNullException.ThrowIfNull(outAttrs);
// Properly disable native input methods so that the software keyboard doesn't unexpectedly open.
// Eg. when pressing keys on a hardware keyboard.
if (!textInputActive)
return null;
outAttrs.ImeOptions = ImeFlags.NoExtractUi | ImeFlags.NoFullscreen;
outAttrs.InputType = InputTypes.TextVariationVisiblePassword | InputTypes.TextFlagNoSuggestions;
return new AndroidInputConnection(this, true);
}
internal void StartTextInput()
{
textInputActive = true;
Activity.RunOnUiThread(() =>
{
inputMethodManager?.RestartInput(this); // this syncs the Android input method state with `OnCreateInputConnection()`.
RequestFocus();
inputMethodManager?.ShowSoftInput(this, 0);
});
}
internal void StopTextInput()
{
textInputActive = false;
Activity.RunOnUiThread(() =>
{
inputMethodManager?.RestartInput(this);
inputMethodManager?.HideSoftInputFromWindow(WindowToken, HideSoftInputFlags.None);
});
}
public override void SwapBuffers()
{
try
{
base.SwapBuffers();
}
catch (GraphicsContextException ex)
{
// sometimes buffers will spontaneously fail to swap with BAD_SURFACE
// just before the activity is suspended to background or just after it has been resumed,
// but will continue operating correctly after that transitionary period.
// despite some testing it is unclear which view callback can be used to tell whether it is safe to swap buffers,
// so for now just catch and suppress these errors.
if (ex.Message.Contains("BAD_SURFACE", StringComparison.Ordinal))
Logger.Log($"BAD_SURFACE failure in {nameof(SwapBuffers)} suppressed");
else
throw;
}
}
#region Events
/// <summary>
/// Invoked on a key down event.
/// </summary>
public new event Action<Keycode, KeyEvent>? KeyDown;
/// <summary>
/// Invoked on a key up event.
/// </summary>
public new event Action<Keycode, KeyEvent>? KeyUp;
/// <summary>
/// Invoked on a key long press event.
/// </summary>
public event Action<Keycode, KeyEvent>? KeyLongPress;
/// <summary>
/// Invoked when text is committed by an <see cref="AndroidInputConnection"/>.
/// </summary>
public event Action<string>? CommitText;
/// <summary>
/// Invoked when the <see cref="game"/> has been started on the <see cref="Host"/>.
/// </summary>
public event Action<AndroidGameHost>? HostStarted;
#endregion
}
}