package vip.ltpp.euv.showcase;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;
import android.view.Surface;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
public final class EuvNativeBridge {
private static final String CHANNEL_ID = "euv_native_alerts";
private static final Object HOST_LOCK = new Object();
private static final Object NATIVE_LOAD_LOCK = new Object();
private static final Object GLYPH_LOCK = new Object();
private static final Paint GLYPH_PAINT = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG | Paint.LINEAR_TEXT_FLAG);
private static final Rect GLYPH_BOUNDS = new Rect();
private static Bitmap glyphBitmap = null;
private static Canvas glyphCanvas = null;
private static int[] glyphPixels = new int[0];
private static final Typeface[] GLYPH_TYPEFACES = new Typeface[8];
private static Typeface resolveTypeface(int styleFlags) {
int idx = styleFlags & 7;
Typeface cached = GLYPH_TYPEFACES[idx];
if (cached != null) return cached;
boolean bold = (idx & 1) != 0;
boolean italic = (idx & 2) != 0;
boolean mono = (idx & 4) != 0;
Typeface base = mono ? Typeface.MONOSPACE : Typeface.SANS_SERIF;
Typeface created;
if (Build.VERSION.SDK_INT >= 28) {
created = Typeface.create(base, bold ? 700 : 400, italic);
} else {
int tfStyle = (bold ? Typeface.BOLD : 0) | (italic ? Typeface.ITALIC : 0);
created = Typeface.create(base, tfStyle);
}
GLYPH_TYPEFACES[idx] = created;
return created;
}
public static byte[] rasterizeGlyph(int codepoint, float sizePx, int styleFlags) {
if (codepoint <= 0 || !Float.isFinite(sizePx) || sizePx < 1.0f) {
return null;
}
synchronized (GLYPH_LOCK) {
float clampedSize = Math.max(6.0f, Math.min(256.0f, sizePx));
GLYPH_PAINT.setTypeface(resolveTypeface(styleFlags));
GLYPH_PAINT.setTextSize(clampedSize);
GLYPH_PAINT.setColor(0xFFFFFFFF);
GLYPH_PAINT.setAntiAlias(true);
GLYPH_PAINT.setSubpixelText(true);
GLYPH_PAINT.setLinearText(true);
String text = new String(Character.toChars(codepoint));
Paint.FontMetricsInt fm = GLYPH_PAINT.getFontMetricsInt();
int ascent = Math.max(-fm.ascent, (int) Math.ceil(clampedSize * 0.80f));
int descent = Math.max(fm.descent, (int) Math.ceil(clampedSize * 0.24f));
int outH = Math.min(512, Math.max(8, ascent + descent) + 2);
float rawAdv = GLYPH_PAINT.measureText(text);
int advPx = Math.max(2, Math.round(rawAdv));
GLYPH_PAINT.getTextBounds(text, 0, text.length(), GLYPH_BOUNDS);
int padLeft = GLYPH_BOUNDS.left < 0 ? -GLYPH_BOUNDS.left : 0;
int contentRight = Math.max(advPx, padLeft + Math.max(0, GLYPH_BOUNDS.right));
int outW = Math.min(512, Math.max(4, contentRight + 3));
if (glyphBitmap == null || glyphBitmap.getWidth() < outW || glyphBitmap.getHeight() < outH) {
int bw = Math.max(outW, glyphBitmap != null ? glyphBitmap.getWidth() : 128);
int bh = Math.max(outH, glyphBitmap != null ? glyphBitmap.getHeight() : 128);
glyphBitmap = Bitmap.createBitmap(bw, bh, Bitmap.Config.ARGB_8888);
glyphCanvas = new Canvas(glyphBitmap);
}
glyphBitmap.eraseColor(0);
glyphCanvas.drawText(text, padLeft + 1.0f, ascent + 1.0f, GLYPH_PAINT);
int count = outW * outH;
if (glyphPixels.length < count) {
glyphPixels = new int[count];
}
glyphBitmap.getPixels(glyphPixels, 0, outW, 0, 0, outW, outH);
byte[] out = new byte[12 + count];
out[0] = (byte) (outW & 0xFF);
out[1] = (byte) ((outW >>> 8) & 0xFF);
out[2] = (byte) ((outW >>> 16) & 0xFF);
out[3] = (byte) ((outW >>> 24) & 0xFF);
out[4] = (byte) (outH & 0xFF);
out[5] = (byte) ((outH >>> 8) & 0xFF);
out[6] = (byte) ((outH >>> 16) & 0xFF);
out[7] = (byte) ((outH >>> 24) & 0xFF);
out[8] = (byte) (advPx & 0xFF);
out[9] = (byte) ((advPx >>> 8) & 0xFF);
out[10] = (byte) ((advPx >>> 16) & 0xFF);
out[11] = (byte) ((advPx >>> 24) & 0xFF);
for (int i = 0; i < count; i++) {
out[12 + i] = (byte) ((glyphPixels[i] >>> 24) & 0xFF);
}
return out;
}
}
private static volatile boolean nativeLibLoaded = false;
private static WeakReference<Activity> hostActivity = new WeakReference<>(null);
private static long activeSessionGen = 0L;
private static int notifSeq = 100;
public static void ensureNativeLibraryLoaded() {
if (nativeLibLoaded) return;
synchronized (NATIVE_LOAD_LOCK) {
if (!nativeLibLoaded) {
System.loadLibrary("euv_android_host");
nativeLibLoaded = true;
}
}
}
public static long registerHostActivity(Activity activity) {
synchronized (HOST_LOCK) {
activeSessionGen += 1L;
hostActivity = new WeakReference<>(activity);
return activeSessionGen;
}
}
public static void activateHostActivity(Activity activity, long sessionGen) {
if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
return;
}
synchronized (HOST_LOCK) {
Activity current = hostActivity.get();
if (sessionGen >= activeSessionGen || current == null || current.isFinishing() || current.isDestroyed()) {
if (sessionGen > activeSessionGen) {
activeSessionGen = sessionGen;
}
hostActivity = new WeakReference<>(activity);
}
}
}
public static void clearHostActivity(Activity activity, long sessionGen) {
synchronized (HOST_LOCK) {
if (hostActivity.get() == activity && sessionGen == activeSessionGen) {
hostActivity = new WeakReference<>(null);
}
}
}
public static void setHostActivity(Activity activity) {
synchronized (HOST_LOCK) {
if (activity != null) {
activeSessionGen += 1L;
}
hostActivity = new WeakReference<>(activity);
}
}
private static Activity currentHostActivity() {
synchronized (HOST_LOCK) {
return hostActivity.get();
}
}
public static boolean invokeNativeAction(String kind, String arg1, String arg2) {
Activity act = currentHostActivity();
if (act == null || act.isFinishing() || act.isDestroyed()) {
return false;
}
String k = (kind != null) ? kind : "";
String a1 = (arg1 != null) ? arg1 : "";
String a2 = (arg2 != null) ? arg2 : "";
Log.i("euv-native", "invokeNativeAction kind=" + k + " arg1=" + a1 + " arg2=" + a2);
act.runOnUiThread(() -> {
if (act.isDestroyed()) {
return;
}
try {
switch (k) {
case "ime": {
if (act instanceof EuvActivity) {
((EuvActivity) act).setSoftKeyboardVisible("show".equals(a1));
}
break;
}
case "clipboard": {
ClipboardManager cm = (ClipboardManager) act.getSystemService(Context.CLIPBOARD_SERVICE);
if (cm != null) {
cm.setPrimaryClip(ClipData.newPlainText("euv", a2));
}
break;
}
case "haptic": {
Vibrator vib = (Vibrator) act.getSystemService(Context.VIBRATOR_SERVICE);
if (vib != null && vib.hasVibrator()) {
vib.vibrate(VibrationEffect.createOneShot(45, VibrationEffect.DEFAULT_AMPLITUDE));
}
Toast.makeText(act, "Native Haptic + A11y Dispatched", Toast.LENGTH_SHORT).show();
break;
}
case "notify":
case "island": {
NotificationManager nm = (NotificationManager) act.getSystemService(Context.NOTIFICATION_SERVICE);
if ("island".equals(k) && "stop".equals(a1)) {
if (nm != null) {
nm.cancel(99);
}
Toast.makeText(act, "Dynamic Island Live Activity Stopped", Toast.LENGTH_SHORT).show();
break;
}
if (Build.VERSION.SDK_INT >= 33
&& act.checkSelfPermission("android.permission.POST_NOTIFICATIONS") != PackageManager.PERMISSION_GRANTED) {
act.requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"}, 201);
}
if (nm != null) {
NotificationChannel ch = new NotificationChannel(
CHANNEL_ID,
"Euv Native Alerts",
NotificationManager.IMPORTANCE_HIGH
);
nm.createNotificationChannel(ch);
Notification.Builder b = new Notification.Builder(act, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(a1.isEmpty() ? "Euv Studio" : a1)
.setContentText(a2.isEmpty() ? "Native notification dispatched" : a2)
.setAutoCancel(!"island".equals(k))
.setOngoing("island".equals(k));
int nid = "island".equals(k) ? 99 : (++notifSeq);
nm.notify(nid, b.build());
}
Toast.makeText(act, (a1.isEmpty() ? "Notification" : a1) + ": " + a2, Toast.LENGTH_SHORT).show();
break;
}
case "permission": {
if (a1.startsWith("android.permission.")) {
if (act.checkSelfPermission(a1) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(act, "Already Granted: " + a1, Toast.LENGTH_SHORT).show();
} else {
act.requestPermissions(new String[]{a1}, 202);
}
} else {
Toast.makeText(act, "Native Entitlement Checked: " + a1, Toast.LENGTH_SHORT).show();
}
break;
}
case "fullscreen": {
boolean enableFs = "on".equals(a1);
if (act instanceof EuvActivity) {
((EuvActivity) act).setImmersiveFullscreen(enableFs);
} else {
WindowInsetsController ctrl = act.getWindow().getInsetsController();
if (ctrl != null) {
if (enableFs) {
ctrl.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
ctrl.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
} else {
ctrl.show(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
}
}
}
break;
}
case "open_url": {
if (a1.startsWith("https://") || a1.startsWith("http://")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(a1));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.startActivity(intent);
}
break;
}
case "webview": {
if (act instanceof EuvActivity) {
EuvActivity host = (EuvActivity) act;
if ("close".equals(a1)) {
host.closeEmbeddedWebView();
} else if ("reload".equals(a1)) {
host.reloadEmbeddedWebView(a2);
} else if ("frame".equals(a1)) {
String[] parts = a2.split(",");
if (parts.length == 5) {
float fx = Float.parseFloat(parts[0]);
float fy = Float.parseFloat(parts[1]);
float fw = Float.parseFloat(parts[2]);
float fh = Float.parseFloat(parts[3]);
float fa = Float.parseFloat(parts[4]);
host.updateEmbeddedWebViewFrame(fx, fy, fw, fh, fa);
}
} else if (a1.startsWith("https://") || a1.startsWith("http://")) {
host.openEmbeddedWebView(a1);
}
}
break;
}
case "protocol": {
Toast.makeText(act, "DeepLink Scheme Ready: " + a1 + ":// (" + a2 + ")", Toast.LENGTH_SHORT).show();
break;
}
case "toast": {
String msg = a1.isEmpty() ? "Press back again to exit" : a1;
Toast.makeText(act, msg, Toast.LENGTH_SHORT).show();
break;
}
case "exit": {
if (!act.isFinishing() && !act.isDestroyed()) {
act.finish();
}
break;
}
default: {
Toast.makeText(act, "Native Action: " + k + " " + a1, Toast.LENGTH_SHORT).show();
break;
}
}
} catch (Throwable t) {
Log.w("euv-native", "Action failed: " + t.getMessage());
}
});
return true;
}
public static native long nativeCreate(
int physWidth,
int physHeight,
float scale,
float refreshHz,
float safeTop,
float safeRight,
float safeBottom,
float safeLeft
);
public static native void nativeDestroy(long handle);
public static native int nativeIsRunning(long handle);
public static native void nativeUpdateRefreshRate(long handle, float refreshHz);
public static native void nativeImeDisabled(long handle);
public static native void nativeSystemLifecycle(long handle, int tag);
public static native void nativeFocusChanged(long handle, int focused);
public static native void nativeKeyboardChanged(long handle, int visible, float height);
public static native void nativeThemeChanged(long handle, int isDark);
public static native void nativeMemoryWarning(long handle, int level);
public static native void nativeLowPowerChanged(long handle, int enabled);
public static native void nativeNetworkChanged(long handle, int statusTag);
public static native void nativeLocaleChanged(long handle, byte[] utf8Bytes);
public static native void nativeDeepLink(long handle, byte[] utf8Bytes);
public static native void nativeClipboardChanged(long handle);
public static native void nativeDeviceMotion(
long handle,
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
);
public static native void nativeResize(long handle, int physWidth, int physHeight, float scale);
public static native void nativeSetSurface(long handle, Surface surface, int physWidth, int physHeight, float scale);
public static native int nativeStepSurface(long handle, float dt, int forcePresent);
public static native int nativeStepSurfaceWithTimestamp(long handle, float dt, int forcePresent, long choreographerFrameTimeNanos);
public static native int nativeNeedsFrame(long handle);
public static native long nativeGetLastStepUs(long handle);
public static native long nativeGetLastBlitUs(long handle);
public static native int nativeGetCpuMirrorActive(long handle);
public static native int nativeGetActivePresentPath(long handle);
public static native int nativeGetUploadStrategy(long handle);
public static native long nativeGetLastUploadBytes(long handle);
public static native long nativeGetSubmitFailures(long handle);
public static native long nativeGetPresentFailures(long handle);
public static native long nativeGetLastPresentTimestampNs(long handle);
public static native void nativeSetSafeArea(long handle, float top, float right, float bottom, float left);
public static native void nativeTouchDown(long handle, int pointerId, float x, float y);
public static native void nativeTouchMove(long handle, int pointerId, float x, float y);
public static native void nativeTouchUp(long handle, int pointerId, float x, float y);
public static native void nativeTouchCancel(long handle, int pointerId);
public static native void nativeFlushTouchBatch(long handle, ByteBuffer directBuf, int count, long activeMask);
public static native void nativeTouchSyncMask(long handle, long activeMask);
public static native void nativeRotaryScroll(long handle, float dx, float dy);
public static native void nativeAmbientModeChanged(long handle, int ambient);
public static native void nativeSystemBack(long handle);
public static native void nativeTextInput(long handle, byte[] utf8Bytes);
public static native void nativeKeyDown(long handle, int keyTag);
public static native int nativeCopyFramebufferDirect(long handle, ByteBuffer outRgba, int maxBytes);
public static native int nativeStepFrameDirect(long handle, float dt, ByteBuffer outRgba, int maxBytes);
public static native int nativeStepFrame(long handle, float dt, int[] outPixels, int maxLen);
public static native int nativeGetWidth(long handle);
public static native int nativeGetHeight(long handle);
}