forked from ppy/osu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOsuGameActivity.cs
More file actions
359 lines (307 loc) · 15.1 KB
/
Copy pathOsuGameActivity.cs
File metadata and controls
359 lines (307 loc) · 15.1 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
// 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.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using osu.Framework.Android;
using osu.Framework.Extensions;
using osu.Game.Database;
using Debug = System.Diagnostics.Debug;
namespace osu.Android
{
[global::Android.App.Activity(ConfigurationChanges = global::Android.Content.PM.ConfigChanges.Orientation | global::Android.Content.PM.ConfigChanges.ScreenSize | global::Android.Content.PM.ConfigChanges.UiMode, Exported = true, LaunchMode = global::Android.Content.PM.LaunchMode.SingleInstance, MainLauncher = true)]
[global::Android.App.IntentFilter(new[] { "android.intent.action.VIEW" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataScheme = "content", DataPathPattern = ".*\\.osz", DataHost = "*", DataMimeType = "*/*")]
[global::Android.App.IntentFilter(new[] { "android.intent.action.VIEW" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataScheme = "content", DataPathPattern = ".*\\.osk", DataHost = "*", DataMimeType = "*/*")]
[global::Android.App.IntentFilter(new[] { "android.intent.action.VIEW" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataScheme = "content", DataPathPattern = ".*\\.osr", DataHost = "*", DataMimeType = "*/*")]
[global::Android.App.IntentFilter(new[] { "android.intent.action.VIEW" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataScheme = "content", DataMimeType = "application/x-osu-beatmap-archive")]
[global::Android.App.IntentFilter(new[] { "android.intent.action.VIEW" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataScheme = "content", DataMimeType = "application/x-osu-skin-archive")]
[global::Android.App.IntentFilter(new[] { "android.intent.action.VIEW" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataScheme = "content", DataMimeType = "application/x-osu-replay")]
[global::Android.App.IntentFilter(new[] { "android.intent.action.SEND", "android.intent.action.SEND_MULTIPLE" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataMimeTypes = new[]
{
"application/zip",
"application/octet-stream",
"application/download",
"application/x-zip",
"application/x-zip-compressed",
"application/x-osu-beatmap-archive",
"application/x-osu-skin-archive",
"application/x-osu-replay",
})]
[global::Android.App.IntentFilter(new[] { "android.intent.action.VIEW" }, Categories = new[] { "android.intent.category.BROWSABLE", "android.intent.category.DEFAULT" }, DataSchemes = new[] { "osu", "osump" })]
public class OsuGameActivity : AndroidGameActivity
{
public override bool DispatchTouchEvent(global::Android.Views.MotionEvent? e)
{
if (e != null)
{
for (int i = 0; i < e.PointerCount; i++)
{
var toolType = e.GetToolType(i);
if (toolType == global::Android.Views.MotionEventToolType.Stylus)
{
// S Pen detected. Hardware timestamps should be used for improved latency.
// Using EventTime * 1000000 for maximum SDK compatibility as EventTimeNano is sometimes unavailable at compile-time.
long timestampNano = e.EventTime * 1000000;
// Process historical points for smoother/predicted input
for (int h = 0; h < e.HistorySize; h++)
{
float historicalX = e.GetHistoricalX(i, h);
float historicalY = e.GetHistoricalY(i, h);
long historicalTimeNano = e.GetHistoricalEventTime(h) * 1000000;
game.HandleStylusInput(historicalX, historicalY, historicalTimeNano);
}
}
}
}
return base.DispatchTouchEvent(e);
}
public new bool IsDeXMode()
{
var config = Resources?.Configuration;
if (config == null) return false;
return (config.UiMode & global::Android.Content.Res.UiMode.TypeMask) == global::Android.Content.Res.UiMode.TypeDesk;
}
public void ApplyPerformanceOptimizations(bool enabled)
{
RunOnUiThread(() =>
{
var window = Window;
if (window != null)
window.SetSustainedPerformanceMode(enabled);
bool dexMode = IsDeXMode();
var display = WindowManager?.DefaultDisplay;
if ((enabled || dexMode) && display != null)
{
#pragma warning disable CA1422
var modes = display.GetSupportedModes();
var preferredMode = modes?.OrderByDescending(m => m.RefreshRate).FirstOrDefault();
if (preferredMode != null && window != null)
{
var layoutParams = window.Attributes;
if (layoutParams != null)
{
layoutParams.PreferredDisplayModeId = preferredMode.ModeId;
window.Attributes = layoutParams;
}
}
#pragma warning restore CA1422
}
});
}
public void ApplyAngleOptimizations(bool enabled)
{
// ANGLE (GLES to Vulkan) translation logic placeholder.
}
private static readonly string[] osu_url_schemes = { "osu", "osump" };
/// <summary>
/// The default screen orientation.
/// </summary>
/// <remarks>Adjusted on startup to match expected UX for the current device type (phone/tablet).</remarks>
public global::Android.Content.PM.ScreenOrientation DefaultOrientation = global::Android.Content.PM.ScreenOrientation.Unspecified;
public new bool IsTablet { get; private set; }
private readonly OsuGameAndroid game;
private bool gameCreated;
protected override global::osu.Framework.Game CreateGame()
{
if (gameCreated)
throw new InvalidOperationException("Framework tried to create a game twice.");
gameCreated = true;
return game;
}
public OsuGameActivity()
{
game = new OsuGameAndroid(this);
}
protected override void OnStart()
{
base.OnStart();
Window?.DecorView?.RequestUnbufferedDispatch((int)global::Android.Views.InputSourceType.Touchscreen);
}
protected override void OnCreate(global::Android.OS.Bundle? savedInstanceState)
{
base.OnCreate(savedInstanceState);
try
{
global::Java.Lang.JavaSystem.LoadLibrary("osu.Android.Native");
}
catch (Exception e)
{
global::Android.Util.Log.Error("OsuGameActivity", $"Failed to load native library: {e}");
}
// OnNewIntent() only fires for an activity if it's *re-launched* while it's on top of the activity stack.
// on first launch we still have to fire manually.
// reference: https://developer.android.com/reference/android/app/Activity#onNewIntent(android.content.Intent)
handleIntent(Intent);
if (Window != null)
{
Window.AddFlags(global::Android.Views.WindowManagerFlags.Fullscreen);
Window.AddFlags(global::Android.Views.WindowManagerFlags.KeepScreenOn);
}
else
{
global::Android.Util.Log.Warn("OsuGameActivity", "Window is null in OnCreate, flags not set.");
}
if (WindowManager?.DefaultDisplay != null && Resources?.DisplayMetrics != null)
{
global::Android.Graphics.Point displaySize = new global::Android.Graphics.Point();
#pragma warning disable CA1422 // GetSize is deprecated
WindowManager.DefaultDisplay.GetSize(displaySize);
#pragma warning restore CA1422
float smallestWidthDp = Math.Min(displaySize.X, displaySize.Y) / Resources.DisplayMetrics.Density;
IsTablet = smallestWidthDp >= 600f;
}
else
{
global::Android.Util.Log.Warn("OsuGameActivity", "WindowManager.DefaultDisplay or Resources.DisplayMetrics is null in OnCreate.");
}
RequestedOrientation = DefaultOrientation = IsTablet ? global::Android.Content.PM.ScreenOrientation.FullUser : global::Android.Content.PM.ScreenOrientation.SensorLandscape;
// Currently (SDK 6.0.200), BundleAssemblies is not runnable for net6-android.
// The assembly files are not available as files either after native AOT.
// Manually load them so that they can be loaded by RulesetStore.loadFromAppDomain.
// REMEMBER to fully uninstall previous version every time when investigating this!
// Don't forget osu.Game.Tests.Android too.
try
{
// Using typeof() ensures the linker preserves the assemblies.
Assembly.Load(typeof(osu.Game.Rulesets.Osu.OsuRuleset).Assembly.FullName);
Assembly.Load(typeof(osu.Game.Rulesets.Taiko.TaikoRuleset).Assembly.FullName);
Assembly.Load(typeof(osu.Game.Rulesets.Catch.CatchRuleset).Assembly.FullName);
Assembly.Load(typeof(osu.Game.Rulesets.Mania.ManiaRuleset).Assembly.FullName);
}
catch (Exception e)
{
global::Android.Util.Log.Error("OsuGameActivity", $"Failed to load rulesets: {e}");
}
}
protected override void OnResume()
{
base.OnResume();
var gm = (global::Android.App.GameManager?)GetSystemService(GameService);
if (gm != null)
{
int mode = (int)gm.GameMode;
ApplyPerformanceOptimizations(mode == (int)global::Android.App.GameMode.Performance);
}
CheckInputDevices();
}
private void CheckInputDevices()
{
var inputManager = (global::Android.Hardware.Input.InputManager?)GetSystemService(InputService);
int[] deviceIds = inputManager?.GetInputDeviceIds() ?? Array.Empty<int>();
foreach (int id in deviceIds)
{
var device = inputManager?.GetInputDevice(id);
if (device == null) continue;
if ((device.Sources & global::Android.Views.InputSourceType.Gamepad) == global::Android.Views.InputSourceType.Gamepad)
{
// Gamepad detected
}
}
}
public override void OnConfigurationChanged(global::Android.Content.Res.Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
if (IsDeXMode())
{
ApplyPerformanceOptimizations(true);
}
}
protected override void OnNewIntent(global::Android.Content.Intent? intent) => handleIntent(intent);
private void handleIntent(global::Android.Content.Intent? intent)
{
if (intent == null)
return;
switch (intent.Action)
{
case global::Android.Content.Intent.ActionMain:
case global::Android.Content.Intent.ActionView:
if (intent.Scheme == global::Android.Content.ContentResolver.SchemeContent)
{
if (intent.Data != null)
handleImportFromUris(intent.Data);
}
else if (osu_url_schemes.Contains(intent.Scheme))
{
if (intent.DataString != null)
game.HandleLink(intent.DataString);
}
break;
case global::Android.Content.Intent.ActionSend:
case global::Android.Content.Intent.ActionSendMultiple:
{
if (intent.ClipData == null)
break;
var uris = new List<global::Android.Net.Uri>();
for (int i = 0; i < intent.ClipData.ItemCount; i++)
{
var item = intent.ClipData.GetItemAt(i);
if (item?.Uri != null)
uris.Add(item.Uri);
}
handleImportFromUris(uris.ToArray());
break;
}
}
}
private void handleImportFromUris(params global::Android.Net.Uri[] uris) => Task.Factory.StartNew(async () =>
{
try
{
var tasks = new List<ImportTask>();
await Task.WhenAll(uris.Select(async uri =>
{
if (ContentResolver == null) return;
var task = await AndroidImportTask.Create(ContentResolver, uri).ConfigureAwait(false);
if (task != null)
{
lock (tasks)
{
tasks.Add(task);
}
}
})).ConfigureAwait(false);
await game.Import(tasks.ToArray()).ConfigureAwait(false);
}
catch (Exception ex)
{
global::Android.Util.Log.Error("OsuGameActivity", $"Failed to handle imports: {ex}");
}
}, TaskCreationOptions.LongRunning);
public global::Android.Views.Surface? GetSurface()
{
var rootView = Window?.DecorView;
if (rootView == null) return null;
return findSurfaceView(rootView)?.Holder?.Surface;
}
public IntPtr GetSurfaceGlobalRef()
{
var tcs = new TaskCompletionSource<IntPtr>();
RunOnUiThread(() =>
{
var surface = GetSurface();
if (surface != null && surface.Handle != IntPtr.Zero)
tcs.SetResult(global::Android.Runtime.JNIEnv.NewGlobalRef(surface.Handle));
else
tcs.SetResult(IntPtr.Zero);
});
tcs.Task.WaitSafely();
return tcs.Task.GetResultSafely();
}
private global::Android.Views.SurfaceView? findSurfaceView(global::Android.Views.View? view)
{
if (view == null) return null;
if (view is global::Android.Views.SurfaceView sv) return sv;
if (view is global::Android.Views.ViewGroup vg)
{
for (int i = 0; i < vg.ChildCount; i++)
{
var found = findSurfaceView(vg.GetChildAt(i));
if (found != null) return found;
}
}
return null;
}
}
}