package vip.ltpp.euv.showcase;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Insets;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.PowerManager;
import android.os.Process;
import android.text.InputType;
import android.util.Log;
import android.view.Choreographer;
import android.view.Display;
import android.view.DisplayCutout;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public final class EuvActivity extends Activity {
private static final int LAUNCH_BG_LIGHT = 0xFFFAFAFA;
private static final int LAUNCH_BG_DARK = 0xFF09090B;
private static final long LAUNCH_HOLD_TIMEOUT_MS = 1200L;
private FrameLayout rootContainer;
private View launchCoverView;
private EuvCanvasView canvasView;
private WebView embeddedWebView;
private String activeWebUrl = null;
private boolean webSheetOpen = false;
private long sessionGen = 0L;
private volatile boolean activityDestroyed = false;
private Object backInvokedCallback = null;
private float targetRefreshHz = 60.0f;
private int appliedDisplayModeId = 0;
private boolean immersiveFullscreen = false;
private volatile boolean firstFramePresented = false;
private ClipboardManager clipboardManager;
private DisplayManager displayManager;
private SensorManager sensorManager;
private boolean motionSensorsRegistered = false;
private boolean usingGravitySensor = false;
private final float[] rawGravityDev = new float[] {0.0f, 9.80665f, 0.0f};
private final float[] rawLinearDev = new float[] {0.0f, 0.0f, 0.0f};
private final float[] rawGyroDev = new float[] {0.0f, 0.0f, 0.0f};
private final SensorEventListener motionSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (activityDestroyed || isDestroyed() || canvasView == null || event == null || event.values == null || event.values.length < 3) {
return;
}
int type = event.sensor.getType();
if (type == Sensor.TYPE_GRAVITY) {
rawGravityDev[0] = event.values[0];
rawGravityDev[1] = event.values[1];
rawGravityDev[2] = event.values[2];
} else if (type == Sensor.TYPE_ACCELEROMETER && !usingGravitySensor) {
float a = 0.22f;
rawGravityDev[0] = rawGravityDev[0] * (1.0f - a) + event.values[0] * a;
rawGravityDev[1] = rawGravityDev[1] * (1.0f - a) + event.values[1] * a;
rawGravityDev[2] = rawGravityDev[2] * (1.0f - a) + event.values[2] * a;
rawLinearDev[0] = event.values[0] - rawGravityDev[0];
rawLinearDev[1] = event.values[1] - rawGravityDev[1];
rawLinearDev[2] = event.values[2] - rawGravityDev[2];
} else if (type == Sensor.TYPE_LINEAR_ACCELERATION) {
rawLinearDev[0] = event.values[0];
rawLinearDev[1] = event.values[1];
rawLinearDev[2] = event.values[2];
} else if (type == Sensor.TYPE_GYROSCOPE) {
rawGyroDev[0] = event.values[0];
rawGyroDev[1] = event.values[1];
rawGyroDev[2] = event.values[2];
} else {
return;
}
int rot = Surface.ROTATION_0;
Display d = resolveActiveDisplay();
if (d != null) {
rot = d.getRotation();
}
float rGx = rawGravityDev[0], rGy = rawGravityDev[1], rGz = rawGravityDev[2];
float rLx = rawLinearDev[0], rLy = rawLinearDev[1], rLz = rawLinearDev[2];
float rWx = rawGyroDev[0], rWy = rawGyroDev[1], rWz = rawGyroDev[2];
float sGx = rGx, sGy = rGy;
float sLx = rLx, sLy = rLy;
float sWx = rWx, sWy = rWy;
if (rot == Surface.ROTATION_90) {
sGx = -rGy; sGy = rGx;
sLx = -rLy; sLy = rLx;
sWx = -rWy; sWy = rWx;
} else if (rot == Surface.ROTATION_180) {
sGx = -rGx; sGy = -rGy;
sLx = -rLx; sLy = -rLy;
sWx = -rWx; sWy = -rWy;
} else if (rot == Surface.ROTATION_270) {
sGx = rGy; sGy = -rGx;
sLx = rLy; sLy = -rLx;
sWx = rWy; sWy = -rWx;
}
float gx = -sGx;
float gy = sGy;
float gz = -rGz;
float lx = sLx;
float ly = -sLy;
float lz = rLz;
float roll = (float) Math.atan2(gx, gy);
float pitch = (float) Math.atan2(-gz, Math.hypot(gx, gy));
canvasView.dispatchDeviceMotion(gx, gy, gz, lx, ly, lz, sWx, sWy, rWz, pitch, roll, 0.0f, event.timestamp);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
};
private void registerMotionSensors() {
if (motionSensorsRegistered) return;
try {
if (sensorManager == null) {
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
if (sensorManager == null) return;
Sensor gravity = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
if (gravity != null) {
usingGravitySensor = true;
sensorManager.registerListener(motionSensorListener, gravity, SensorManager.SENSOR_DELAY_GAME);
} else {
usingGravitySensor = false;
Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accel != null) {
sensorManager.registerListener(motionSensorListener, accel, SensorManager.SENSOR_DELAY_GAME);
}
}
Sensor linear = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
if (linear != null) {
sensorManager.registerListener(motionSensorListener, linear, SensorManager.SENSOR_DELAY_GAME);
}
Sensor gyro = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (gyro != null) {
sensorManager.registerListener(motionSensorListener, gyro, SensorManager.SENSOR_DELAY_GAME);
}
motionSensorsRegistered = true;
} catch (Throwable ignored) {
}
}
private void unregisterMotionSensors() {
if (!motionSensorsRegistered) return;
motionSensorsRegistered = false;
try {
if (sensorManager != null) {
sensorManager.unregisterListener(motionSensorListener);
}
} catch (Throwable ignored) {
}
}
private final DisplayManager.DisplayListener displayListener = new DisplayManager.DisplayListener() {
@Override
public void onDisplayAdded(int displayId) {}
@Override
public void onDisplayRemoved(int displayId) {}
@Override
public void onDisplayChanged(int displayId) {
if (activityDestroyed || isDestroyed()) return;
selectHighestRefreshMode(getWindow());
if (canvasView != null) {
canvasView.updateTargetRefreshRate(targetRefreshHz);
canvasView.requestSafeAreaRefresh();
}
}
};
private final ClipboardManager.OnPrimaryClipChangedListener clipListener = () -> {
if (activityDestroyed || isDestroyed()) return;
if (canvasView != null) {
canvasView.dispatchClipboardChanged();
}
};
private Display resolveActiveDisplay() {
try {
Display d = getDisplay();
if (d != null) return d;
} catch (Throwable ignored) {
}
try {
DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
if (dm != null) {
Display d = dm.getDisplay(Display.DEFAULT_DISPLAY);
if (d != null) return d;
}
} catch (Throwable ignored) {
}
try {
WindowManager wm = getWindowManager();
if (wm != null) {
@SuppressWarnings("deprecation")
Display d = wm.getDefaultDisplay();
return d;
}
} catch (Throwable ignored) {
}
return null;
}
private void syncSystemConfig(Configuration cfg) {
if (canvasView == null || cfg == null) return;
boolean isDark = (cfg.uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
canvasView.dispatchThemeChanged(isDark);
Window win = getWindow();
if (win != null) {
WindowInsetsController ctrl = win.getInsetsController();
if (ctrl != null) {
int appearance = isDark
? 0
: (WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
| WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);
ctrl.setSystemBarsAppearance(
appearance,
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
| WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
);
}
}
String localeTag = Locale.getDefault().toLanguageTag();
if (localeTag != null && !localeTag.isEmpty()) {
canvasView.dispatchLocaleChanged(localeTag);
}
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm != null) {
canvasView.dispatchLowPowerChanged(pm.isPowerSaveMode());
}
}
private void applyHotUpdateIntentExtras(Intent intent) {
if (intent == null) return;
try {
android.content.SharedPreferences prefs =
getSharedPreferences("euv_hot_update_prefs", Context.MODE_PRIVATE);
String updateUrl = intent.getStringExtra("euv_update_url");
String proxyUrl = intent.getStringExtra("euv_proxy_url");
android.content.SharedPreferences.Editor ed = prefs.edit();
boolean changed = false;
if (updateUrl != null && !updateUrl.trim().isEmpty()) {
ed.putString("euv_update_url", updateUrl.trim());
android.system.Os.setenv("EUV_UPDATE_URL", updateUrl.trim(), true);
changed = true;
} else {
String savedUpdate = prefs.getString("euv_update_url", "");
if (savedUpdate != null && !savedUpdate.isEmpty()) {
android.system.Os.setenv("EUV_UPDATE_URL", savedUpdate, true);
}
}
if (proxyUrl != null) {
String trimmedProxy = proxyUrl.trim();
ed.putString("euv_proxy_url", trimmedProxy);
if (!trimmedProxy.isEmpty()) {
android.system.Os.setenv("EUV_PROXY_URL", trimmedProxy, true);
} else {
android.system.Os.unsetenv("EUV_PROXY_URL");
}
changed = true;
} else {
String savedProxy = prefs.getString("euv_proxy_url", "");
if (savedProxy != null && !savedProxy.isEmpty()) {
android.system.Os.setenv("EUV_PROXY_URL", savedProxy, true);
}
}
if (changed) {
ed.apply();
}
} catch (Throwable ignored) {}
}
private void forwardIntentDeepLink(Intent intent) {
if (intent == null || canvasView == null) return;
applyHotUpdateIntentExtras(intent);
String uri = intent.getDataString();
if (uri != null && !uri.isEmpty()) {
canvasView.dispatchDeepLink(uri);
} else {
String updateUrl = intent.getStringExtra("euv_update_url");
if (updateUrl != null && !updateUrl.trim().isEmpty()) {
canvasView.dispatchDeepLink("euv://dynamic");
}
}
}
private void selectHighestRefreshMode(Window win) {
try {
Display display = resolveActiveDisplay();
if (display == null) return;
Display.Mode current = display.getMode();
Display.Mode best = current;
float bestHz = current.getRefreshRate();
for (Display.Mode m : display.getSupportedModes()) {
if (m.getPhysicalWidth() == current.getPhysicalWidth()
&& m.getPhysicalHeight() == current.getPhysicalHeight()) {
float modeMaxHz = m.getRefreshRate();
if (Build.VERSION.SDK_INT >= 31) {
float[] alts = m.getAlternativeRefreshRates();
if (alts != null) {
for (float altHz : alts) {
if (altHz > modeMaxHz) {
modeMaxHz = altHz;
}
}
}
}
if (modeMaxHz > bestHz) {
best = m;
bestHz = modeMaxHz;
}
}
}
targetRefreshHz = Math.max(60.0f, bestHz);
int bestModeId = best.getModeId();
if (appliedDisplayModeId != bestModeId) {
WindowManager.LayoutParams lp = win.getAttributes();
lp.preferredDisplayModeId = bestModeId;
lp.preferredRefreshRate = targetRefreshHz;
win.setAttributes(lp);
appliedDisplayModeId = bestModeId;
}
if (Build.VERSION.SDK_INT >= 34) {
try {
Method boost = Window.class.getMethod("setFrameRateBoostOnTouchEnabled", boolean.class);
boost.invoke(win, Boolean.TRUE);
} catch (Throwable ignored) {
}
}
if (canvasView != null) {
canvasView.updateTargetRefreshRate(targetRefreshHz);
}
} catch (Throwable t) {
Log.w("euv-fps", "refresh mode hint skipped: " + t.getMessage());
}
}
public void setImmersiveFullscreen(boolean enabled) {
if (immersiveFullscreen == enabled && canvasView != null) {
canvasView.setImmersiveFullscreen(enabled);
return;
}
immersiveFullscreen = enabled;
Window win = getWindow();
if (win != null) {
if (Build.VERSION.SDK_INT >= 29) {
win.setStatusBarContrastEnforced(false);
win.setNavigationBarContrastEnforced(false);
}
WindowInsetsController ctrl = win.getInsetsController();
if (ctrl != null) {
int barTypes = WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars();
if (enabled) {
ctrl.hide(barTypes);
ctrl.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
} else {
ctrl.show(barTypes);
}
}
}
if (canvasView != null) {
canvasView.setImmersiveFullscreen(enabled);
canvasView.requestSafeAreaRefresh();
}
}
private void attachDecorInsetsListener(Window win) {
if (win == null) return;
View decor = win.getDecorView();
if (decor == null) return;
decor.setOnApplyWindowInsetsListener((v, insets) -> {
if (canvasView != null) {
canvasView.applyWindowInsets(insets);
}
return v.onApplyWindowInsets(insets);
});
}
private void dismissLaunchCoverOnFirstFrame() {
if (firstFramePresented) return;
firstFramePresented = true;
if (activityDestroyed || isDestroyed()) return;
runOnUiThread(() -> {
if (activityDestroyed || isDestroyed()) return;
if (launchCoverView != null) {
ViewGroup parent = (ViewGroup) launchCoverView.getParent();
if (parent != null) {
parent.removeView(launchCoverView);
}
launchCoverView = null;
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applyHotUpdateIntentExtras(getIntent());
activityDestroyed = false;
sessionGen = EuvNativeBridge.registerHostActivity(this);
Window win = getWindow();
win.setDecorFitsSystemWindows(false);
win.setStatusBarColor(Color.TRANSPARENT);
win.setNavigationBarColor(Color.TRANSPARENT);
if (Build.VERSION.SDK_INT >= 29) {
win.setStatusBarContrastEnforced(false);
win.setNavigationBarContrastEnforced(false);
}
Configuration cfg = getResources().getConfiguration();
boolean isNight = (cfg.uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
int launchBg = isNight ? LAUNCH_BG_DARK : LAUNCH_BG_LIGHT;
WindowManager.LayoutParams lp = win.getAttributes();
if (Build.VERSION.SDK_INT >= 30) {
lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
} else {
lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
}
win.setAttributes(lp);
selectHighestRefreshMode(win);
rootContainer = new FrameLayout(this);
rootContainer.setBackgroundColor(launchBg);
canvasView = new EuvCanvasView(this, win, targetRefreshHz, this::dismissLaunchCoverOnFirstFrame);
rootContainer.addView(
canvasView,
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
);
launchCoverView = new View(this);
launchCoverView.setBackgroundColor(launchBg);
launchCoverView.setClickable(false);
launchCoverView.setFocusable(false);
rootContainer.addView(
launchCoverView,
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
);
setContentView(rootContainer);
attachDecorInsetsListener(win);
displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
if (displayManager != null) {
displayManager.registerDisplayListener(displayListener, new Handler(getMainLooper()));
}
clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboardManager != null) {
clipboardManager.addPrimaryClipChangedListener(clipListener);
}
forwardIntentDeepLink(getIntent());
if (Build.VERSION.SDK_INT >= 33) {
android.window.OnBackInvokedCallback cb = () -> {
if (!activityDestroyed && canvasView != null) {
canvasView.dispatchSystemBack();
}
};
backInvokedCallback = cb;
getOnBackInvokedDispatcher().registerOnBackInvokedCallback(
android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT,
cb
);
}
View decor = win.getDecorView();
decor.post(() -> {
if (activityDestroyed || isDestroyed()) return;
selectHighestRefreshMode(win);
WindowInsetsController ctrl = win.getInsetsController();
if (ctrl != null) {
int appearance = isNight
? 0
: (WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
| WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);
ctrl.setSystemBarsAppearance(
appearance,
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
| WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
);
}
if (canvasView != null) {
canvasView.requestSafeAreaRefresh();
}
});
decor.postDelayed(() -> {
if (!activityDestroyed && !isDestroyed() && canvasView != null) {
canvasView.requestSafeAreaRefresh();
}
}, 150L);
decor.postDelayed(() -> {
if (!activityDestroyed && !isDestroyed() && canvasView != null) {
canvasView.requestSafeAreaRefresh();
}
}, 400L);
decor.postDelayed(this::dismissLaunchCoverOnFirstFrame, LAUNCH_HOLD_TIMEOUT_MS);
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
selectHighestRefreshMode(getWindow());
if (canvasView != null) {
canvasView.requestSafeAreaRefresh();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
forwardIntentDeepLink(intent);
}
@Override
protected void onStart() {
super.onStart();
if (canvasView != null) {
canvasView.dispatchSystemLifecycle(1);
}
}
@Override
protected void onStop() {
if (canvasView != null) {
canvasView.cancelAllTouches();
canvasView.dispatchSystemLifecycle(5);
}
super.onStop();
}
public void openEmbeddedWebView(String url) {
if (activityDestroyed || isDestroyed() || rootContainer == null || url == null || url.isEmpty()) {
return;
}
if (embeddedWebView == null) {
WebView wv = new WebView(this);
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
ws.setDomStorageEnabled(true);
ws.setLoadWithOverviewMode(true);
ws.setUseWideViewPort(true);
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
wv.setBackgroundColor(Color.TRANSPARENT);
wv.setVisibility(View.GONE);
wv.setAlpha(0.0f);
wv.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request == null || request.getUrl() == null) return false;
String scheme = request.getUrl().getScheme();
return !("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme));
}
@Override
public void onPageCommitVisible(WebView view, String committedUrl) {
view.setBackgroundColor(Color.WHITE);
}
});
rootContainer.addView(wv, new FrameLayout.LayoutParams(1, 1));
embeddedWebView = wv;
}
webSheetOpen = true;
embeddedWebView.bringToFront();
if (!url.equals(activeWebUrl)) {
activeWebUrl = url;
embeddedWebView.setBackgroundColor(Color.TRANSPARENT);
embeddedWebView.loadUrl(url);
}
}
public void updateEmbeddedWebViewFrame(float xDp, float yDp, float wDp, float hDp, float alpha) {
if (activityDestroyed || isDestroyed() || !webSheetOpen || embeddedWebView == null) {
return;
}
if (wDp < 1.0f || hDp < 1.0f || alpha <= 0.005f) {
embeddedWebView.setVisibility(View.GONE);
embeddedWebView.setAlpha(0.0f);
return;
}
float density = getResources().getDisplayMetrics().density;
int wPx = Math.max(1, Math.round(wDp * density));
int hPx = Math.max(1, Math.round(hDp * density));
ViewGroup.LayoutParams lp = embeddedWebView.getLayoutParams();
if (lp == null || lp.width != wPx || lp.height != hPx) {
embeddedWebView.setLayoutParams(new FrameLayout.LayoutParams(wPx, hPx));
}
embeddedWebView.setTranslationX(xDp * density);
embeddedWebView.setTranslationY(yDp * density);
embeddedWebView.setAlpha(alpha);
embeddedWebView.setVisibility(View.VISIBLE);
}
public void reloadEmbeddedWebView(String fallbackUrl) {
if (activityDestroyed || isDestroyed() || !webSheetOpen || embeddedWebView == null) {
return;
}
String current = embeddedWebView.getUrl();
if (current != null && !current.isEmpty() && !"about:blank".equalsIgnoreCase(current)) {
embeddedWebView.reload();
} else if (fallbackUrl != null && !fallbackUrl.isEmpty()) {
activeWebUrl = null;
openEmbeddedWebView(fallbackUrl);
}
}
public void closeEmbeddedWebView() {
webSheetOpen = false;
activeWebUrl = null;
if (embeddedWebView != null) {
embeddedWebView.stopLoading();
embeddedWebView.loadUrl("about:blank");
embeddedWebView.setBackgroundColor(Color.TRANSPARENT);
embeddedWebView.setAlpha(0.0f);
embeddedWebView.setVisibility(View.GONE);
}
}
@Override
protected void onDestroy() {
activityDestroyed = true;
if (embeddedWebView != null) {
try {
embeddedWebView.stopLoading();
ViewGroup parent = (ViewGroup) embeddedWebView.getParent();
if (parent != null) {
parent.removeView(embeddedWebView);
}
embeddedWebView.destroy();
} catch (Throwable ignored) {
}
embeddedWebView = null;
}
if (Build.VERSION.SDK_INT >= 33 && backInvokedCallback instanceof android.window.OnBackInvokedCallback) {
try {
getOnBackInvokedDispatcher().unregisterOnBackInvokedCallback(
(android.window.OnBackInvokedCallback) backInvokedCallback
);
} catch (Throwable ignored) {
}
backInvokedCallback = null;
}
if (displayManager != null) {
displayManager.unregisterDisplayListener(displayListener);
displayManager = null;
}
if (clipboardManager != null) {
clipboardManager.removePrimaryClipChangedListener(clipListener);
clipboardManager = null;
}
EuvNativeBridge.clearHostActivity(this, sessionGen);
if (canvasView != null) {
canvasView.shutdown();
canvasView = null;
}
super.onDestroy();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (canvasView == null) return;
if (level >= TRIM_MEMORY_RUNNING_CRITICAL || level >= TRIM_MEMORY_COMPLETE) {
canvasView.dispatchMemoryWarning(2);
} else if (level >= TRIM_MEMORY_RUNNING_MODERATE) {
canvasView.dispatchMemoryWarning(1);
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (canvasView != null) {
canvasView.dispatchMemoryWarning(2);
}
}
public void setSoftKeyboardVisible(boolean show) {
if (canvasView != null) {
canvasView.setSoftKeyboardVisible(show);
}
}
@Override
@SuppressWarnings("deprecation")
public void onBackPressed() {
if (canvasView != null && canvasView.dispatchSystemBack()) {
return;
}
super.onBackPressed();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
selectHighestRefreshMode(getWindow());
if (canvasView != null) {
canvasView.syncDisplayScaleAndResize();
canvasView.requestSafeAreaRefresh();
syncSystemConfig(newConfig);
}
}
@Override
protected void onResume() {
super.onResume();
EuvNativeBridge.activateHostActivity(this, sessionGen);
selectHighestRefreshMode(getWindow());
registerMotionSensors();
if (canvasView != null) {
canvasView.onActivityResumed();
syncSystemConfig(getResources().getConfiguration());
canvasView.requestSafeAreaRefresh();
getWindow().getDecorView().post(() -> {
if (!activityDestroyed && !isDestroyed() && canvasView != null) {
canvasView.requestSafeAreaRefresh();
}
});
}
}
@Override
protected void onPause() {
super.onPause();
unregisterMotionSensors();
if (canvasView != null) {
canvasView.onActivityPaused();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (canvasView != null) {
if (!hasFocus) {
canvasView.cancelAllTouches();
} else {
selectHighestRefreshMode(getWindow());
canvasView.requestSafeAreaRefresh();
canvasView.requestFocus();
}
canvasView.dispatchFocusChanged(hasFocus);
}
}
private static final class EuvCanvasView extends SurfaceView implements SurfaceHolder.Callback {
private final Window hostWindow;
private final Runnable onFirstFramePresented;
private final HandlerThread renderThread;
private final Handler renderHandler;
private final Object moveLock = new Object();
private final Object safeLock = new Object();
private static final int TOUCH_BATCH_CAP = 32;
private static final int TOUCH_RECORD_BYTES = 20;
private boolean hasPendingMove = false;
private int pendingMoveCount = 0;
private final ByteBuffer touchRingStaging = ByteBuffer.allocateDirect(TOUCH_BATCH_CAP * TOUCH_RECORD_BYTES).order(ByteOrder.nativeOrder());
private final ByteBuffer touchRingFlush = ByteBuffer.allocateDirect(TOUCH_BATCH_CAP * TOUCH_RECORD_BYTES).order(ByteOrder.nativeOrder());
private long pendingMoveMask = 0L;
private long handle = 0;
private volatile boolean destroyed = false;
private volatile boolean activityResumed = false;
private long activeLoopGen = 0L;
private volatile float displayDensity = 2.0f;
private volatile float renderScale = 2.0f;
private volatile float targetFps = 60.0f;
private volatile boolean immersiveFullscreen = false;
private boolean firstPresentNotified = false;
private float cachedSafeTop = 28.0f;
private float cachedSafeRight = 0.0f;
private float cachedSafeBottom = 24.0f;
private float cachedSafeLeft = 0.0f;
private boolean surfaceReady = false;
private int surfaceW = 0;
private int surfaceH = 0;
private long lastNanos = 0;
private boolean running = false;
private boolean choreographerArmed = false;
private boolean pendingForcePresent = false;
private long submitRetries = 0;
private boolean imeWasVisible = false;
private long renderedFrames = 0;
private double accumTotalMs = 0.0;
private double accumStepMs = 0.0;
private double accumBlitMs = 0.0;
private double maxRenderMs = 0.0;
private long droppedFrames = 0;
private final Choreographer.FrameCallback renderFrameCallback = new Choreographer.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
choreographerArmed = false;
if (!running || destroyed) return;
long gen = activeLoopGen;
float hz = targetFps > 24.0f ? targetFps : 60.0f;
float rawDt = (lastNanos > 0)
? ((frameTimeNanos - lastNanos) / 1_000_000_000.0f)
: (1.0f / hz);
float dt = Math.max(1.0f / 1000.0f, Math.min(0.05f, rawDt));
lastNanos = frameTimeNanos;
flushPendingMovesOnRenderThread();
if (!running || destroyed || activeLoopGen != gen) return;
boolean forceNow = pendingForcePresent;
pendingForcePresent = false;
int presented = stepAndPresentOnRenderThread(dt, forceNow, frameTimeNanos);
if (!running || destroyed || activeLoopGen != gen) return;
boolean moreMoves;
synchronized (moveLock) {
moreMoves = hasPendingMove;
}
boolean needsNext = (presented != 0)
|| pendingForcePresent
|| moreMoves
|| (handle != 0 && EuvNativeBridge.nativeNeedsFrame(handle) != 0);
if (needsNext) {
choreographerArmed = true;
Choreographer.getInstance().postFrameCallback(this);
} else {
lastNanos = 0;
}
}
};
private void scheduleNextFrameOnRenderThread(boolean forcePresent) {
if (forcePresent) {
pendingForcePresent = true;
}
if (activityResumed && surfaceReady && !destroyed) {
if (!running) {
startLoopOnRenderThread();
} else if (!choreographerArmed) {
choreographerArmed = true;
lastNanos = 0;
Choreographer.getInstance().postFrameCallback(renderFrameCallback);
}
}
}
private float computeRoundWatchSafeInsetDp(Context ctx) {
if (ctx == null || immersiveFullscreen) return 0.0f;
Configuration cfg = ctx.getResources().getConfiguration();
if (!cfg.isScreenRound()) return 0.0f;
int wPx = ctx.getResources().getDisplayMetrics().widthPixels;
int hPx = ctx.getResources().getDisplayMetrics().heightPixels;
int diameterPx = Math.min(wPx, hPx);
if (diameterPx <= 0) return 0.0f;
float insetPx = diameterPx * (1.0f - 0.70710678f) * 0.5f;
return insetPx / Math.max(1.0f, displayDensity);
}
EuvCanvasView(Context ctx, Window window, float preferredHz, Runnable firstFrameCallback) {
super(ctx);
hostWindow = window;
onFirstFramePresented = firstFrameCallback;
targetFps = Math.max(60.0f, preferredHz);
refreshDensity(ctx);
seedInitialSafeArea(ctx);
renderThread = new HandlerThread("euv-render", Process.THREAD_PRIORITY_DISPLAY);
renderThread.start();
renderHandler = new Handler(renderThread.getLooper());
renderHandler.post(EuvNativeBridge::ensureNativeLibraryLoaded);
getHolder().setFormat(PixelFormat.RGBA_8888);
getHolder().addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
applyViewRequestedFrameRate(targetFps);
setOnApplyWindowInsetsListener((v, insets) -> {
applyWindowInsets(insets);
return insets;
});
}
private void applyViewRequestedFrameRate(float hz) {
if (Build.VERSION.SDK_INT >= 35) {
try {
Method setReq = View.class.getMethod("setRequestedFrameRate", float.class);
setReq.invoke(this, hz);
} catch (Throwable ignored) {
}
}
}
private int queryFallbackStatusBarHeightPx(Context ctx) {
int fallbackPx = 0;
try {
int resId = ctx.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
fallbackPx = Math.max(fallbackPx, ctx.getResources().getDimensionPixelSize(resId));
}
} catch (Throwable ignored) {
}
try {
Display d = ctx.getDisplay();
if (d == null) {
DisplayManager dm = (DisplayManager) ctx.getSystemService(Context.DISPLAY_SERVICE);
if (dm != null) {
d = dm.getDisplay(Display.DEFAULT_DISPLAY);
}
}
if (d != null) {
DisplayCutout cutout = d.getCutout();
fallbackPx = Math.max(fallbackPx, extractCutoutTopPx(cutout, ctx));
}
} catch (Throwable ignored) {
}
return fallbackPx;
}
private int extractCutoutTopPx(DisplayCutout cutout, Context ctx) {
if (cutout == null) return 0;
int topPx = Math.max(0, cutout.getSafeInsetTop());
int screenH = ctx.getResources().getDisplayMetrics().heightPixels;
int maxTopBand = screenH > 0 ? (screenH / 3) : 600;
List<Rect> rects = cutout.getBoundingRects();
if (rects != null) {
for (Rect r : rects) {
if (r != null && r.top <= topPx + 32 && r.bottom > topPx && r.bottom <= maxTopBand) {
topPx = Math.max(topPx, r.bottom);
}
}
}
return topPx;
}
private void seedInitialSafeArea(Context ctx) {
WindowInsets rootInsets = (hostWindow != null && hostWindow.getDecorView() != null)
? hostWindow.getDecorView().getRootWindowInsets()
: null;
if (rootInsets != null) {
applyWindowInsets(rootInsets);
return;
}
float d = displayDensity;
int topPx = queryFallbackStatusBarHeightPx(ctx);
int navPx = 0;
try {
int navId = ctx.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
if (navId > 0) {
navPx = Math.min(ctx.getResources().getDimensionPixelSize(navId), Math.round(32.0f * d));
}
} catch (Throwable ignored) {
}
float roundInset = computeRoundWatchSafeInsetDp(ctx);
float fallbackTop = topPx > 0 ? (topPx / d) : 24.0f;
synchronized (safeLock) {
cachedSafeTop = Math.max(roundInset, fallbackTop);
cachedSafeRight = Math.max(roundInset, 0.0f);
cachedSafeBottom = Math.max(roundInset, Math.max(0.0f, navPx / d));
cachedSafeLeft = Math.max(roundInset, 0.0f);
}
}
void setImmersiveFullscreen(boolean enabled) {
immersiveFullscreen = enabled;
if (enabled) {
synchronized (safeLock) {
cachedSafeTop = 0.0f;
cachedSafeRight = 0.0f;
cachedSafeBottom = 0.0f;
cachedSafeLeft = 0.0f;
}
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeSetSafeArea(handle, 0.0f, 0.0f, 0.0f, 0.0f);
scheduleNextFrameOnRenderThread(true);
}
});
}
}
void requestSafeAreaRefresh() {
if (hostWindow != null && hostWindow.getDecorView() != null) {
View decor = hostWindow.getDecorView();
WindowInsets live = decor.getRootWindowInsets();
if (live != null) {
applyWindowInsets(live);
}
decor.requestApplyInsets();
}
requestApplyInsets();
}
void applyWindowInsets(WindowInsets insets) {
if (insets == null) return;
Context ctx = getContext();
refreshDensity(ctx);
int topTypes = WindowInsets.Type.statusBars()
| WindowInsets.Type.displayCutout();
int edgeTypes = WindowInsets.Type.navigationBars()
| WindowInsets.Type.displayCutout();
Insets visibleTop = insets.getInsets(topTypes);
Insets ignoringTop = insets.getInsetsIgnoringVisibility(topTypes);
Insets visibleEdges = insets.getInsets(edgeTypes);
Insets ignoringEdges = insets.getInsetsIgnoringVisibility(edgeTypes);
Insets ime = insets.getInsets(WindowInsets.Type.ime());
boolean imeVisible = ime.bottom > 0;
boolean imeHiddenNow = imeWasVisible && !imeVisible;
imeWasVisible = imeVisible;
float d = displayDensity;
float top;
float right;
float bottom;
float left;
if (immersiveFullscreen) {
top = 0.0f;
right = 0.0f;
bottom = imeVisible ? (ime.bottom / d) : 0.0f;
left = 0.0f;
} else {
int cutoutTopPx = extractCutoutTopPx(insets.getDisplayCutout(), ctx);
int fallbackTopPx = queryFallbackStatusBarHeightPx(ctx);
int topPx = Math.max(
Math.max(visibleTop.top, ignoringTop.top),
Math.max(cutoutTopPx, fallbackTopPx)
);
int rightPx = Math.max(visibleEdges.right, ignoringEdges.right);
int bottomPx = Math.max(Math.max(visibleEdges.bottom, ignoringEdges.bottom), ime.bottom);
int leftPx = Math.max(visibleEdges.left, ignoringEdges.left);
float roundInset = computeRoundWatchSafeInsetDp(ctx);
top = Math.max(roundInset, topPx / d);
right = Math.max(roundInset, rightPx / d);
bottom = Math.max(roundInset, bottomPx / d);
left = Math.max(roundInset, leftPx / d);
}
float imeHeight = ime.bottom / d;
boolean changed;
synchronized (safeLock) {
changed = Math.abs(top - cachedSafeTop) > 0.25f
|| Math.abs(right - cachedSafeRight) > 0.25f
|| Math.abs(bottom - cachedSafeBottom) > 0.25f
|| Math.abs(left - cachedSafeLeft) > 0.25f;
cachedSafeTop = top;
cachedSafeRight = right;
cachedSafeBottom = bottom;
cachedSafeLeft = left;
}
final boolean shouldRedraw = changed;
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeKeyboardChanged(handle, imeVisible ? 1 : 0, imeHeight);
if (imeHiddenNow) {
EuvNativeBridge.nativeImeDisabled(handle);
}
EuvNativeBridge.nativeSetSafeArea(handle, top, right, bottom, left);
if (shouldRedraw && surfaceReady) {
scheduleNextFrameOnRenderThread(true);
}
}
});
}
private void refreshDensity(Context ctx) {
displayDensity = Math.max(1.0f, ctx.getResources().getDisplayMetrics().density);
renderScale = Math.max(1.0f, Math.min(6.0f, displayDensity));
}
void updateTargetRefreshRate(float hz) {
float clamped = Math.max(60.0f, Math.min(1000.0f, hz));
targetFps = clamped;
applyViewRequestedFrameRate(clamped);
SurfaceHolder holder = getHolder();
if (holder != null && holder.getSurface() != null && holder.getSurface().isValid()) {
applySurfaceFrameRate(holder.getSurface());
}
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeUpdateRefreshRate(handle, clamped);
}
});
}
private void applySurfaceFrameRate(Surface surface) {
if (surface != null && Build.VERSION.SDK_INT >= 31) {
try {
surface.setFrameRate(
targetFps,
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
Surface.CHANGE_FRAME_RATE_ALWAYS
);
} catch (Throwable ignored) {
}
} else if (surface != null && Build.VERSION.SDK_INT >= 30) {
try {
surface.setFrameRate(targetFps, Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE);
} catch (Throwable ignored) {
}
}
}
@Override
public boolean onCheckIsTextEditor() {
return true;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_ACTION_DONE;
return new BaseInputConnection(this, false) {
@Override
public boolean commitText(CharSequence text, int newCursorPosition) {
if (text != null && text.length() > 0) {
dispatchTextInput(text.toString());
}
return true;
}
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
int count = Math.max(1, Math.min(32, beforeLength));
for (int i = 0; i < count; i++) {
dispatchKeyTag(1);
}
return true;
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
if (handleHardwareKeyDown(event.getKeyCode(), event)) {
return true;
}
}
return super.sendKeyEvent(event);
}
};
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (handleHardwareKeyDown(keyCode, event)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
private boolean handleHardwareKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return dispatchSystemBack();
}
if (keyCode == KeyEvent.KEYCODE_DEL) {
dispatchKeyTag(1);
return true;
}
if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) {
dispatchKeyTag(2);
return true;
}
if (keyCode == KeyEvent.KEYCODE_TAB) {
dispatchKeyTag(3);
return true;
}
if (keyCode == KeyEvent.KEYCODE_ESCAPE) {
dispatchKeyTag(4);
return true;
}
if (event != null) {
int uni = event.getUnicodeChar();
if (uni >= 32) {
dispatchTextInput(new String(Character.toChars(uni)));
return true;
}
}
return false;
}
void setSoftKeyboardVisible(boolean show) {
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) return;
if (show) {
requestFocus();
imm.restartInput(this);
boolean shown = imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT);
if (Build.VERSION.SDK_INT >= 30) {
WindowInsetsController ctrl = getWindowInsetsController();
if (ctrl != null) {
ctrl.show(WindowInsets.Type.ime());
}
}
if (!shown) {
postDelayed(() -> {
requestFocus();
imm.restartInput(this);
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT);
if (Build.VERSION.SDK_INT >= 30) {
WindowInsetsController ctrl = getWindowInsetsController();
if (ctrl != null) {
ctrl.show(WindowInsets.Type.ime());
}
}
}, 40L);
}
} else {
if (Build.VERSION.SDK_INT >= 30) {
WindowInsetsController ctrl = getWindowInsetsController();
if (ctrl != null) {
ctrl.hide(WindowInsets.Type.ime());
}
}
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
private void dispatchTextInput(String text) {
byte[] utf8 = text.getBytes(StandardCharsets.UTF_8);
if (utf8.length == 0) return;
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeTextInput(handle, utf8);
scheduleNextFrameOnRenderThread(false);
}
});
}
private void dispatchKeyTag(int keyTag) {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeKeyDown(handle, keyTag);
scheduleNextFrameOnRenderThread(false);
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Surface surface = holder.getSurface();
applySurfaceFrameRate(surface);
int w = getWidth();
int h = getHeight();
if (w > 0 && h > 0 && surface != null && surface.isValid()) {
initializeSurfaceAndPresent(surface, w, h);
} else {
post(this::requestSafeAreaRefresh);
}
}
private void ensureLiveHandleOnRenderThread(int width, int height, float scale) {
if (destroyed) return;
EuvNativeBridge.ensureNativeLibraryLoaded();
final float initTop;
final float initRight;
final float initBottom;
final float initLeft;
synchronized (safeLock) {
initTop = cachedSafeTop;
initRight = cachedSafeRight;
initBottom = cachedSafeBottom;
initLeft = cachedSafeLeft;
}
if (handle != 0 && EuvNativeBridge.nativeIsRunning(handle) == 0) {
long stale = handle;
handle = 0;
EuvNativeBridge.nativeSetSurface(stale, null, 0, 0, scale);
EuvNativeBridge.nativeDestroy(stale);
}
if (handle == 0) {
handle = EuvNativeBridge.nativeCreate(
Math.max(200, width),
Math.max(200, height),
scale,
targetFps,
initTop,
initRight,
initBottom,
initLeft
);
} else {
EuvNativeBridge.nativeUpdateRefreshRate(handle, targetFps);
EuvNativeBridge.nativeSetSafeArea(handle, initTop, initRight, initBottom, initLeft);
}
}
private void initializeSurfaceAndPresent(Surface surface, int width, int height) {
if (destroyed) return;
refreshDensity(getContext());
surfaceW = width;
surfaceH = height;
applySurfaceFrameRate(surface);
float scale = renderScale;
renderHandler.post(() -> {
if (destroyed) return;
ensureLiveHandleOnRenderThread(width, height, scale);
if (handle == 0) return;
EuvNativeBridge.nativeSetSurface(handle, surface, width, height, scale);
surfaceReady = true;
float initDt = 1.0f / Math.max(60.0f, targetFps);
stepAndPresentOnRenderThread(initDt, true);
scheduleNextFrameOnRenderThread(false);
post(this::requestSafeAreaRefresh);
});
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (destroyed || width <= 0 || height <= 0) return;
if (surfaceReady && surfaceW == width && surfaceH == height && handle != 0) {
applySurfaceFrameRate(holder.getSurface());
post(this::requestSafeAreaRefresh);
return;
}
initializeSurfaceAndPresent(holder.getSurface(), width, height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (destroyed) return;
synchronized (moveLock) {
hasPendingMove = false;
pendingMoveCount = 0;
}
CountDownLatch latch = new CountDownLatch(1);
float scale = renderScale;
boolean posted = renderHandler.post(() -> {
surfaceReady = false;
if (handle != 0) {
EuvNativeBridge.nativeTouchCancel(handle, -1);
EuvNativeBridge.nativeSetSurface(handle, null, 0, 0, scale);
}
latch.countDown();
});
if (!posted) return;
try {
latch.await(500L, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
void syncDisplayScaleAndResize() {
refreshDensity(getContext());
int w = surfaceW > 0 ? surfaceW : getWidth();
int h = surfaceH > 0 ? surfaceH : getHeight();
Surface surface = getHolder().getSurface();
float scale = renderScale;
if (w > 0 && h > 0 && surface != null) {
renderHandler.post(() -> {
if (handle != 0 && surfaceReady) {
EuvNativeBridge.nativeSetSurface(handle, surface, w, h, scale);
post(this::requestApplyInsets);
scheduleNextFrameOnRenderThread(true);
}
});
}
}
boolean dispatchSystemBack() {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeSystemBack(handle);
scheduleNextFrameOnRenderThread(true);
}
});
return true;
}
void dispatchAmbientMode(boolean ambient) {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeAmbientModeChanged(handle, ambient ? 1 : 0);
scheduleNextFrameOnRenderThread(true);
}
});
}
void dispatchSystemLifecycle(int tag) {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeSystemLifecycle(handle, tag);
}
});
}
void dispatchSystemLifecycleSync(int tag) {
CountDownLatch latch = new CountDownLatch(1);
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeSystemLifecycle(handle, tag);
}
latch.countDown();
});
try {
latch.await(250L, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
void dispatchFocusChanged(boolean focused) {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeFocusChanged(handle, focused ? 1 : 0);
scheduleNextFrameOnRenderThread(false);
}
});
}
void dispatchThemeChanged(boolean isDark) {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeThemeChanged(handle, isDark ? 1 : 0);
scheduleNextFrameOnRenderThread(true);
}
});
}
void dispatchMemoryWarning(int level) {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeMemoryWarning(handle, level);
scheduleNextFrameOnRenderThread(false);
}
});
}
void dispatchLowPowerChanged(boolean enabled) {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeLowPowerChanged(handle, enabled ? 1 : 0);
scheduleNextFrameOnRenderThread(false);
}
});
}
void dispatchLocaleChanged(String localeTag) {
byte[] utf8 = localeTag.getBytes(StandardCharsets.UTF_8);
if (utf8.length == 0) return;
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeLocaleChanged(handle, utf8);
scheduleNextFrameOnRenderThread(true);
}
});
}
void dispatchDeepLink(String uri) {
byte[] utf8 = uri.getBytes(StandardCharsets.UTF_8);
if (utf8.length == 0) return;
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeDeepLink(handle, utf8);
scheduleNextFrameOnRenderThread(true);
}
});
}
void dispatchClipboardChanged() {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeClipboardChanged(handle);
scheduleNextFrameOnRenderThread(false);
}
});
}
void dispatchDeviceMotion(
float gx,
float gy,
float gz,
float lx,
float ly,
float lz,
float wx,
float wy,
float wz,
float pitch,
float roll,
float yaw,
long timestampNs
) {
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeDeviceMotion(handle, gx, gy, gz, lx, ly, lz, wx, wy, wz, pitch, roll, yaw, timestampNs);
if (EuvNativeBridge.nativeNeedsFrame(handle) != 0) {
scheduleNextFrameOnRenderThread(false);
}
}
});
}
private void startLoopOnRenderThread() {
if (destroyed) return;
activeLoopGen += 1L;
running = true;
choreographerArmed = true;
lastNanos = 0;
Choreographer ch = Choreographer.getInstance();
ch.removeFrameCallback(renderFrameCallback);
ch.postFrameCallback(renderFrameCallback);
}
private void stopLoopOnRenderThread() {
activeLoopGen += 1L;
running = false;
choreographerArmed = false;
Choreographer.getInstance().removeFrameCallback(renderFrameCallback);
}
void onActivityResumed() {
if (destroyed) return;
activityResumed = true;
SurfaceHolder holder = getHolder();
Surface liveSurface = (holder != null) ? holder.getSurface() : null;
int curW = surfaceW > 0 ? surfaceW : getWidth();
int curH = surfaceH > 0 ? surfaceH : getHeight();
float scale = renderScale;
renderHandler.post(() -> {
if (destroyed) return;
if (handle != 0 && EuvNativeBridge.nativeIsRunning(handle) == 0) {
ensureLiveHandleOnRenderThread(curW, curH, scale);
if (handle != 0 && liveSurface != null && liveSurface.isValid() && curW > 0 && curH > 0) {
EuvNativeBridge.nativeSetSurface(handle, liveSurface, curW, curH, scale);
surfaceReady = true;
}
}
if (handle != 0) {
EuvNativeBridge.nativeSystemLifecycle(handle, 3);
}
startLoopOnRenderThread();
if (handle != 0 && surfaceReady) {
scheduleNextFrameOnRenderThread(true);
}
});
}
void onActivityPaused() {
activityResumed = false;
if (destroyed) return;
synchronized (moveLock) {
hasPendingMove = false;
pendingMoveCount = 0;
pendingMoveMask = 0L;
}
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeTouchCancel(handle, -1);
EuvNativeBridge.nativeSystemLifecycle(handle, 4);
}
stopLoopOnRenderThread();
});
}
void startLoop() {
if (destroyed) return;
renderHandler.post(this::startLoopOnRenderThread);
}
void stopLoop() {
if (destroyed) return;
renderHandler.post(this::stopLoopOnRenderThread);
}
void shutdown() {
if (destroyed) return;
destroyed = true;
activityResumed = false;
synchronized (moveLock) {
hasPendingMove = false;
pendingMoveCount = 0;
}
float scale = renderScale;
CountDownLatch latch = new CountDownLatch(1);
boolean posted = renderHandler.post(() -> {
stopLoopOnRenderThread();
surfaceReady = false;
if (handle != 0) {
long closing = handle;
handle = 0;
EuvNativeBridge.nativeTouchCancel(closing, -1);
EuvNativeBridge.nativeSystemLifecycle(closing, 6);
EuvNativeBridge.nativeSetSurface(closing, null, 0, 0, scale);
EuvNativeBridge.nativeDestroy(closing);
}
latch.countDown();
});
if (posted) {
try {
latch.await(1000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
renderThread.quitSafely();
}
private void flushPendingMovesOnRenderThread() {
int count;
long mask;
synchronized (moveLock) {
if (!hasPendingMove) return;
hasPendingMove = false;
count = pendingMoveCount;
pendingMoveCount = 0;
mask = pendingMoveMask;
if (count > 0) {
int byteLen = count * TOUCH_RECORD_BYTES;
touchRingStaging.position(0);
touchRingStaging.limit(byteLen);
touchRingFlush.clear();
touchRingFlush.put(touchRingStaging);
touchRingFlush.flip();
touchRingStaging.clear();
}
}
if (handle == 0 || count <= 0) return;
EuvNativeBridge.nativeFlushTouchBatch(handle, touchRingFlush, count, mask);
}
private int stepAndPresentOnRenderThread(float dt, boolean force) {
return stepAndPresentOnRenderThread(dt, force, System.nanoTime());
}
private int stepAndPresentOnRenderThread(float dt, boolean force, long choreographerFrameTimeNanos) {
if (handle == 0 || !surfaceReady) return 0;
long t0 = System.nanoTime();
int presented = EuvNativeBridge.nativeStepSurfaceWithTimestamp(handle, dt, force ? 1 : 0, choreographerFrameTimeNanos);
if (presented < 0) {
pendingForcePresent = true;
submitRetries += 1;
if (submitRetries <= 5 || submitRetries % 60 == 0) {
Log.w("euv-fps", "android surface submit failed; retrying pending frame on next VSync (retries=" + submitRetries + ")");
}
return -1;
}
if (presented > 0) {
if (!firstPresentNotified) {
firstPresentNotified = true;
if (onFirstFramePresented != null) {
onFirstFramePresented.run();
}
}
double totalMs = (System.nanoTime() - t0) / 1_000_000.0;
double stepMs = EuvNativeBridge.nativeGetLastStepUs(handle) / 1000.0;
double blitMs = EuvNativeBridge.nativeGetLastBlitUs(handle) / 1000.0;
renderedFrames += 1;
accumTotalMs += totalMs;
accumStepMs += stepMs;
accumBlitMs += blitMs;
if (totalMs > maxRenderMs) maxRenderMs = totalMs;
double budgetMs = 1000.0 / targetFps;
if (totalMs > budgetMs) droppedFrames += 1;
if (renderedFrames % 60 == 0) {
int bw = EuvNativeBridge.nativeGetWidth(handle);
int bh = EuvNativeBridge.nativeGetHeight(handle);
int pathId = EuvNativeBridge.nativeGetActivePresentPath(handle);
int mirror = EuvNativeBridge.nativeGetCpuMirrorActive(handle);
int stratId = EuvNativeBridge.nativeGetUploadStrategy(handle);
long uploadBytes = EuvNativeBridge.nativeGetLastUploadBytes(handle);
Log.i("euv-fps", String.format(
"android rendered=%d path=%d cpu_mirror=%d upload_strategy=%d upload_bytes=%d avg=%.2fms (step=%.2fms blit=%.2fms) max=%.2fms dropped=%d retries=%d target=%.0fHz res=%dx%d",
renderedFrames,
pathId,
mirror,
stratId,
uploadBytes,
accumTotalMs / 60.0,
accumStepMs / 60.0,
accumBlitMs / 60.0,
maxRenderMs,
droppedFrames,
submitRetries,
targetFps,
bw,
bh
));
accumTotalMs = 0.0;
accumStepMs = 0.0;
accumBlitMs = 0.0;
maxRenderMs = 0.0;
}
}
return presented;
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (destroyed || event == null) return super.onGenericMotionEvent(event);
if (event.getAction() == MotionEvent.ACTION_SCROLL
&& (event.isFromSource(InputDevice.SOURCE_ROTARY_ENCODER)
|| event.isFromSource(InputDevice.SOURCE_MOUSE))) {
boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
float vAxis = isMouse
? event.getAxisValue(MotionEvent.AXIS_VSCROLL)
: event.getAxisValue(MotionEvent.AXIS_SCROLL);
float hAxis = isMouse
? event.getAxisValue(MotionEvent.AXIS_HSCROLL)
: 0.0f;
if (vAxis != 0.0f || hAxis != 0.0f) {
float vFactor = ViewConfiguration.get(getContext()).getScaledVerticalScrollFactor();
if (vFactor <= 0.0f) vFactor = 48.0f;
float hFactor = ViewConfiguration.get(getContext()).getScaledHorizontalScrollFactor();
if (hFactor <= 0.0f) hFactor = vFactor;
float dx = hAxis * hFactor / Math.max(1.0f, renderScale);
float dy = -vAxis * vFactor / Math.max(1.0f, renderScale);
renderHandler.post(() -> {
if (destroyed || handle == 0) return;
EuvNativeBridge.nativeRotaryScroll(handle, dx, dy);
scheduleNextFrameOnRenderThread(false);
});
return true;
}
}
return super.onGenericMotionEvent(event);
}
void cancelAllTouches() {
synchronized (moveLock) {
hasPendingMove = false;
pendingMoveCount = 0;
}
renderHandler.post(() -> {
if (handle != 0) {
EuvNativeBridge.nativeTouchCancel(handle, -1);
}
});
}
private long buildActiveTouchMask(MotionEvent event, int excludeIndex) {
long mask = 0L;
int count = event.getPointerCount();
for (int i = 0; i < count; i++) {
if (i == excludeIndex) continue;
int pid = event.getPointerId(i);
if (pid >= 0 && pid < 63) {
mask |= (1L << pid);
}
}
return mask;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (destroyed) return false;
int action = event.getActionMasked();
int actionIdx = event.getActionIndex();
float d = renderScale;
switch (action) {
case MotionEvent.ACTION_DOWN: {
int pid = event.getPointerId(actionIdx);
float x = event.getX(actionIdx) / d;
float y = event.getY(actionIdx) / d;
synchronized (moveLock) {
hasPendingMove = false;
pendingMoveCount = 0;
}
renderHandler.post(() -> {
if (destroyed || handle == 0) return;
if (activityResumed && !running) {
startLoopOnRenderThread();
}
EuvNativeBridge.nativeTouchSyncMask(handle, 0L);
EuvNativeBridge.nativeTouchDown(handle, pid, x, y);
});
return true;
}
case MotionEvent.ACTION_POINTER_DOWN: {
int pid = event.getPointerId(actionIdx);
float x = event.getX(actionIdx) / d;
float y = event.getY(actionIdx) / d;
long mask = buildActiveTouchMask(event, -1);
renderHandler.post(() -> {
if (destroyed) return;
flushPendingMovesOnRenderThread();
if (handle == 0) return;
EuvNativeBridge.nativeTouchDown(handle, pid, x, y);
EuvNativeBridge.nativeTouchSyncMask(handle, mask);
});
return true;
}
case MotionEvent.ACTION_MOVE: {
int count = Math.min(TOUCH_BATCH_CAP, event.getPointerCount());
long mask = buildActiveTouchMask(event, -1);
synchronized (moveLock) {
touchRingStaging.clear();
for (int i = 0; i < count; i++) {
touchRingStaging.putInt(MotionEvent.ACTION_MOVE);
touchRingStaging.putInt(i);
touchRingStaging.putInt(event.getPointerId(i));
touchRingStaging.putFloat(event.getX(i) / d);
touchRingStaging.putFloat(event.getY(i) / d);
}
pendingMoveCount = count;
pendingMoveMask = mask;
hasPendingMove = true;
}
return true;
}
case MotionEvent.ACTION_POINTER_UP: {
int pid = event.getPointerId(actionIdx);
float x = event.getX(actionIdx) / d;
float y = event.getY(actionIdx) / d;
long mask = buildActiveTouchMask(event, actionIdx);
renderHandler.post(() -> {
if (destroyed) return;
flushPendingMovesOnRenderThread();
if (handle == 0) return;
EuvNativeBridge.nativeTouchUp(handle, pid, x, y);
EuvNativeBridge.nativeTouchSyncMask(handle, mask);
});
return true;
}
case MotionEvent.ACTION_UP: {
int pid = event.getPointerId(actionIdx);
float x = event.getX(actionIdx) / d;
float y = event.getY(actionIdx) / d;
renderHandler.post(() -> {
if (destroyed) return;
flushPendingMovesOnRenderThread();
if (handle == 0) return;
EuvNativeBridge.nativeTouchUp(handle, pid, x, y);
EuvNativeBridge.nativeTouchSyncMask(handle, 0L);
});
return true;
}
case MotionEvent.ACTION_CANCEL: {
cancelAllTouches();
return true;
}
default:
return super.onTouchEvent(event);
}
}
}
}