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
4 changes: 2 additions & 2 deletions android/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ android {
applicationId = "org.moveweight.cartridge"
minSdk = 24
targetSdk = 35
versionCode = 31
versionName = "0.31.0"
versionCode = 32
versionName = "0.31.1"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
Expand Down
4 changes: 2 additions & 2 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="sensorLandscape"
android:configChanges="orientation|screenSize|screenLayout|keyboard|keyboardHidden|navigation">
android:screenOrientation="unspecified"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
Expand Down
168 changes: 95 additions & 73 deletions android/app/src/main/java/org/moveweight/cartridge/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@ import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.net.http.SslError
import android.os.Bundle
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.webkit.JavascriptInterface
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat

class MainActivity : AppCompatActivity() {

Expand All @@ -27,13 +29,26 @@ class MainActivity : AppCompatActivity() {
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
hideSystemUI()
// Must set content view BEFORE touching WindowInsetsController, or PhoneWindow.mDecor
// is null on Android 11+ (API 30+) and throws NullPointerException on launch.
setContentView(R.layout.activity_main)
hideSystemUI()

webView = findViewById(R.id.webview)
setupWebView()

// Load bundled Cartridge frontend by default so setup, pairing, and library browsing work out of the box
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
webView.evaluateJavascript(
"(function(){ if (window.GP && window.GP.triggerUI) { window.GP.triggerUI('b'); return true; } return false; })()"
) { handled ->
if (handled != "true" && webView.canGoBack()) {
webView.goBack()
}
}
}
})

val prefs = getSharedPreferences("cartridge_prefs", Context.MODE_PRIVATE)
val startUrl = prefs.getString("server_url", null)?.takeIf { it.isNotBlank() }
?: "file:///android_asset/web/index.html"
Expand All @@ -44,32 +59,29 @@ class MainActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
hideSystemUI()
webView.onResume()
if (::webView.isInitialized) {
webView.onResume()
}
}

override fun onPause() {
if (::webView.isInitialized) {
webView.onPause()
}
super.onPause()
webView.onPause()
}

private fun hideSystemUI() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.setDecorFitsSystemWindows(false)
window.insetsController?.let { controller ->
controller.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
window?.decorView?.post {
try {
WindowCompat.setDecorFitsSystemWindows(window, false)
val controller = WindowInsetsControllerCompat(window, window.decorView)
controller.hide(WindowInsetsCompat.Type.systemBars())
controller.systemBarsBehavior =
WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
} catch (_: Throwable) {
// Never crash if an OEM window manager rejects immersive flags during transition
}
} else {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
)
}
}

Expand All @@ -86,6 +98,7 @@ class MainActivity : AppCompatActivity() {
settings.allowFileAccessFromFileURLs = true
@Suppress("DEPRECATION")
settings.allowUniversalAccessFromFileURLs = true
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
settings.useWideViewPort = true
settings.loadWithOverviewMode = true

Expand All @@ -104,13 +117,22 @@ class MainActivity : AppCompatActivity() {
return false
}

@SuppressLint("WebViewClientOnReceivedSslError")
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
val prefs = getSharedPreferences("cartridge_prefs", Context.MODE_PRIVATE)
if (prefs.getBoolean("insecure_certs", false)) {
handler?.proceed()
} else {
super.onReceivedSslError(view, handler, error)
}
}

override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
// Inject platform identity
view?.evaluateJavascript(
"window.__CARTRIDGE_PLATFORM = 'android'; window.__CARTRIDGE_NATIVE = true; window.__CARTRIDGE_VERSION = '0.31.0'; " +
"if (document.title === 'Cartridge for Xbox') { document.title = 'Cartridge for Android'; " +
"const h1 = document.querySelector('#view-setup h1'); if (h1) h1.textContent = 'Cartridge for Android'; }",
"window.__CARTRIDGE_PLATFORM = 'android'; window.__CARTRIDGE_NATIVE = true; window.__CARTRIDGE_VERSION = '0.31.1'; " +
"if (document.title === 'Cartridge for Xbox') { document.title = 'Cartridge'; " +
"const h1 = document.querySelector('#view-setup h1'); if (h1) h1.textContent = 'Cartridge'; }",
null
)
}
Expand All @@ -129,70 +151,59 @@ class MainActivity : AppCompatActivity() {
}

override fun dispatchKeyEvent(event: KeyEvent): Boolean {
// Forward gamepad keys directly to WebView
val keyCode = event.keyCode
val action = event.action

when (keyCode) {
KeyEvent.KEYCODE_BUTTON_A,
KeyEvent.KEYCODE_BUTTON_B,
KeyEvent.KEYCODE_BUTTON_X,
KeyEvent.KEYCODE_BUTTON_Y,
KeyEvent.KEYCODE_BUTTON_L1,
KeyEvent.KEYCODE_BUTTON_R1,
KeyEvent.KEYCODE_BUTTON_L2,
KeyEvent.KEYCODE_BUTTON_R2,
KeyEvent.KEYCODE_BUTTON_START,
KeyEvent.KEYCODE_BUTTON_SELECT,
KeyEvent.KEYCODE_DPAD_UP,
KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT -> {
val jsKey = mapKeyCodeToJsKey(keyCode)
val isDown = (action == KeyEvent.ACTION_DOWN)
if (jsKey != null) {
webView.evaluateJavascript(
"if (window.dispatchEvent) { window.dispatchEvent(new CustomEvent('cartridge_gamepad_key', { detail: { key: '$jsKey', down: $isDown } })); }",
null
)
}
val jsKey = mapKeyCodeToJsKey(keyCode)
if (jsKey != null && (action == KeyEvent.ACTION_DOWN || action == KeyEvent.ACTION_UP)) {
val isDown = (action == KeyEvent.ACTION_DOWN)
if (isDown && event.repeatCount == 0) {
webView.evaluateJavascript(
"if (window.GP && window.GP.triggerUI) window.GP.triggerUI('$jsKey');",
null
)
}
webView.evaluateJavascript(
"if (window.dispatchEvent) { window.dispatchEvent(new CustomEvent('cartridge_gamepad_key', { detail: { key: '$jsKey', down: $isDown } })); }",
null
)
return true
}
return super.dispatchKeyEvent(event)
}

override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
// Handle analog sticks and trigger axes
val lx = event.getAxisValue(MotionEvent.AXIS_X)
val ly = event.getAxisValue(MotionEvent.AXIS_Y)
val rx = event.getAxisValue(MotionEvent.AXIS_Z)
val ry = event.getAxisValue(MotionEvent.AXIS_RZ)
val lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER)
val rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER)

webView.evaluateJavascript(
"if (window.dispatchEvent) { window.dispatchEvent(new CustomEvent('cartridge_gamepad_axes', { detail: { lx: $lx, ly: $ly, rx: $rx, ry: $ry, lt: $lt, rt: $rt } })); }",
null
)
if (::webView.isInitialized) {
webView.evaluateJavascript(
"if (window.dispatchEvent) { window.dispatchEvent(new CustomEvent('cartridge_gamepad_axes', { detail: { lx: $lx, ly: $ly, rx: $rx, ry: $ry, lt: $lt, rt: $rt } })); }",
null
)
}
return super.dispatchGenericMotionEvent(event)
}

private fun mapKeyCodeToJsKey(keyCode: Int): String? {
return when (keyCode) {
KeyEvent.KEYCODE_BUTTON_A -> "A"
KeyEvent.KEYCODE_BUTTON_B -> "B"
KeyEvent.KEYCODE_BUTTON_X -> "X"
KeyEvent.KEYCODE_BUTTON_Y -> "Y"
KeyEvent.KEYCODE_BUTTON_L1 -> "LB"
KeyEvent.KEYCODE_BUTTON_R1 -> "RB"
KeyEvent.KEYCODE_BUTTON_L2 -> "LT"
KeyEvent.KEYCODE_BUTTON_R2 -> "RT"
KeyEvent.KEYCODE_BUTTON_START -> "Start"
KeyEvent.KEYCODE_BUTTON_SELECT -> "Select"
KeyEvent.KEYCODE_DPAD_UP -> "Up"
KeyEvent.KEYCODE_DPAD_DOWN -> "Down"
KeyEvent.KEYCODE_DPAD_LEFT -> "Left"
KeyEvent.KEYCODE_DPAD_RIGHT -> "Right"
KeyEvent.KEYCODE_BUTTON_A -> "a"
KeyEvent.KEYCODE_BUTTON_B -> "b"
KeyEvent.KEYCODE_BUTTON_X -> "x"
KeyEvent.KEYCODE_BUTTON_Y -> "y"
KeyEvent.KEYCODE_BUTTON_L1 -> "l1"
KeyEvent.KEYCODE_BUTTON_R1 -> "r1"
KeyEvent.KEYCODE_BUTTON_L2 -> "l2"
KeyEvent.KEYCODE_BUTTON_R2 -> "r2"
KeyEvent.KEYCODE_BUTTON_START -> "start"
KeyEvent.KEYCODE_BUTTON_SELECT -> "select"
KeyEvent.KEYCODE_DPAD_UP -> "up"
KeyEvent.KEYCODE_DPAD_DOWN -> "down"
KeyEvent.KEYCODE_DPAD_LEFT -> "left"
KeyEvent.KEYCODE_DPAD_RIGHT -> "right"
else -> null
}
}
Expand All @@ -202,7 +213,18 @@ class MainActivity : AppCompatActivity() {
fun getPlatform(): String = "android"

@JavascriptInterface
fun getVersion(): String = "1.0.0"
fun getVersion(): String = "0.31.1"

@JavascriptInterface
fun setInsecureCerts(enabled: Boolean) {
val prefs = getSharedPreferences("cartridge_prefs", Context.MODE_PRIVATE)
prefs.edit().putBoolean("insecure_certs", enabled).apply()
}

@JavascriptInterface
fun exitApp() {
runOnUiThread { finish() }
}

@JavascriptInterface
fun launchExternalEmulator(packageName: String, uriString: String, mimeType: String?): Boolean {
Expand All @@ -214,7 +236,7 @@ class MainActivity : AppCompatActivity() {
}
startActivity(intent)
true
} catch (e: Exception) {
} catch (_: Exception) {
false
}
}
Expand Down
3 changes: 3 additions & 0 deletions android/tests/validate_android.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,8 @@
assert "CartridgeNativeBridge" in content, "Bridge missing"
assert "mapKeyCodeToJsKey" in content, "Gamepad mapper missing"
assert "launchExternalEmulator" in content, "Emulator launcher missing"
assert content.index("setContentView(R.layout.activity_main)") < content.index("hideSystemUI()"), (
"setContentView must run before hideSystemUI() to avoid NullPointerException on Android 11+ PhoneWindow.mDecor"
)

print("Cartridge Android project verified successfully.")
20 changes: 20 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ function renderSetup(status) {
const d = document.createElement('div');
d.className = 'opt' + (i === setupIdx ? ' focus' : '');
d.innerHTML = `<b>${it.label}</b><span class="dim">${it.sub || ''}</span>`;
d.onclick = () => { setupIdx = i; renderSetup(); it.go(); };
opts.appendChild(d);
});
}
Expand Down Expand Up @@ -267,11 +268,19 @@ function setupItems() {
// browser setInsecure is a no-op and there is no bypass to grant —
// the browser's own trust store is the only answer there.
if (HOST.present) HOST.setInsecure(CFG.insecureCerts);
if (typeof window !== 'undefined' && window.CartridgeNative && window.CartridgeNative.setInsecureCerts) {
window.CartridgeNative.setInsecureCerts(CFG.insecureCerts);
}
renderSetup(CFG.insecureCerts
? 'Invalid certificates accepted — retry connecting.'
: 'Certificate checking is back on.');
},
});
items.push({
label: 'Diagnostics',
sub: 'check server connection, controller and build info',
go: () => { show('diag'); renderDiag(''); },
});
if (CFG.server) items.push({ label: 'Continue', sub: 'sign in to ' + CFG.server,
go: () => enterAuth() });
return items;
Expand Down Expand Up @@ -591,6 +600,10 @@ function setupInput(btn) {
// Settings reached from the library: go back. Otherwise this is the root,
// and back should leave the app rather than do nothing.
if (CFG.server && CFG.token) return enterLibrary();
if (typeof window !== 'undefined' && window.CartridgeNative && window.CartridgeNative.exitApp) {
window.CartridgeNative.exitApp();
return;
}
// In a browser there is nothing to exit — closing the tab is the user's job.
HOST.exit();
return;
Expand Down Expand Up @@ -629,8 +642,11 @@ function renderAuth(status) {
const d = document.createElement('div');
d.className = 'tab' + (i === authIdx ? ' current' : '');
d.textContent = t;
d.onclick = () => { authIdx = i; renderAuth(''); };
tabs.appendChild(d);
});
const credsCta = document.querySelector('#auth-creds .cta');
if (credsCta) credsCta.onclick = () => askCredentials();
$('auth-pair').classList.toggle('hidden', authIdx !== 0);
$('auth-creds').classList.toggle('hidden', authIdx !== 1);
if (authIdx === 0) {
Expand All @@ -643,6 +659,7 @@ function renderAuth(status) {
const d = document.createElement('div');
d.className = 'key' + (i === padIdx ? ' focus' : '');
d.textContent = k;
d.onclick = () => { padIdx = i; authInput('a'); };
pad.appendChild(d);
});
}
Expand Down Expand Up @@ -902,6 +919,7 @@ function renderRail() {
const d = document.createElement('div');
d.className = 'plat' + (i === platIdx ? ' current' : '');
d.textContent = `${p.display_name || p.name || p.slug} (${p.rom_count})`;
d.onclick = () => { platIdx = i; loadGames(); };
rail.appendChild(d);
});
const cur = rail.children[platIdx];
Expand All @@ -914,6 +932,7 @@ function renderGrid() {
games.forEach((g, i) => {
const t = document.createElement('div');
t.className = 'tile' + (i === gameIdx ? ' focus' : '');
t.onclick = () => { gameIdx = i; renderGrid(); startGame(g); };
const cover = ROMM.coverUrl(g);
if (cover) {
const img = document.createElement('img');
Expand Down Expand Up @@ -1229,6 +1248,7 @@ GP.onRaw((btn, pressed) => {
// project ships) can be offered as a one-press choice instead of typing a URL.
let sameOriginServer = '';
async function detectSameOrigin() {
if (!location.origin || location.origin === 'null' || location.protocol === 'file:') return '';
for (const suffix of ['/romm', '']) {
try {
const r = await fetch(location.origin + suffix + '/api/heartbeat');
Expand Down
2 changes: 2 additions & 0 deletions gamepad.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ const GP = (() => {

return {
onUI(fn) { uiHandler = fn; },
triggerUI(btn) { if (uiHandler) uiHandler(btn); },
onRaw(fn) { rawHandler = fn; },
// Pass null to stop reporting; the stream view turns this on only while it
// is on screen.
Expand All @@ -118,3 +119,4 @@ const GP = (() => {
get usingHost() { return !!hostState; },
};
})();
if (typeof window !== 'undefined') window.GP = GP;
Loading
Loading