A game framework written with osu! in mind.
1// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
2// See the LICENCE file in the repository root for full licence text.
3
4using System;
5using Android.Views;
6using osu.Framework.Input;
7using osu.Framework.Input.Handlers;
8using osu.Framework.Input.StateChanges;
9using osu.Framework.Input.States;
10using osu.Framework.Platform;
11using osuTK;
12using osuTK.Input;
13
14namespace osu.Framework.Android.Input
15{
16 public class AndroidTouchHandler : InputHandler
17 {
18 private readonly AndroidGameView view;
19
20 public override bool IsActive => true;
21
22 public AndroidTouchHandler(AndroidGameView view)
23 {
24 this.view = view;
25 view.Touch += handleTouch;
26 view.Hover += handleHover;
27 }
28
29 public override bool Initialize(GameHost host) => true;
30
31 private void handleTouch(object sender, View.TouchEventArgs e)
32 {
33 if (e.Event.Action == MotionEventActions.Move)
34 {
35 for (int i = 0; i < Math.Min(e.Event.PointerCount, TouchState.MAX_TOUCH_COUNT); i++)
36 {
37 var touch = getEventTouch(e.Event, i);
38 PendingInputs.Enqueue(new TouchInput(touch, true));
39 }
40 }
41 else if (e.Event.ActionIndex < TouchState.MAX_TOUCH_COUNT)
42 {
43 var touch = getEventTouch(e.Event, e.Event.ActionIndex);
44
45 switch (e.Event.ActionMasked)
46 {
47 case MotionEventActions.Down:
48 case MotionEventActions.PointerDown:
49 PendingInputs.Enqueue(new TouchInput(touch, true));
50 break;
51
52 case MotionEventActions.Up:
53 case MotionEventActions.PointerUp:
54 case MotionEventActions.Cancel:
55 PendingInputs.Enqueue(new TouchInput(touch, false));
56 break;
57 }
58 }
59 }
60
61 private void handleHover(object sender, View.HoverEventArgs e)
62 {
63 PendingInputs.Enqueue(new MousePositionAbsoluteInput { Position = getEventPosition(e.Event) });
64 PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Right, e.Event.ButtonState == MotionEventButtonState.StylusPrimary));
65 }
66
67 private Touch getEventTouch(MotionEvent e, int index) => new Touch((TouchSource)e.GetPointerId(index), getEventPosition(e, index));
68 private Vector2 getEventPosition(MotionEvent e, int index = 0) => new Vector2(e.GetX(index) * view.ScaleX, e.GetY(index) * view.ScaleY);
69
70 protected override void Dispose(bool disposing)
71 {
72 view.Touch -= handleTouch;
73 view.Hover -= handleHover;
74 base.Dispose(disposing);
75 }
76 }
77}