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.Content;
6using Android.Views;
7using Android.Views.InputMethods;
8using osu.Framework.Input;
9
10namespace osu.Framework.Android.Input
11{
12 public class AndroidTextInput : ITextInputSource
13 {
14 private readonly AndroidGameView view;
15 private readonly AndroidGameActivity activity;
16 private readonly InputMethodManager inputMethodManager;
17 private string pending = string.Empty;
18 private readonly object pendingLock = new object();
19
20 public AndroidTextInput(AndroidGameView view)
21 {
22 this.view = view;
23 activity = (AndroidGameActivity)view.Context;
24
25 inputMethodManager = view.Context.GetSystemService(Context.InputMethodService) as InputMethodManager;
26 }
27
28 public void Deactivate()
29 {
30 activity.RunOnUiThread(() =>
31 {
32 inputMethodManager.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
33 view.ClearFocus();
34 view.KeyDown -= keyDown;
35 view.CommitText -= commitText;
36 });
37 }
38
39 public string GetPendingText()
40 {
41 lock (pendingLock)
42 {
43 var oldPending = pending;
44 pending = string.Empty;
45 return oldPending;
46 }
47 }
48
49 private void commitText(string text)
50 {
51 OnNewImeComposition?.Invoke(text);
52 OnNewImeResult?.Invoke(text);
53 }
54
55 private void keyDown(Keycode arg, KeyEvent e)
56 {
57 if (e.UnicodeChar != 0)
58 pending += (char)e.UnicodeChar;
59 }
60
61 public bool ImeActive => false;
62
63 public event Action<string> OnNewImeComposition;
64 public event Action<string> OnNewImeResult;
65
66 public void Activate()
67 {
68 activity.RunOnUiThread(() =>
69 {
70 view.RequestFocus();
71 inputMethodManager.ShowSoftInput(view, 0);
72 view.KeyDown += keyDown;
73 view.CommitText += commitText;
74 });
75 }
76
77 public void EnsureActivated()
78 {
79 activity.RunOnUiThread(() =>
80 {
81 inputMethodManager.ShowSoftInput(view, 0);
82 });
83 }
84 }
85}