diff --git a/.github/workflows/release-beta.yml b/.github/workflows/release-beta.yml index 9b9b6de..519fbad 100644 --- a/.github/workflows/release-beta.yml +++ b/.github/workflows/release-beta.yml @@ -156,6 +156,17 @@ jobs: grep ' dx-x86_64-unknown-linux-gnu.tar.gz$' dx-x86_64-unknown-linux-gnu.sha256 | sha256sum -c - mkdir -p "$HOME/.local/bin" && tar -xzf dx-x86_64-unknown-linux-gnu.tar.gz -C "$HOME/.local/bin" echo "$HOME/.local/bin" >> "$GITHUB_PATH" + - name: Signing key + # Gradle signs debug builds with ~/.android/debug.keystore, which a + # fresh runner makes up anew: every APK had its own key, and Android + # refuses an update signed with another key ("package conflicts"). + # One key for every build lets updates install over the last one. + env: + KEYSTORE: ${{ secrets.ANDROID_DEBUG_KEYSTORE }} + run: | + if [ -z "$KEYSTORE" ]; then echo "::warning::No ANDROID_DEBUG_KEYSTORE secret: this APK gets a one-off key"; exit 0; fi + mkdir -p "$HOME/.android" + echo "$KEYSTORE" | base64 --decode > "$HOME/.android/debug.keystore" - name: Build the APK run: | export ANDROID_NDK_HOME="$ANDROID_NDK_LATEST_HOME" diff --git a/Cargo.lock b/Cargo.lock index 002a01e..fcd60e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3397,11 +3397,17 @@ dependencies = [ name = "mullion-app" version = "0.1.0" dependencies = [ + "anyhow", "dioxus", "futures-channel", + "futures-util", + "jni 0.21.1", + "mullion-host", "mullion-proto", "serde", "serde_json", + "tracing", + "webbrowser", "winresource", ] diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 44cc349..3490573 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -11,6 +11,19 @@ serde_json = { workspace = true } serde = { workspace = true } # The Nearby sweep's answer comes back from a thread (main.rs). futures-channel = "0.3" +# Links out of the page (the update, GitHub) open in the system browser. +webbrowser = "1" + +# Android: "Share this screen" runs a host (src/share.rs). +[target.'cfg(target_os = "android")'.dependencies] +mullion-host = { path = "../host" } +jni = "0.21" +anyhow = { workspace = true } +tracing = { workspace = true } +futures-util = "0.3" + +[dev-dependencies] +mullion-host = { path = "../host" } [features] default = ["desktop"] diff --git a/crates/app/android/kotlin/MainActivity.kt b/crates/app/android/kotlin/MainActivity.kt new file mode 100644 index 0000000..c5a547f --- /dev/null +++ b/crates/app/android/kotlin/MainActivity.kt @@ -0,0 +1,70 @@ +// Mullion's MainActivity: dx's generated one (an empty WryActivity) plus +// "Share this screen". tools/build-android.sh puts this file over dx's. +package dev.dioxus.main + +import android.Manifest +import android.app.Activity +import android.content.Intent +import android.content.pm.PackageManager +import android.media.projection.MediaProjectionManager +import android.os.Build +import android.view.WindowManager +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat + +typealias BuildConfig = app.mullion.tablet.BuildConfig + +class MainActivity : WryActivity() { + /** Called from Rust (share.rs) on this thread: ask Android for consent. */ + fun startShare() { + // The "Stop sharing" notification needs this on Android 13+; sharing works without it. + if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1) + } + val mpm = getSystemService(MediaProjectionManager::class.java) + @Suppress("DEPRECATION") + startActivityForResult(mpm.createScreenCaptureIntent(), SHARE_REQUEST) + } + + /** Called from Rust (share.rs). */ + fun stopShare() { + ShareService.running?.stopNow() ?: MullionNative.onShare(0, 0, 0, filesDir.absolutePath) + } + + /** Called from Rust (share.rs): the page's Full screen button. The web + * view ignores the page's own request, so hide the system bars here. */ + fun setFullscreen(on: Boolean) { + WindowCompat.setDecorFitsSystemWindows(window, !on) + if (Build.VERSION.SDK_INT >= 28) { + window.attributes = window.attributes.apply { + layoutInDisplayCutoutMode = if (on) WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + else WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT + } + } + val bars = WindowCompat.getInsetsController(window, window.decorView) + if (on) { + bars.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + bars.hide(WindowInsetsCompat.Type.systemBars()) + } else { + bars.show(WindowInsetsCompat.Type.systemBars()) + } + } + + @Deprecated("Deprecated in Java") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + @Suppress("DEPRECATION") + super.onActivityResult(requestCode, resultCode, data) + if (requestCode != SHARE_REQUEST) return + if (resultCode != Activity.RESULT_OK || data == null) { + MullionNative.onShare(-1, 0, 0, filesDir.absolutePath) + return + } + val i = Intent(this, ShareService::class.java).putExtra("code", resultCode).putExtra("data", data) + startForegroundService(i) + } + + companion object { + const val SHARE_REQUEST = 4710 + } +} diff --git a/crates/app/android/kotlin/Share.kt b/crates/app/android/kotlin/Share.kt new file mode 100644 index 0000000..45be126 --- /dev/null +++ b/crates/app/android/kotlin/Share.kt @@ -0,0 +1,191 @@ +// "Share this screen": MediaProjection into a hardware H.264 encoder, run by a +// foreground service (Android requires one for screen capture). Every encoder +// output goes to Rust (crates/app/src/share.rs), which streams it to receivers. +// tools/build-android.sh copies this file into dx's Gradle project. +package dev.dioxus.main + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Intent +import android.content.pm.ServiceInfo +import android.graphics.drawable.Icon +import android.hardware.display.DisplayManager +import android.hardware.display.VirtualDisplay +import android.media.MediaCodec +import android.media.MediaCodecInfo +import android.media.MediaFormat +import android.media.projection.MediaProjection +import android.media.projection.MediaProjectionManager +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.HandlerThread +import android.os.IBinder +import android.os.Looper +import android.util.DisplayMetrics +import android.util.Log +import android.view.Display +import java.nio.ByteBuffer + +/** Rust: crates/app/src/share.rs. */ +object MullionNative { + /** One encoder output buffer. Returns true when Rust wants a key frame next. */ + @JvmStatic external fun onH264(buf: ByteBuffer, offset: Int, size: Int, ptsUs: Long, flags: Int): Boolean + + /** 1 sharing at width x height, 0 stopped, -1 the person said no, -2 capture failed. */ + @JvmStatic external fun onShare(state: Int, width: Int, height: Int, dir: String) +} + +class ShareService : Service() { + private var projection: MediaProjection? = null + private var codec: MediaCodec? = null + private var display: VirtualDisplay? = null + private var thread: HandlerThread? = null + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.action == STOP) { + stopNow() + return START_NOT_STICKY + } + if (intent == null || projection != null) return START_NOT_STICKY + // Android 14: the service must be in the foreground before it may + // turn the consent into a MediaProjection. + showNotification() + try { + begin(intent) + } catch (e: Exception) { + Log.e(TAG, "sharing could not start", e) + stopNow() + MullionNative.onShare(-2, 0, 0, filesDir.absolutePath) + } + return START_NOT_STICKY + } + + private fun showNotification() { + val nm = getSystemService(NotificationManager::class.java) + nm.createNotificationChannel(NotificationChannel(CHANNEL, "Screen sharing", NotificationManager.IMPORTANCE_LOW)) + val stop = PendingIntent.getService(this, 0, Intent(this, ShareService::class.java).setAction(STOP), PendingIntent.FLAG_IMMUTABLE) + val open = packageManager.getLaunchIntentForPackage(packageName)?.let { PendingIntent.getActivity(this, 1, it, PendingIntent.FLAG_IMMUTABLE) } + val n = Notification.Builder(this, CHANNEL) + .setSmallIcon(android.R.drawable.ic_menu_share) + .setContentTitle("Mullion is sharing this screen") + .setContentText("Anyone you paired can see it.") + .setOngoing(true) + .setContentIntent(open) + .addAction(Notification.Action.Builder(Icon.createWithResource(this, android.R.drawable.ic_menu_close_clear_cancel), "Stop sharing", stop).build()) + .build() + if (Build.VERSION.SDK_INT >= 29) startForeground(1, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) else startForeground(1, n) + } + + private fun begin(intent: Intent) { + val code = intent.getIntExtra("code", 0) + @Suppress("DEPRECATION") + val data = intent.getParcelableExtra("data") ?: error("no consent") + val p = getSystemService(MediaProjectionManager::class.java).getMediaProjection(code, data) ?: error("no projection") + projection = p + val t = HandlerThread("mullion-share").also { it.start() } + thread = t + val h = Handler(t.looper) + // Android 14: a callback before the virtual display. The person can + // also stop sharing from the system's own controls. + p.registerCallback(object : MediaProjection.Callback() { + override fun onStop() { onMain { stopNow() } } + }, h) + + // The real screen, long side at most 1920, in multiples of 16 (encoders want it). + val m = DisplayMetrics() + @Suppress("DEPRECATION") + getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY).getRealMetrics(m) + val scale = minOf(1.0, 1920.0 / maxOf(m.widthPixels, m.heightPixels)) + val w = (m.widthPixels * scale).toInt() / 16 * 16 + val ht = (m.heightPixels * scale).toInt() / 16 * 16 + + val c = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC) + codec = c + val cb = object : MediaCodec.Callback() { + override fun onInputBufferAvailable(c: MediaCodec, i: Int) {} + override fun onOutputFormatChanged(c: MediaCodec, f: MediaFormat) {} + override fun onError(c: MediaCodec, e: MediaCodec.CodecException) { + Log.e(TAG, "encoder", e) + onMain { stopNow() } + } + override fun onOutputBufferAvailable(c: MediaCodec, i: Int, info: MediaCodec.BufferInfo) { + var key = false + try { + val buf = c.getOutputBuffer(i) + if (buf != null && info.size > 0) key = MullionNative.onH264(buf, info.offset, info.size, info.presentationTimeUs, info.flags) + c.releaseOutputBuffer(i, false) + if (key) c.setParameters(Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) }) + } catch (e: IllegalStateException) { + // Stopping: the codec went away under this callback. + } + } + } + c.setCallback(cb, h) + try { + c.configure(format(w, ht, true), null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) + } catch (e: Exception) { + // Some encoders refuse an explicit profile or low latency: take their defaults. + c.reset() + c.setCallback(cb, h) + c.configure(format(w, ht, false), null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) + } + val surface = c.createInputSurface() + c.start() + display = p.createVirtualDisplay("Mullion", w, ht, m.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, surface, null, null) + running = this + MullionNative.onShare(1, w, ht, filesDir.absolutePath) + } + + private fun format(w: Int, h: Int, tuned: Boolean) = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, w, h).apply { + setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface) + setInteger(MediaFormat.KEY_BIT_RATE, 6_000_000) + setInteger(MediaFormat.KEY_FRAME_RATE, 30) + setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10) + // A still screen sends no frames; repeat the last one so a receiver + // that joins (or loses a packet) still gets a picture. + setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 100_000) + if (tuned) { + setInteger(MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline) + setInteger(MediaFormat.KEY_LEVEL, MediaCodecInfo.CodecProfileLevel.AVCLevel41) + if (Build.VERSION.SDK_INT >= 30) setInteger(MediaFormat.KEY_LOW_LATENCY, 1) + } + } + + // Stopping waits on the encoder, whose callbacks run on `thread`: always stop from the main thread. + private fun onMain(f: () -> Unit) { Handler(Looper.getMainLooper()).post(f) } + + /** Stop capture and encoding, leave the foreground, tell Rust. Main thread; safe to call twice. */ + @Synchronized + fun stopNow() { + val wasRunning = running != null + running = null + try { display?.release() } catch (_: Exception) {} + try { codec?.stop() } catch (_: Exception) {} + try { codec?.release() } catch (_: Exception) {} + val p = projection + display = null; codec = null; projection = null + try { p?.stop() } catch (_: Exception) {} + thread?.quitSafely(); thread = null + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + if (wasRunning) MullionNative.onShare(0, 0, 0, filesDir.absolutePath) + } + + override fun onDestroy() { + stopNow() + super.onDestroy() + } + + companion object { + const val STOP = "app.mullion.tablet.STOP_SHARING" + const val CHANNEL = "share" + const val TAG = "Mullion" + @Volatile var running: ShareService? = null + } +} diff --git a/crates/app/assets/pair.js b/crates/app/assets/pair.js index 1473129..f7af235 100644 --- a/crates/app/assets/pair.js +++ b/crates/app/assets/pair.js @@ -3,7 +3,7 @@ // (window.MullionNoble) because a page served over http:// is not a // secure context and has no crypto.subtle; crypto.getRandomValues works there. // -// pair(base, { name, askCode }) first time: SPAKE2 with the code the Mac shows +// pair(base, { name, hostName, askCode }) first time: SPAKE2 with the code the host shows // load(hostId) / forget(hostId) the stored credential for a host // sealOffer / openAnswer the offer and answer, sealed with the device secret // signed(cred, method, path, body) X-Mullion-Auth header for other requests @@ -107,9 +107,12 @@ // and run SPAKE2. askCode({ hostName, error }) resolves to the typed code, // or null to give up. Resolves to the stored credential, or null. async function pair(base, opts) { + // The host is a Mac or, sharing its screen, a tablet: call it by its name. + const who = opts.hostName || 'the host'; + const Who = who[0].toUpperCase() + who.slice(1); const s = await post(base + '/pair/start', { name: opts.name }); - if (s.status === 429) throw new Error('Another device is pairing with this Mac. Try again in a few seconds.'); - if (s.status !== 200 || !s.data) throw new Error('This Mac did not start pairing.'); + if (s.status === 429) throw new Error(`Another device is pairing with ${who}. Try again in a few seconds.`); + if (s.status !== 200 || !s.data) throw new Error(`${Who} did not start pairing.`); const { pairing, host_id: hostId } = s.data; let error = ''; for (;;) { @@ -128,13 +131,13 @@ if (c.status === 403) { const left = c.data && c.data.left; if (!left) throw new Error('Wrong code too many times. Connect again for a new one.'); - error = `That code is not the one on the Mac. ${left === 1 ? '1 try' : left + ' tries'} left.`; + error = `That code is not the one on ${who}. ${left === 1 ? '1 try' : left + ' tries'} left.`; continue; } if (c.status === 410) throw new Error('The code expired. Connect again for a new one.'); if (c.status !== 200) throw new Error('Pairing failed.'); - // The Mac proves it knew the code too, so this is the Mac that showed it. - if (!sameBytes(unb64(c.data.mac), mac(k.h, 'host'))) throw new Error('This Mac could not prove the code. Pairing stopped.'); + // The host proves it knew the code too, so this is the host that showed it. + if (!sameBytes(unb64(c.data.mac), mac(k.h, 'host'))) throw new Error(`${Who} could not prove the code. Pairing stopped.`); const plain = JSON.parse(dec.decode(open(k.s, 'mullion pair seal', c.data.credential))); const cred = { host_id: plain.host_id, host_name: plain.host_name, device: plain.device, secret: plain.secret }; store(cred); diff --git a/crates/app/assets/ui.css b/crates/app/assets/ui.css index f876a27..91844dd 100644 --- a/crates/app/assets/ui.css +++ b/crates/app/assets/ui.css @@ -10,20 +10,41 @@ --glass: rgba(247, 247, 245, 0.72); --glass-edge: rgba(255, 255, 255, 0.5); --hud: rgba(17, 20, 24, 0.86); --radius: 12px; + /* Raised surfaces: in dark they get lighter as they rise (cards, then + dialogs), since shadows barely show on a dark page. */ + --surface: #FFFFFF; --surface-2: #FFFFFF; + --heart: #BF3989; + color-scheme: light; } +/* Dark: the system's choice unless this device picked Light; or this device + picked Dark. The theme switch in the footer sets data-theme (ui.js). */ @media (prefers-color-scheme: dark) { - :root { + :root:not([data-theme="light"]) { --ink: #ECEDEE; --paper: #0F1113; --line: #2A2E33; + --surface: #171A1E; --surface-2: #1E2227; --accent: #5B93FF; --on-accent: #0F1113; --device: #FF7A52; --device-1: #FF7A52; --device-2: #3CC7AE; --device-3: #B98CF0; --glass: rgba(17, 20, 24, 0.72); --glass-edge: rgba(255, 255, 255, 0.08); + --heart: #E85AAD; + color-scheme: dark; } } +:root[data-theme="dark"] { + --ink: #ECEDEE; --paper: #0F1113; --line: #2A2E33; + --surface: #171A1E; --surface-2: #1E2227; + --accent: #5B93FF; --on-accent: #0F1113; + --device: #FF7A52; + --device-1: #FF7A52; --device-2: #3CC7AE; --device-3: #B98CF0; + --glass: rgba(17, 20, 24, 0.72); --glass-edge: rgba(255, 255, 255, 0.08); + --heart: #E85AAD; + color-scheme: dark; +} html, body { margin: 0; height: 100%; background: var(--paper); color: var(--ink); font: 15px/1.5 system-ui, -apple-system, "Segoe UI Variable", Roboto, sans-serif; - font-optical-sizing: auto; -webkit-font-smoothing: antialiased; overflow: hidden; } + font-optical-sizing: auto; -webkit-font-smoothing: antialiased; overflow: hidden; + transition: background-color 200ms ease-out, color 200ms ease-out; } * { box-sizing: border-box; } button, input, select { font: inherit; color: inherit; } @@ -43,28 +64,34 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify- .stage.live ~ .status { top: calc(max(12px, env(safe-area-inset-top)) + 58px); } /* Setup card: the only solid surface; anchored to the centre, materializes. */ -.setup { position: fixed; inset: 0; display: grid; place-items: center; padding: 24px; - background: var(--paper); } -.card { width: min(420px, 100%); display: grid; gap: 14px; +/* It scrolls when the card is taller than the screen (a phone in landscape, a + long Nearby list), and the footer (version, links) sits under the card in + the flow, so neither ever covers the other. */ +.setup { position: fixed; inset: 0; overflow-y: auto; overscroll-behavior: contain; background: var(--paper); + display: grid; grid-template-columns: 1fr auto; grid-template-rows: 1fr auto auto; column-gap: 8px; + padding: max(24px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) + max(12px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); } +.card { grid-column: 1 / -1; align-self: safe center; justify-self: center; margin-bottom: 20px; + width: min(440px, 100%); display: grid; gap: 14px; will-change: transform, opacity, filter; transform-origin: 50% 50%; } .card .brand { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; } .card .brand svg { width: 44px; height: 44px; flex: none; } -.card .brand h1 { font-size: 22px; line-height: 1.2; letter-spacing: -0.01em; font-weight: 650; margin: 0; } +.card .brand h1 { font-size: clamp(20px, 18px + 0.6vw, 26px); line-height: 1.2; letter-spacing: -0.01em; font-weight: 650; margin: 0; } .card .brand p { margin: 0; opacity: .7; font-size: 13px; letter-spacing: 0; } .field { display: grid; gap: 4px; } .field label { font-size: 12px; font-weight: 600; letter-spacing: .01em; opacity: .75; } .field input, .field select { width: 100%; padding: 10px 12px; border-radius: 10px; - border: 1px solid var(--line); background: transparent; outline: none; + border: 1px solid var(--line); background: var(--surface); outline: none; font-variant-numeric: tabular-nums; transition: border-color 120ms ease-out, box-shadow 120ms ease-out; } .field input:focus-visible, .field select:focus-visible { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent); } -.row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +.row { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(170px, 100%), 1fr)); gap: 10px; } .seg { display: grid; grid-template-columns: 1fr 1fr; padding: 3px; border-radius: 10px; border: 1px solid var(--line); position: relative; } .seg button { position: relative; z-index: 1; background: none; border: 0; padding: 8px 0; border-radius: 8px; font-weight: 600; opacity: .7; } .seg .i { width: 16px; height: 16px; } .seg button[aria-pressed="true"] { opacity: 1; color: var(--on-accent); } .seg .thumb { position: absolute; top: 3px; bottom: 3px; left: 3px; width: calc(50% - 3px); border-radius: 8px; background: var(--accent); will-change: transform; } -.primary { padding: 12px 16px; border-radius: 10px; border: 0; background: var(--accent); color: var(--on-accent); +.primary { min-height: 44px; padding: 12px 16px; border-radius: 10px; border: 0; background: var(--accent); color: var(--on-accent); font-weight: 650; letter-spacing: 0; cursor: pointer; will-change: transform; transition: transform 100ms ease-out, filter 100ms ease-out; } .primary:active, .primary.pressed { transform: scale(0.97); filter: brightness(.95); } @@ -88,7 +115,7 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify- .hosts { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } .hosts:empty { display: none; } .host { width: 100%; display: flex; align-items: center; gap: 12px; padding: 10px 12px; text-align: left; cursor: pointer; - border-radius: 12px; border: 1px solid var(--line); background: transparent; will-change: transform, opacity; + border-radius: 12px; border: 1px solid var(--line); background: var(--surface); will-change: transform, opacity; transition: border-color 120ms ease-out, background 120ms ease-out; } .host:hover { border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); } .host:active, .host.pressed { background: color-mix(in srgb, var(--accent) 8%, transparent); } @@ -104,7 +131,7 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify- .nearby-empty { margin: 0; font-size: 13px; opacity: .7; } .nearby-empty:empty { display: none; } -.ghost { justify-self: center; padding: 8px 14px; border-radius: 10px; border: 0; background: transparent; color: var(--ink); +.ghost { justify-self: center; min-height: 40px; padding: 8px 14px; border-radius: 10px; border: 0; background: transparent; color: var(--ink); font-size: 14px; font-weight: 600; opacity: .8; cursor: pointer; transition: transform 100ms ease-out, opacity 120ms ease-out, background 120ms ease-out; } .ghost:hover, .ghost:focus-visible { opacity: 1; background: color-mix(in srgb, var(--ink) 7%, transparent); } .ghost:active { transform: scale(0.97); } @@ -116,11 +143,20 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify- .pair input { font: 600 26px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .25em; text-align: center; font-variant-numeric: tabular-nums; } .pair-actions { display: grid; gap: 6px; margin-top: 6px; } .hint.err { opacity: 1; } +/* Share this screen (Android app): while sharing, the card shows only that. */ +.card.sharing > :not(.brand):not(#shareBox):not(#hint) { display: none; } +.share[hidden], .share-code[hidden] { display: none; } +.share { display: grid; gap: 10px; } +.share h2 { margin: 0; } +.share p { margin: 0; font-size: 14px; line-height: 1.45; } +.share-code { display: grid; gap: 6px; justify-items: center; padding: 12px; border-radius: 12px; background: color-mix(in srgb, var(--accent) 10%, transparent); text-align: center; } +.share-code .code { font: 600 34px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .2em; font-variant-numeric: tabular-nums; } +.share-viewers { opacity: .7; } /* Project links: bottom-right of the setup screen, quiet until touched. They live inside .setup, so they leave with the card and never sit on the video. */ -.links { position: fixed; right: max(16px, env(safe-area-inset-right)); bottom: max(14px, env(safe-area-inset-bottom)); - display: flex; gap: 4px; } +.links { grid-column: 2; grid-row: 2 / 4; align-self: end; + display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 4px; } .links a { padding: 6px 10px; border-radius: 9px; color: var(--ink); text-decoration: none; font-size: 13px; font-weight: 600; letter-spacing: .01em; opacity: .7; transition: opacity 120ms ease-out, background 120ms ease-out, transform 100ms ease-out; } @@ -128,19 +164,32 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify- .links a:active { transform: scale(0.97); } .links a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .links .i { width: 16px; height: 16px; } +/* The theme switch sits with the links and looks like them. */ +.links button { border: 0; background: transparent; cursor: pointer; padding: 6px 10px; border-radius: 9px; color: var(--ink); + font-size: 13px; font-weight: 600; letter-spacing: .01em; opacity: .7; display: inline-flex; align-items: center; gap: 7px; } +.links button:hover, .links button:focus-visible { opacity: 1; background: color-mix(in srgb, var(--ink) 7%, transparent); } +.links button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } /* Version, bottom left, opposite the links; same type, quieter. */ -.version { position: fixed; left: max(16px, env(safe-area-inset-left)); bottom: max(14px, env(safe-area-inset-bottom)); +.version { grid-column: 1; grid-row: 3; align-self: end; justify-self: start; margin: 0; padding: 6px 10px; color: var(--ink); opacity: .55; font-size: 13px; font-weight: 600; - letter-spacing: .01em; font-variant-numeric: tabular-nums; user-select: text; } + letter-spacing: .01em; font-variant-numeric: tabular-nums; user-select: text; white-space: nowrap; } .version:empty { display: none; } /* The apps' update check (ui.js): a link just above the version. */ -.update { position: fixed; left: max(16px, env(safe-area-inset-left)); bottom: calc(max(14px, env(safe-area-inset-bottom)) + 22px); +.update { grid-column: 1; grid-row: 2; align-self: end; justify-self: start; font-size: 13px; font-weight: 600; color: var(--accent); text-decoration: none; padding: 4px 10px; } .update:hover, .update:focus-visible { text-decoration: underline; } -.update[hidden] { display: none; } +.update[hidden], .update-bar[hidden] { display: none; } +/* A newer version: asked once per start, above everything on the setup screen. */ +.update-bar { position: fixed; z-index: 30; left: 50%; transform: translateX(-50%); + bottom: calc(max(16px, env(safe-area-inset-bottom)) + 52px); width: min(420px, calc(100% - 32px)); + display: grid; gap: 10px; padding: 14px; border-radius: var(--radius); + background: var(--surface-2); border: 1px solid var(--line); box-shadow: 0 8px 28px rgba(0, 0, 0, .18); } +.update-bar p { margin: 0; font-size: 14px; line-height: 1.45; } +.update-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } +.update-actions .ghost { justify-self: stretch; } + /* GitHub's sponsor heart colour; a non-text mark (4.7:1 light, 5.9:1 dark on --paper). */ -.links .heart { color: #BF3989; } -@media (prefers-color-scheme: dark) { .links .heart { color: #E85AAD; } } +.links .heart { color: var(--heart); } /* Floating toolbar: translucent, hides over the video after a pause. */ .toolbar { position: fixed; left: 50%; top: max(12px, env(safe-area-inset-top)); transform: translate(-50%, 0); @@ -179,7 +228,7 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify- visibility: hidden; pointer-events: none; } .sheet .scrim { position: absolute; inset: 0; background: rgba(15, 17, 19, 0.5); opacity: 0; } .panel { position: relative; width: min(980px, 100%); outline: none; max-height: 100%; display: grid; grid-template-rows: auto 1fr auto; gap: 12px; - padding: 18px 18px 14px; border-radius: 16px; background: var(--paper); color: var(--ink); border: 1px solid var(--line); + padding: 18px 18px 14px; border-radius: 16px; background: var(--surface-2); color: var(--ink); border: 1px solid var(--line); box-shadow: 0 24px 64px rgba(0, 0, 0, 0.32); will-change: transform, opacity; transform-origin: 50% 60%; } .panel header { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; } .panel h2 { margin: 0; display: flex; align-items: center; gap: 8px; font-size: 22px; line-height: 1.2; font-weight: 650; letter-spacing: -0.01em; } @@ -236,6 +285,21 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify- .hud, .status { outline: 1px solid #fff; } } @media (prefers-reduced-motion: reduce) { + html, body { transition: none; } .card, .toolbar, .status, .seg .thumb, .links a, .board, .tile, .slot, .host, .scanbar span { transition: opacity 150ms ease !important; } .stage video { transition: opacity 150ms ease; } } + +/* Touch screens: every control at least 44px each way. */ +@media (pointer: coarse) { + .ghost, .seg button, .links a, .links button, .toolbar button { min-height: 44px; } + .icon-btn { width: 44px; height: 44px; } +} +/* Narrow screens: the toolbar keeps its icons and drops the words (still + read out: the label stays in the button, only hidden from view). */ +@media (max-width: 560px) { + .toolbar { max-width: calc(100% - 24px); gap: 4px; } + .toolbar .name { max-width: 28vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .toolbar button > span { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .toolbar button { padding: 6px 8px; } +} diff --git a/crates/app/assets/ui.html b/crates/app/assets/ui.html index 44abc3e..2952a41 100644 --- a/crates/app/assets/ui.html +++ b/crates/app/assets/ui.html @@ -10,6 +10,15 @@ + + + + + + + + + @@ -60,17 +69,37 @@
- - + +
+ +

+ diff --git a/crates/app/assets/ui.js b/crates/app/assets/ui.js index 9ea9fb0..0a507e8 100644 --- a/crates/app/assets/ui.js +++ b/crates/app/assets/ui.js @@ -46,6 +46,25 @@ // Buttons hold an icon plus a label span; change the parts, never textContent. const setIcon = (use, name) => use.setAttribute('href', '#i-' + name); + // Colours: Auto follows the system; Light or Dark is this device's choice, + // kept with its other settings. ui.css reads data-theme on . + const THEMES = ['auto', 'light', 'dark']; + const THEME_NAMES = { auto: 'Auto', light: 'Light', dark: 'Dark' }; + let theme = 'auto'; + try { const t = localStorage.getItem('mullion.theme'); if (THEMES.includes(t)) theme = t; } catch (e) { /* storage off */ } + function applyTheme() { + if (theme === 'auto') delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = theme; + setIcon($('themeIcon'), 'theme-' + theme); + $('themeLabel').textContent = THEME_NAMES[theme]; + $('themeBtn').title = `Colours: ${THEME_NAMES[theme]}. Tap to switch.`; + } + applyTheme(); + $('themeBtn').addEventListener('click', () => { + theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length]; + try { localStorage.setItem('mullion.theme', theme); } catch (e) { /* storage off */ } + applyTheme(); + }); + let mode = localStorage.getItem('mullion.mode') || 'mirror'; // Viewer mode: the page is in Mullion.app's "Connect to Another Computer…" // window, served by this Mac's own host. That host is not a target: it is @@ -359,6 +378,68 @@ // Version, bottom left: the host's when it served this page, the app's in the tablet app. if (window.MULLION_VERSION) $('version').textContent = 'Mullion ' + window.MULLION_VERSION; + // --- Share this screen (Android app): the tablet becomes a host (app share.rs) --- + // A Mac connects to it like to any host; the code to pair shows here. + if (window.mullionNative && window.mullionNative.share) { + const shareBtn = $('shareBtn'), shareBox = $('shareBox'), shareCodeBox = $('shareCodeBox'); + let viewersTimer = 0, waiting = 0; + // Rust's events wait while Android has paused the app (its dialogs, another + // app in front) until the page sends something: poke while waiting for + // Android's answer and on coming back. While sharing, countViewers does it. + const poke = () => window.mullionNative.poke(); + addEventListener('focus', poke); + document.addEventListener('visibilitychange', () => { if (!document.hidden) poke(); }); + const countViewers = async () => { + try { + const r = await window.mullionFetch('http://127.0.0.1:47100/devices'); + const n = ((await r.json()).devices || []).length; + $('shareViewers').textContent = n === 0 ? 'No one is watching yet.' : n === 1 ? '1 device is watching.' : `${n} devices are watching.`; + } catch (e) { $('shareViewers').textContent = ''; } + }; + const showSharing = (on) => { + card.classList.toggle('sharing', on); shareBox.hidden = !on; shareCodeBox.hidden = true; + clearInterval(viewersTimer); + if (on) { countViewers(); viewersTimer = setInterval(countViewers, 2000); } + }; + shareBtn.hidden = false; + shareBtn.onclick = () => { + hint.textContent = 'Android asks before this screen is shared.'; hint.classList.remove('err'); + window.mullionNative.share(true, nameEl.value); + clearInterval(waiting); waiting = setInterval(poke, 1000); + }; + $('shareStop').onclick = () => window.mullionNative.share(false); + $('shareDeny').onclick = () => { window.mullionNative.pairDeny(); shareCodeBox.hidden = true; }; + addEventListener('mullion-native', (e) => { + const m = e.detail; + if (m.kind === 'share') { + clearInterval(waiting); + showSharing(m.state === 'on'); + if (m.state === 'on') { $('shareAddr').textContent = m.address; hint.textContent = ''; } + else { hint.textContent = m.error || ''; hint.classList.toggle('err', !!m.error); } + } else if (m.kind === 'pair_code') { + $('shareWho').textContent = `${m.name} wants to see this screen. Enter this code there:`; + $('shareCode').textContent = `${m.code.slice(0, 3)} ${m.code.slice(3)}`; + shareCodeBox.hidden = false; + } else if (m.kind === 'pair_closed') { + shareCodeBox.hidden = true; + } + }); + } + + // Links out (the update, GitHub, Sponsor) open in the system browser. In + // the apps a web view would try them itself: Android's ignores a new + // window, and neither can install a download. + function openOutside(url) { + if (window.mullionNative && window.mullionNative.open) window.mullionNative.open(url); + else window.open(url, '_blank', 'noopener'); + } + document.addEventListener('click', (e) => { + const a = e.target.closest && e.target.closest('a[href^="https://"]'); + if (!a || !(window.mullionNative && window.mullionNative.open)) return; + e.preventDefault(); + window.mullionNative.open(a.href); + }); + // The Windows and Android apps look for a newer beta on GitHub at start and // every 6 hours, and offer this platform's file (Mullion.app has its own // updater in the menu bar). The page can call GitHub itself: it is HTTPS. @@ -385,6 +466,7 @@ } return false; } + let asked = ''; async function checkUpdate() { if (!UPDATE_FILE || !window.MULLION_VERSION) return; try { @@ -400,10 +482,16 @@ const link = $('update'); link.href = best.url; link.textContent = `Get Mullion ${best.version}`; - // Beta APKs are signed with a different key each build, so Android - // will not install one over the other. - link.title = window.MULLION_APP === 'android' ? 'Remove this app first, then install the new one.' : 'Download the new version'; + link.title = 'Download the new version'; link.hidden = false; + // Ask once per start (the link stays after Later). + if (asked === best.version) return; + asked = best.version; + $('updateText').textContent = `Mullion ${best.version} is out. You have ${window.MULLION_VERSION}.`; + const bar = $('updateBar'); + bar.hidden = false; + $('updateLater').onclick = () => { bar.hidden = true; }; + $('updateGo').onclick = () => { bar.hidden = true; openOutside(best.url); }; } catch (e) { /* offline or rate-limited: try again later */ } } if (UPDATE_FILE) { setTimeout(checkUpdate, 3000); setInterval(checkUpdate, 6 * 3600 * 1000); } diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index c47ef18..a4f2559 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -10,6 +10,9 @@ // Windows release build: a window app, no console window behind it. #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] +#[cfg(any(target_os = "android", test))] +mod share; + use dioxus::document::eval; use dioxus::prelude::*; @@ -88,16 +91,31 @@ fn App() -> Element { // (mullion_proto::lanhttp). The Android page is https://dioxus.index.html // and its WebView blocks every http:// request as mixed content, so the // page cannot reach a host with fetch. - // - fullscreen(on), desktop only: the page's Full screen button fills only - // the web view (WebView2 does not resize the window), so this makes the - // window itself borderless full screen. + // - share(on, name), pairDeny(), Android only: "Share this screen" + // (share.rs). Its state and pairing codes come back as a + // `mullion-native` event on window ({kind: 'share' | 'pair_code' | 'pair_closed'}). + // While Android pauses the app (its consent and permission dialogs, + // another app in front) those events wait until the page next sends + // something; poke() is that something. + // - fullscreen(on): the page's Full screen button. On Windows the page's own + // fills only the web view (WebView2 does not resize the window), so the + // window itself goes borderless full screen; on Android the web view + // ignores it, so the activity hides the system bars (MainActivity.kt). + // - open(url): an https link in the system browser (the update, GitHub). // Replies are tagged, and slow work runs on its own thread, so one sweep // never holds up a request or the full screen toggle. use_future(move || async move { - let fullscreen = if cfg!(feature = "desktop") { "fullscreen: (on) => dioxus.send({ fullscreen: !!on })," } else { "" }; + // Every app: full screen is native (a web view's own fills only itself on + // Windows, and does nothing on Android), links out open in the browser. + let fullscreen = "fullscreen: (on) => dioxus.send({ fullscreen: !!on }), open: (url) => dioxus.send({ open: String(url) }),"; + let share = if cfg!(target_os = "android") { + "share: (on, name) => dioxus.send({ share: { on: !!on, name: String(name || '') } }), pairDeny: () => dioxus.send({ pairDeny: true }), poke: () => dioxus.send({ poke: true })," + } else { + "" + }; let bridge = eval(&format!( "const nearby = [], pending = new Map(); let next = 1; - window.mullionNative = {{ {fullscreen} + window.mullionNative = {{ {fullscreen} {share} nearby: () => new Promise((r) => {{ if (nearby.push(r) === 1) dioxus.send({{ nearby: true }}); }}), http: (method, url, headers, body) => new Promise((r) => {{ const id = next++; pending.set(id, r); dioxus.send({{ http: {{ id, method, url, headers: headers || {{}}, body: body || '' }} }}); }}), }}; @@ -105,8 +123,17 @@ fn App() -> Element { const m = await dioxus.recv(); if (m.kind === 'nearby') nearby.splice(0).forEach((r) => r(m.found)); else if (m.kind === 'http') {{ const r = pending.get(m.id); pending.delete(m.id); if (r) r(m); }} + else window.dispatchEvent(new CustomEvent('mullion-native', {{ detail: m }})); }}" )); + #[cfg(target_os = "android")] + spawn(async move { + use futures_util::StreamExt; + let mut events = share::events(); + while let Some(v) = events.next().await { + let _ = bridge.send(v); + } + }); let mut rx = bridge; while let Ok(msg) = rx.recv::().await { if msg["nearby"] == true { @@ -133,9 +160,30 @@ fn App() -> Element { }); }); } - #[cfg(feature = "desktop")] + #[cfg(target_os = "android")] + { + if let Some(on) = msg["share"]["on"].as_bool() { + share::set_share(on, msg["share"]["name"].as_str().unwrap_or("").to_string()); + } + if msg["pairDeny"] == true { + share::deny_pairing(); + } + } + if let Some(url) = msg["open"].as_str() { + // Only web pages: the page is ours, but this is a way out of it. + if url.starts_with("https://") { + if let Err(e) = webbrowser::open(url) { + eprintln!("open {url}: {e}"); + } + } + } if let Some(on) = msg["fullscreen"].as_bool() { - dioxus::desktop::window().set_fullscreen(on); + // Borderless(None): the window's own monitor. dioxus's + // set_fullscreen does nothing when it cannot name that monitor. + #[cfg(feature = "desktop")] + dioxus::desktop::window().window.set_fullscreen(on.then_some(dioxus::desktop::tao::window::Fullscreen::Borderless(None))); + #[cfg(target_os = "android")] + share::set_fullscreen(on); } } }); diff --git a/crates/app/src/share.rs b/crates/app/src/share.rs new file mode 100644 index 0000000..7e486fb --- /dev/null +++ b/crates/app/src/share.rs @@ -0,0 +1,312 @@ +//! "Share this screen" (Android): the tablet becomes a Mirror-only Mullion +//! host, so a Mac (Connect to Another Computer…) or a browser shows it. +//! +//! Capture and encoding are Android's (crates/app/android/kotlin/Share.kt: +//! MediaProjection into a hardware H.264 encoder, in a foreground service). +//! Each encoder output reaches `MullionNative.onH264` here, becomes an +//! `EncodedFrame`, and goes to the host's sessions (mullion_host, the same +//! core as the Mac's). Pairing works as on the Mac: the tablet shows the code. + +use mullion_host::platform::EncodedFrame; + +/// MediaCodec.BufferInfo flags. +const FLAG_KEY_FRAME: i32 = 1; +const FLAG_CODEC_CONFIG: i32 = 2; + +/// Encoder output to `EncodedFrame`s. MediaCodec hands over SPS/PPS once, as +/// a codec-config buffer; receivers that join later need them in front of +/// every IDR, so they are kept and prepended (Annex B either way). +#[derive(Default)] +pub struct Assembler { + config: Vec, + seq: u64, +} + +impl Assembler { + pub fn push(&mut self, flags: i32, bytes: &[u8], pts_us: i64, now_ms: f64) -> Option { + if flags & FLAG_CODEC_CONFIG != 0 { + self.config = bytes.to_vec(); + return None; + } + let idr = flags & FLAG_KEY_FRAME != 0; + let has_sps = mullion_proto::h264::split_annex_b(bytes).first().is_some_and(|n| !n.is_empty() && n[0] & 0x1f == 7); + let data = if idr && !has_sps { [self.config.as_slice(), bytes].concat() } else { bytes.to_vec() }; + self.seq += 1; + Some(EncodedFrame { + seq: self.seq, + capture_ms: now_ms, + encode_done_ms: now_ms, + rtp_time_90k: (pts_us.max(0) as u64) * 9 / 100, + idr, + data, + }) + } +} + +#[cfg(target_os = "android")] +pub use android::{deny_pairing, events, set_fullscreen, set_share}; + +#[cfg(target_os = "android")] +mod android { + use super::Assembler; + use std::path::PathBuf; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::mpsc::Sender; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use anyhow::{bail, Result}; + use dioxus::mobile::wry::prelude::dispatch; + use futures_channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}; + use jni::objects::{JByteBuffer, JClass, JString}; + use jni::sys::{jboolean, jint, jlong, JNI_FALSE, JNI_TRUE}; + use jni::JNIEnv; + use mullion_host::pairing::Notice; + use mullion_host::platform::{DisplayInfo, EncodedFrame, Pipeline, PipelineConfig, Platform, Source, VirtualDisplay}; + use serde_json::{json, Value}; + + #[derive(Default)] + struct State { + sharing: bool, + size: (u32, u32), + asm: Assembler, + sink: Option>, + host: Option, + name: String, + } + + static STATE: Mutex> = Mutex::new(None); + /// Set by a session (join, picture loss); the encoder reads it on its next output. + static WANT_IDR: AtomicBool = AtomicBool::new(false); + /// Events for the page (main.rs forwards them over the bridge). + static EVENTS: Mutex>> = Mutex::new(None); + + fn with(f: impl FnOnce(&mut State) -> T) -> T { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) + } + + fn emit(v: Value) { + if let Some(tx) = EVENTS.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + let _ = tx.unbounded_send(v); + } + } + + /// The page's end of the events: share state and pairing codes. + pub fn events() -> UnboundedReceiver { + let (tx, rx) = unbounded(); + *EVENTS.lock().unwrap_or_else(|e| e.into_inner()) = Some(tx); + rx + } + + /// Start (asks Android for consent first) or stop sharing. `name` is what + /// receivers see this tablet as. + pub fn set_share(on: bool, name: String) { + with(|s| s.name = name); + let method = if on { "startShare" } else { "stopShare" }; + dispatch(move |env, activity, _| { + if let Err(e) = env.call_method(activity, method, "()V", &[]) { + tracing::warn!("{method}: {e}"); + let _ = env.exception_clear(); + emit(json!({ "kind": "share", "state": "off", "error": "This tablet can't share its screen." })); + } + }); + } + + /// The page's Full screen button: Android's web view ignores the page's + /// own request, so the activity hides the system bars instead. + pub fn set_fullscreen(on: bool) { + dispatch(move |env, activity, _| { + if env.call_method(activity, "setFullscreen", "(Z)V", &[on.into()]).is_err() { + let _ = env.exception_clear(); + } + }); + } + + /// "Don't Allow" next to the pairing code. + pub fn deny_pairing() { + if let Some(p) = with(|s| s.host.as_ref().map(|h| h.pairing.clone())) { + p.cancel(); + } + } + + struct AndroidPlatform; + + struct SharePipeline; + + impl Pipeline for SharePipeline { + fn request_idr(&self) { + WANT_IDR.store(true, Ordering::Relaxed); + } + fn stop(&mut self) { + with(|s| s.sink = None); + } + } + + impl Platform for AndroidPlatform { + fn name(&self) -> &'static str { + "Android (MediaProjection + MediaCodec)" + } + fn start_pipeline(&self, source: Source, _: &PipelineConfig, tx: Sender) -> Result> { + if source != Source::Main { + bail!("a tablet can only be mirrored"); + } + if !with(|s| s.sharing) { + bail!("this tablet is not sharing its screen"); + } + with(|s| s.sink = Some(tx)); + WANT_IDR.store(true, Ordering::Relaxed); + Ok(Box::new(SharePipeline)) + } + fn create_virtual_display(&self, _: u32, _: u32, _: u32, _: &str, _: u32) -> Result>> { + Ok(None) + } + fn displays(&self) -> Result> { + let (width, height) = with(|s| s.size); + Ok(vec![DisplayInfo { id: 1, x: 0, y: 0, width, height, main: true, builtin: true }]) + } + } + + /// The host runs from the first share on (its port and pairing store stay); + /// between shares, connecting is refused by `start_pipeline`. + fn start_host(dir: PathBuf, size: (u32, u32), name: String) -> Result { + mullion_host::start(mullion_host::HostOptions { + platform: Arc::new(AndroidPlatform), + addr: ([0, 0, 0, 0], 47100).into(), + web_port: 0, + host_name: if name.trim().is_empty() { "Android tablet".into() } else { name }, + kind: "tablet", + session: mullion_host::session::SessionConfig { + advertise_ips: mullion_host::lan_ips(), + pipeline: PipelineConfig { width: size.0, height: size.1, fps: 30, require_hardware: false, ..Default::default() }, + extend: false, + display_grace: Duration::from_secs(5), + multi_session: true, + }, + config: json!({ "extend": false }), + log: Arc::new(mullion_host::timing::TimingLog::new(None)?), + pairing_store: dir.join("paired.json"), + notify: Box::new(|n| match n { + Notice::Code { name, code } => emit(json!({ "kind": "pair_code", "name": name, "code": code })), + Notice::Closed => emit(json!({ "kind": "pair_closed" })), + }), + }) + } + + fn now_ms() -> f64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64() * 1000.0).unwrap_or(0.0) + } + + /// Share.kt: one encoder output buffer. Returns whether the next frame + /// should be a key frame. + #[no_mangle] + pub extern "system" fn Java_dev_dioxus_main_MullionNative_onH264( + env: JNIEnv, + _: JClass, + buf: JByteBuffer, + offset: jint, + size: jint, + pts_us: jlong, + flags: jint, + ) -> jboolean { + let (Ok(ptr), Ok(cap)) = (env.get_direct_buffer_address(&buf), env.get_direct_buffer_capacity(&buf)) else { return JNI_FALSE }; + let (off, len) = (offset.max(0) as usize, size.max(0) as usize); + if ptr.is_null() || off + len > cap { + return JNI_FALSE; + } + // SAFETY: a direct buffer of `cap` bytes, valid until Share.kt releases + // it after this call returns; the range was checked above. + let bytes = unsafe { std::slice::from_raw_parts(ptr.add(off), len) }; + with(|s| { + if let Some(f) = s.asm.push(flags, bytes, pts_us, now_ms()) { + if let Some(tx) = &s.sink { + if tx.send(f).is_err() { + s.sink = None; + } + } + } + }); + if WANT_IDR.swap(false, Ordering::Relaxed) { JNI_TRUE } else { JNI_FALSE } + } + + /// Share.kt: 1 sharing at `width`x`height`, 0 stopped, -1 the person + /// declined, -2 capture failed. `dir` is the app's files folder. + #[no_mangle] + pub extern "system" fn Java_dev_dioxus_main_MullionNative_onShare(mut env: JNIEnv, _: JClass, state: jint, width: jint, height: jint, dir: JString) { + let dir: String = env.get_string(&dir).map(|s| s.into()).unwrap_or_default(); + match state { + 1 => { + let size = (width.max(0) as u32, height.max(0) as u32); + let (started, name) = with(|s| { + s.sharing = true; + s.size = size; + s.asm = Assembler::default(); + (s.host.is_some(), s.name.clone()) + }); + if !started { + match start_host(PathBuf::from(dir), size, name) { + Ok(h) => with(|s| s.host = Some(h)), + Err(e) => { + tracing::warn!("share: {e:#}"); + emit(json!({ "kind": "share", "state": "off", "error": format!("Sharing could not start: {e}") })); + set_share(false, String::new()); + return; + } + } + } + let address = with(|s| s.host.as_ref().map(|h| h.address.clone()).unwrap_or_default()); + emit(json!({ "kind": "share", "state": "on", "address": address, "width": size.0, "height": size.1 })); + } + _ => { + let shared = with(|s| { + s.sharing = false; + s.sink = None; + s.host.as_ref().map(|h| h.shared.clone()) + }); + if let Some(sh) = shared { + sh.0.lock().unwrap_or_else(|e| e.into_inner()).end_all(); + } + let error = match state { + -1 => Some("Sharing needs your OK. Tap Share this screen to ask again."), + s if s < 0 => Some("This tablet could not start sharing its screen."), + _ => None, + }; + emit(json!({ "kind": "share", "state": "off", "error": error })); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SPS_PPS: &[u8] = &[0, 0, 0, 1, 0x67, 0x42, 0xc0, 0x1f, 0, 0, 0, 1, 0x68, 0xce, 0x3c, 0x80]; + const IDR: &[u8] = &[0, 0, 0, 1, 0x65, 0x88, 0x84]; + const P: &[u8] = &[0, 0, 0, 1, 0x41, 0x9a, 0x02]; + + #[test] + fn keeps_sps_pps_and_puts_them_in_front_of_every_idr() { + let mut a = Assembler::default(); + assert!(a.push(FLAG_CODEC_CONFIG, SPS_PPS, 0, 0.0).is_none()); + let k = a.push(FLAG_KEY_FRAME, IDR, 1_000_000, 0.0).unwrap(); + assert!(k.idr); + assert_eq!(k.data, [SPS_PPS, IDR].concat()); + assert_eq!(k.rtp_time_90k, 90_000); + let p = a.push(0, P, 1_033_333, 0.0).unwrap(); + assert!(!p.idr); + assert_eq!(p.data, P); + assert_eq!(p.rtp_time_90k, 92_999); + assert_eq!((k.seq, p.seq), (1, 2)); + let au = mullion_proto::h264::inspect_annex_b(&k.data); + assert!(au.has_sps && au.has_pps && au.is_idr, "{au:?}"); + } + + #[test] + fn an_idr_that_already_carries_sps_is_left_alone() { + let mut a = Assembler::default(); + a.push(FLAG_CODEC_CONFIG, SPS_PPS, 0, 0.0); + let with_sps = [SPS_PPS, IDR].concat(); + assert_eq!(a.push(FLAG_KEY_FRAME | 8, &with_sps, 0, 0.0).unwrap().data, with_sps); + } +} diff --git a/crates/host/src/signaling.rs b/crates/host/src/signaling.rs index 8df5460..b7fafde 100644 --- a/crates/host/src/signaling.rs +++ b/crates/host/src/signaling.rs @@ -117,6 +117,7 @@ fn platform_name() -> &'static str { "macos" => "macOS", "windows" => "Windows", "linux" => "Linux", + "android" => "Android", other => other, } } diff --git a/crates/proto/src/nearby.rs b/crates/proto/src/nearby.rs index 2cd7e1c..0932d87 100644 --- a/crates/proto/src/nearby.rs +++ b/crates/proto/src/nearby.rs @@ -78,7 +78,11 @@ pub fn hello(ip: Ipv4Addr, port: u16) -> Option { let mut s = TcpStream::connect_timeout(&SocketAddr::from((ip, port)), CONNECT_TIMEOUT).ok()?; s.set_read_timeout(Some(READ_TIMEOUT)).ok()?; s.set_write_timeout(Some(READ_TIMEOUT)).ok()?; - write!(s, "GET /hello HTTP/1.0\r\nHost: {ip}:{port}\r\nConnection: close\r\n\r\n").ok()?; + // One write: `write!` on the stream sends each formatted piece on its own, + // and a listener that reads once and closes then resets the connection, + // which loses its reply. + let req = format!("GET /hello HTTP/1.0\r\nHost: {ip}:{port}\r\nConnection: close\r\n\r\n"); + s.write_all(req.as_bytes()).ok()?; // Up to 64 KiB, until the host closes or goes quiet. let mut buf = Vec::new(); let _ = s.take(64 * 1024).read_to_end(&mut buf); @@ -105,8 +109,16 @@ mod tests { let port = l.local_addr().unwrap().port(); std::thread::spawn(move || { let (mut c, _) = l.accept().unwrap(); - let mut req = [0u8; 1024]; - let _ = c.read(&mut req); + // Read the whole request before answering: closing with some of it + // unread resets the connection and the client loses the reply. + let mut req = Vec::new(); + let mut chunk = [0u8; 1024]; + while !req.windows(4).any(|w| w == b"\r\n\r\n") { + match c.read(&mut chunk) { + Ok(0) | Err(_) => break, + Ok(n) => req.extend_from_slice(&chunk[..n]), + } + } c.write_all(response.as_bytes()).unwrap(); }); port diff --git a/docs/evidence/share/README.md b/docs/evidence/share/README.md new file mode 100644 index 0000000..29259fd --- /dev/null +++ b/docs/evidence/share/README.md @@ -0,0 +1,35 @@ +# Share this screen evidence + +Captured on 2026-11-12 in an Android 15 emulator (arm64) on the Mac, with this branch's APK. + +| File | What it shows | +|---|---| +| `tablet-sharing.png` | After Android's consent, the app shows what to do on the Mac and the address to enter; "Stop sharing" ends it. Android's cast icon is in the status bar. | +| `tablet-notification.png` | The foreground service's notification, "Mullion is sharing this screen", which Android requires for screen capture. | +| `tablet-host-log.txt` | The tablet's host: `/hello` says Android and Mirror only. Pairing, then a receiver's offer is answered, and ICE, DTLS and the data channel come up. The receiver decodes 1072×1920 frames. After Stop sharing, offers are refused. | + +**What the emulator can't show:** a Mac viewing the tablet. The Mac can't reach the emulator's UDP ports, so the receiver here is the app's own page, connected over loopback. Decoding its own screen in software is also what eventually runs the emulator's WebView out of memory. On real devices the Mac decodes, and the tablet only encodes in hardware. + +## Update prompt and full screen + +| File | What it shows | +|---|---| +| `app-update-prompt.png` | A build stamped `0.1.0-beta.14` asks on start: "Mullion 0.1.0-beta.19 is out. You have 0.1.0-beta.14", with **Later** and **Update**. Update opened Chrome with the APK's github.com URL (logcat: `START u0 {act=android.intent.action.VIEW dat=https://github.com/... cmp=com.android.chrome/...}` from Mullion's uid). | +| `android-fullscreen.png` | Full screen on Android hides the status and navigation bars. The page grows from 412×684 to 412×732 CSS px (the whole 1080×1920 screen) and goes back on exit. | + +The Mac's host name in Nearby is replaced with `[Mac name]`. Windows full screen was not run here; there's no Windows machine. + +## Icons, responsive layout and dark mode + +| File | What it shows | +|---|---| +| `theme-light.png`, `theme-dark.png` | The colour switch in the footer: **Auto** (follows the system), **Light**, **Dark**, remembered on the device. In dark, raised surfaces (host rows, inputs) are lighter than the page (#171A1E on #0F1113). 390×844, touch. | +| `android-dark.png` | The Android app with the system in dark mode, on Auto. The app's theme is now DayNight, so its web view reports dark. | + +Checked with Playwright at 320×640, 360×740, 740×360, 820×1180 and 1280×800, in light and dark: +- no horizontal scrolling; +- the setup screen scrolls instead of clipping on a phone in landscape; +- the footer never covers the card; +- on touch screens every button and link is at least 44×44 px. + +The Mac's host name is replaced with `[Mac name]`. diff --git a/docs/evidence/share/android-dark.png b/docs/evidence/share/android-dark.png new file mode 100644 index 0000000..8de0a92 Binary files /dev/null and b/docs/evidence/share/android-dark.png differ diff --git a/docs/evidence/share/android-fullscreen.png b/docs/evidence/share/android-fullscreen.png new file mode 100644 index 0000000..48ff787 Binary files /dev/null and b/docs/evidence/share/android-fullscreen.png differ diff --git a/docs/evidence/share/app-update-prompt.png b/docs/evidence/share/app-update-prompt.png new file mode 100644 index 0000000..fb5c390 Binary files /dev/null and b/docs/evidence/share/app-update-prompt.png differ diff --git a/docs/evidence/share/tablet-host-log.txt b/docs/evidence/share/tablet-host-log.txt new file mode 100644 index 0000000..f74c6f6 --- /dev/null +++ b/docs/evidence/share/tablet-host-log.txt @@ -0,0 +1,28 @@ +# Android 15 emulator (arm64, 6 GB), this branch's APK. The app's own receiver connects to the +# tablet's host over loopback (127.0.0.1:47100), the only path a receiver has into an emulator. +# /hello on the tablet (adb forward): +{"app":"mullion","name":"Android tablet","version":"0.1.0","platform":"Android","port":47100,"ips":["10.0.2.16","10.0.2.15"],"extend":false,"receivers":0,"host_id":"0a2fed73…"} + +# Encoder (logcat): c2.android.avc.encoder at 1072x1920, level 41, no B-frames; SPS 67 42 c0 29 = Constrained Baseline 4.1 + +# Host log (logcat, RustStdoutStderr): +2026-11-11T19:24:00.592651Z INFO mullion_host::signaling: offer from 127.0.0.1:49212 answered (Mirror) +2026-11-11T19:24:00.603231Z INFO mullion_host::session: #1 ice: Checking +2026-11-11T19:24:00.663609Z INFO mullion_host::session: #1 ice: Completed +2026-11-11T19:24:00.671930Z INFO mullion_host::session: #1 dtls connected +2026-11-11T19:24:00.671949Z INFO mullion_host::session: #1 media added: mid=0 kind=Video dir=SendOnly +2026-11-11T19:24:00.691357Z INFO mullion_host::session: #1 data channel open: probe +2026-11-11T19:24:00.691515Z INFO mullion_host::session: #1 receiver: jitterBufferTarget supported=true value=Some(0.0) ua=…Android 15… +2026-11-11T19:24:51.725851Z INFO mullion_host::session: WebRTC media on UDP 10.0.2.15:33062, 10.0.2.16:40905, 127.0.0.1:45173 + +# Earlier run (first pairing of this receiver): +INFO mullion_host::pairing: pairing requested by Loopback test +INFO mullion_host::pairing: paired Loopback test + +# Receiver (page) 6 s in: mullion.stats().status = "streaming", video 1072x1920, 36 frames decoded; +# share sheet: "1 device is watching." +# Then the emulator's WebView renderer ran out of memory (mmap failed) decoding, in software, a stream of +# its own screen. A real setup decodes on the Mac. + +# Stop sharing: the service ends; the host stays up and refuses offers: +{"error":"Pair this device with the tablet first.","pair":true} diff --git a/docs/evidence/share/tablet-notification.png b/docs/evidence/share/tablet-notification.png new file mode 100644 index 0000000..7c8e048 Binary files /dev/null and b/docs/evidence/share/tablet-notification.png differ diff --git a/docs/evidence/share/tablet-sharing.png b/docs/evidence/share/tablet-sharing.png new file mode 100644 index 0000000..ade4c45 Binary files /dev/null and b/docs/evidence/share/tablet-sharing.png differ diff --git a/docs/evidence/share/theme-dark.png b/docs/evidence/share/theme-dark.png new file mode 100644 index 0000000..9438438 Binary files /dev/null and b/docs/evidence/share/theme-dark.png differ diff --git a/docs/evidence/share/theme-light.png b/docs/evidence/share/theme-light.png new file mode 100644 index 0000000..a628576 Binary files /dev/null and b/docs/evidence/share/theme-light.png differ diff --git a/tools/build-android.sh b/tools/build-android.sh index 1077eb2..87234bd 100755 --- a/tools/build-android.sh +++ b/tools/build-android.sh @@ -1,18 +1,21 @@ #!/usr/bin/env bash # Build the Mullion tablet APK (arm64, debug-signed) into dist/. -# dx 0.7.10 names the app "MullionApp", gives it Android's template icon, and -# generates a network_security_config that only allows cleartext to 127.0.0.1; -# PoC 1 signaling is plain HTTP on the LAN (SRS A-12). All three are replaced -# and Gradle re-run before copying the APK out. +# dx 0.7.10 names the app "MullionApp", gives it Android's template icon, +# generates a network_security_config that only allows cleartext to 127.0.0.1 +# (PoC 1 signaling is plain HTTP on the LAN, SRS A-12), and has no screen +# sharing. All are replaced or added, and Gradle re-run before copying the APK out. set -euo pipefail cd "$(dirname "$0")/.." export ANDROID_HOME="${ANDROID_HOME:-/opt/homebrew/share/android-commandlinetools}" export ANDROID_NDK_HOME="${ANDROID_NDK_HOME:-$ANDROID_HOME/ndk/$(ls "$ANDROID_HOME/ndk" | sort -V | tail -1)}" export JAVA_HOME="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home}" +APP=target/dx/mullion-app/release/android/app +# A rerun: dx writes its template icons (.webp) next to the last build's +# Mullion icons (.png) and Gradle refuses the duplicates. Take ours out first. +rm -f "$APP"/app/src/main/res/mipmap-*/ic_launcher*.png (cd crates/app && dx build --platform android --release --features mobile --no-default-features --target aarch64-linux-android) -APP=target/dx/mullion-app/release/android/app cat > "$APP/app/src/main/res/xml/network_security_config.xml" <<'EOF' @@ -24,12 +27,34 @@ EOF # Mullion's (crates/app/android/res, from tools/make-icons.py --android). rm -f "$APP"/app/src/main/res/mipmap-*/ic_launcher.webp "$APP"/app/src/main/res/mipmap-*/ic_launcher_round.webp cp -R crates/app/android/res/. "$APP/app/src/main/res/" +# Dark mode: dx's theme is Theme.AppCompat.Light, and Android's web view +# reports prefers-color-scheme from the app's theme, so the page never went +# dark. DayNight follows the system. +cat > "$APP/app/src/main/res/values/styles.xml" <<'XML' + +