Skip to content

Commit

Permalink
Inject text via ADB keyboard as fallback to injecting key event
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexBurdu authored and Alex committed Mar 22, 2022
1 parent 9fb7f74 commit 63b6044
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
10 changes: 8 additions & 2 deletions server/src/main/java/com/genymobile/scrcpy/Controller.java
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,17 @@ private int injectText(String text) {
int successCount = 0;
for (char c : text.toCharArray()) {
if (!injectChar(c)) {
Ln.w("Could not inject char u+" + String.format("%04x", (int) c));
continue;
continue;
}
successCount++;
}
if (successCount == 0) {
if (device.injectViaAdbKeyboard(text)) {
return text.length();
} else {
Ln.w("Could not inject text " + text);
}
}
return successCount;
}

Expand Down
37 changes: 37 additions & 0 deletions server/src/main/java/com/genymobile/scrcpy/Device.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
import android.view.KeyCharacterMap;
import android.view.KeyEvent;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

public final class Device {
Expand Down Expand Up @@ -210,6 +213,40 @@ public boolean injectKeyEvent(int action, int keyCode, int repeat, int metaState
return injectKeyEvent(action, keyCode, repeat, metaState, displayId, injectMode);
}

/**
* @param text the text to inject via ADB Keyboard
* @return true if the text was successfully injected, false otherwise
*/
public boolean injectViaAdbKeyboard(String text) {
try {
Runtime runtime = Runtime.getRuntime();
Process checkImeProc = runtime.exec("settings get secure default_input_method");
String selectedIme = null;
try (BufferedReader checkImeInput = new BufferedReader(
new InputStreamReader(checkImeProc.getInputStream()))) {
String line;
while ((line = checkImeInput.readLine()) != null) {
if (selectedIme != null) {
Ln.e("Found multiple IME");
return false;
}
selectedIme = line;
}
}
if (Objects.equals(selectedIme, "com.android.adbkeyboard/.AdbIME")) {
Process broadcastProc = runtime.exec(
"am broadcast -a ADB_INPUT_TEXT --es msg " + text);
return broadcastProc.waitFor() == 0;
} else {
Ln.i("ADB Keyboard needs to be installed and selected as default input to send text through it");
}
return false;
} catch (Throwable throwable) {
Ln.e("Encountered error while trying ti send char through IME", throwable);
return false;
}
}

public static boolean pressReleaseKeycode(int keyCode, int displayId, int injectMode) {
return injectKeyEvent(KeyEvent.ACTION_DOWN, keyCode, 0, 0, displayId, injectMode)
&& injectKeyEvent(KeyEvent.ACTION_UP, keyCode, 0, 0, displayId, injectMode);
Expand Down

0 comments on commit 63b6044

Please sign in to comment.