Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
android:theme="@style/Theme.EzDisplay">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden|density"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|density"
android:exported="true"
android:screenOrientation="sensorLandscape">
<intent-filter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import android.graphics.Color
import android.graphics.Rect
import android.graphics.Typeface
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.Handler
Expand All @@ -16,6 +17,7 @@ import android.util.TypedValue
import android.view.Choreographer
import android.view.Gravity
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.PointerIcon
import android.view.SurfaceHolder
Expand Down Expand Up @@ -85,6 +87,8 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
private var telemetryOn = false
private var lastInputNote = ""
private var keysHintShown = false
private var hostLacksKeys = false // the host reported input_caps without the KEYS bit
private val keysDown = LinkedHashSet<Int>() // hardware key codes currently down on the host
private var airHintShown = false
private var barrelDown = false
private var barrelPressAt = 0L
Expand Down Expand Up @@ -215,6 +219,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall

override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) releaseAllKeys()
if (hasFocus) {
hideSystemBars()
if (Build.VERSION.SDK_INT >= 31) root.requestUnbufferedDispatch(InputDevice.SOURCE_CLASS_POINTER)
Expand All @@ -228,6 +233,19 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
}
}

override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
pushKeyboardState(newConfig)
}

/** Tells the native side (and through it the host) whether a hardware keyboard is attached. */
private fun pushKeyboardState(config: Configuration = resources.configuration) {
NativeBridge.setKeyboardAttached(
config.keyboard == Configuration.KEYBOARD_QWERTY &&
config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO,
)
}

override fun onResume() {
super.onResume()
applyInputConfig()
Expand All @@ -246,6 +264,11 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
scheduleConnect(0)
}

override fun onPause() {
releaseAllKeys()
super.onPause()
}

override fun onStop() {
started = false
handler.removeCallbacks(connectRunnable)
Expand Down Expand Up @@ -283,6 +306,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
if (!started || sessionActive) return
if (!surfaceReady) return // surfaceCreated reschedules
val caps = capsJson ?: Capabilities.toJson(this, chosenMode).also { capsJson = it }
pushKeyboardState()
val err = NativeBridge.start(surfaceView.holder.surface, HOST, PORT, caps)
if (err != null) {
Log.w(TAG, "start failed: $err")
Expand All @@ -296,6 +320,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
wasStreaming = false
lastInputNote = ""
keysHintShown = false
hostLacksKeys = false
airHintShown = false
streamW = 0
streamH = 0
Expand All @@ -307,6 +332,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
}

private fun stopSession() {
releaseAllKeys()
if (sessionActive) {
NativeBridge.stop()
sessionActive = false
Expand Down Expand Up @@ -490,6 +516,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
telemetryOn = (flags and 1) != 0
telemetryView.visibility = if (telemetryOn) View.VISIBLE else View.GONE
if (telemetryOn) showTelemetry(j)
hostLacksKeys = !j.isNull("input_caps") && (j.optInt("input_caps") and 8) == 0
val note = if (j.isNull("input_note")) "" else j.optString("input_note")
if (note != lastInputNote) {
lastInputNote = note
Expand Down Expand Up @@ -575,6 +602,50 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
return super.dispatchGenericMotionEvent(ev)
}

override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (inputActive() && isHardwareKey(event)) {
val code = event.keyCode
val nanos = event.eventTime * 1_000_000L
when (event.action) {
// repeatCount > 0 is an autorepeat: the host treats a press of a key already down as one.
KeyEvent.ACTION_DOWN -> if (NativeBridge.keyEvent(code, true, nanos)) {
keysDown.add(code)
if (hostLacksKeys && !keysHintShown) {
keysHintShown = true
showTransient(getString(R.string.status_keys_unsupported), NOTE_SHOW_MS)
}
return true
}
KeyEvent.ACTION_UP -> if (keysDown.remove(code)) {
NativeBridge.keyEvent(code, false, nanos)
return true
}
}
}
return super.dispatchKeyEvent(event)
}

/** A key from a physical keyboard that Android does not need for itself. */
private fun isHardwareKey(event: KeyEvent): Boolean {
if (event.source and InputDevice.SOURCE_KEYBOARD != InputDevice.SOURCE_KEYBOARD) return false
val device = event.device ?: return false
if (device.isVirtual || device.keyboardType != InputDevice.KEYBOARD_TYPE_ALPHABETIC) return false
return when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE,
KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_APP_SWITCH,
KeyEvent.KEYCODE_BRIGHTNESS_UP, KeyEvent.KEYCODE_BRIGHTNESS_DOWN -> false
else -> true // media keys have no HID usage, so they fall through to Android
}
}

/** Releases every forwarded key so none stays stuck on the PC. */
private fun releaseAllKeys() {
if (keysDown.isEmpty()) return
val nanos = SystemClock.uptimeMillis() * 1_000_000L
keysDown.toList().asReversed().forEach { NativeBridge.keyEvent(it, false, nanos) }
keysDown.clear()
}

/** Packs [ev] (with its history) for [NativeBridge.inputEvent]; buffers are reused. */
private fun forward(ev: MotionEvent) {
val n = ev.pointerCount
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ object NativeBridge {
*/
@JvmStatic external fun inputEvent(ints: IntArray, floats: FloatArray, timesNs: LongArray)

/**
* Forwards one hardware key transition. [timeNs] is on the `SystemClock.uptimeMillis` base.
* A press of a key already down is an autorepeat. Returns false when the key code has no HID
* usage (nothing was sent).
*/
@JvmStatic external fun keyEvent(keyCode: Int, pressed: Boolean, timeNs: Long): Boolean

/**
* Reports whether a hardware keyboard is attached. Kept across sessions: a session started
* later tells the host about the last value.
*/
@JvmStatic external fun setKeyboardAttached(attached: Boolean)

/** Fires the engine timers that are due; call once per frame. */
@JvmStatic external fun inputTick()

Expand Down
55 changes: 52 additions & 3 deletions crates/ezd-android/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
use crate::caps::parse_caps;
use crate::decoder::SendWindow;
use crate::input::{mono_to_now_us, unpack_motion};
use crate::keys::keycode_to_hid;
use crate::session::Session;
use ezd_client_core::now_us;
use ezd_input::{InputConfig, InputEngine, ViewTransform};
use ezd_proto::Message;
use ezd_proto::{Key, Message};
use jni::EnvUnowned;
use jni::errors::ThrowRuntimeExAndDefault;
use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JLongArray, JObject, JString};
Expand All @@ -17,7 +18,7 @@ use ndk::native_window::NativeWindow;
use std::cell::RefCell;
use std::sync::Mutex;
use std::sync::Once;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

static SESSION: Mutex<Option<Session>> = Mutex::new(None);

Expand All @@ -34,6 +35,8 @@ static INPUT: Mutex<InputState> = Mutex::new(InputState {
config: None,
view: (1.0, 1.0),
});
/// Last hardware keyboard state from Kotlin; a new session starts with it.
static KEYBOARD_ATTACHED: AtomicBool = AtomicBool::new(false);
static LAST_INPUT_ERR_S: AtomicU64 = AtomicU64::new(0);

#[derive(Default)]
Expand Down Expand Up @@ -145,7 +148,9 @@ pub extern "system" fn start<'local>(
old.stop();
}
log::info!("start {host}:{port} surface={}", window.is_some());
*guard = Some(Session::start(window, host, port, caps));
let s = Session::start(window, host, port, caps);
s.set_keyboard_attached(KEYBOARD_ATTACHED.load(Ordering::Relaxed));
*guard = Some(s);
Ok(JString::null())
})
.resolve::<ThrowRuntimeExAndDefault>()
Expand Down Expand Up @@ -324,6 +329,50 @@ pub extern "system" fn input_event<'local>(
.resolve::<ThrowRuntimeExAndDefault>()
}

/// `external fun keyEvent(keyCode: Int, pressed: Boolean, timeNs: Long): Boolean`: one hardware
/// key transition (`timeNs` is uptime-based). Returns whether the key code maps to a HID usage
/// and was sent (a press of a key already down is an autorepeat).
#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")]
pub extern "system" fn key_event<'local>(
mut env: EnvUnowned<'local>,
_class: JClass<'local>,
key_code: jint,
pressed: jni::sys::jboolean,
time_ns: jni::sys::jlong,
) -> jni::sys::jboolean {
env.with_env(|_env| -> jni::errors::Result<jni::sys::jboolean> {
let Some(usage) = keycode_to_hid(key_code) else {
return Ok(false);
};
let mut out = vec![Message::Key(Key {
t_us: mono_to_now_us(time_ns, mono_ns(), now_us()),
usage,
pressed,
})];
send_all(&mut out);
Ok(true)
})
.resolve::<ThrowRuntimeExAndDefault>()
}

/// `external fun setKeyboardAttached(attached: Boolean)`: whether a hardware keyboard is attached.
/// Stored also while there is no session, so the next `start` reports it to the host.
#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")]
pub extern "system" fn set_keyboard_attached<'local>(
mut env: EnvUnowned<'local>,
_class: JClass<'local>,
attached: jni::sys::jboolean,
) {
env.with_env(|_env| -> jni::errors::Result<()> {
KEYBOARD_ATTACHED.store(attached, Ordering::Relaxed);
if let Some(s) = session().as_ref() {
s.set_keyboard_attached(attached);
}
Ok(())
})
.resolve::<ThrowRuntimeExAndDefault>()
}

/// `external fun inputTick()`: fires due gesture/pen timers.
#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")]
pub extern "system" fn input_tick<'local>(mut env: EnvUnowned<'local>, _class: JClass<'local>) {
Expand Down
Loading
Loading