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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/release-beta.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 6 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions crates/app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
70 changes: 70 additions & 0 deletions crates/app/android/kotlin/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -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
}
}
191 changes: 191 additions & 0 deletions crates/app/android/kotlin/Share.kt
Original file line number Diff line number Diff line change
@@ -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<Intent>("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) {}

Check failure on line 111 in crates/app/android/kotlin/Share.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Add a nested comment explaining why this function is empty or complete the implementation.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHMPdCahp_XmauBSM0G&open=AaHMPdCahp_XmauBSM0G&pullRequest=24
override fun onOutputFormatChanged(c: MediaCodec, f: MediaFormat) {}

Check failure on line 112 in crates/app/android/kotlin/Share.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Add a nested comment explaining why this function is empty or complete the implementation.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHMPdCahp_XmauBSM0H&open=AaHMPdCahp_XmauBSM0H&pullRequest=24
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) {}

Check warning on line 168 in crates/app/android/kotlin/Share.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Either remove or fill this block of code.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHMPdCZhp_XmauBSM0C&open=AaHMPdCZhp_XmauBSM0C&pullRequest=24
try { codec?.stop() } catch (_: Exception) {}

Check warning on line 169 in crates/app/android/kotlin/Share.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Either remove or fill this block of code.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHMPdCahp_XmauBSM0D&open=AaHMPdCahp_XmauBSM0D&pullRequest=24
try { codec?.release() } catch (_: Exception) {}

Check warning on line 170 in crates/app/android/kotlin/Share.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Either remove or fill this block of code.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHMPdCahp_XmauBSM0E&open=AaHMPdCahp_XmauBSM0E&pullRequest=24
val p = projection
display = null; codec = null; projection = null
try { p?.stop() } catch (_: Exception) {}

Check warning on line 173 in crates/app/android/kotlin/Share.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Either remove or fill this block of code.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHMPdCahp_XmauBSM0F&open=AaHMPdCahp_XmauBSM0F&pullRequest=24
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
}
}
15 changes: 9 additions & 6 deletions crates/app/assets/pair.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// (window.MullionNoble) because a page served over http://<LAN IP> 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
Expand Down Expand Up @@ -106,10 +106,13 @@
// First connection to a host: ask it to show a code, ask the person for it,
// 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) {

Check failure on line 109 in crates/app/assets/pair.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 24 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHMPdCThp_XmauBSM0B&open=AaHMPdCThp_XmauBSM0B&pullRequest=24
// 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 (;;) {
Expand All @@ -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);
Expand Down
Loading
Loading