diff --git a/.github/scripts/android-smoke.sh b/.github/scripts/android-smoke.sh new file mode 100755 index 00000000..0c88e41a --- /dev/null +++ b/.github/scripts/android-smoke.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Installs the test APK on the emulator, opens it, and prints small screenshots (base64 JPEG +# between markers) and the app's log lines, so the run's log shows how it started. +set -u +# Every adb call has a time limit, so a stuck emulator ends the check instead of the whole job. +a() { timeout 60 adb "$@"; } +command -v convert >/dev/null || sudo apt-get install -y -q imagemagick >/dev/null +apk=$(find src-tauri/gen/android/app/build/outputs/apk -name '*.apk' | head -1) +echo "APK: $apk" +a install -r "$apk" +# Let Google Play services finish starting first: when it restarts during our start-up, Android +# also closes apps that use its fonts. +sleep 60 +a logcat -c +# The log is kept on this machine as it comes, so it's there even if the emulator stops. +adb logcat -v time > logcat.txt 2>&1 & +# Shut any system dialog left from the emulator's start ("isn't responding"). +a shell am broadcast -a android.intent.action.CLOSE_SYSTEM_DIALOGS >/dev/null +a shell am start -n com.recomplauncher.app/.MainActivity +shot() { + a exec-out screencap -p > "shot-$1.png" || return 1 + convert "shot-$1.png" -resize 960x -quality 60 "shot-$1.jpg" || return 1 + echo "=====SHOT $1 BEGIN=====" + base64 -w0 "shot-$1.jpg" + echo + echo "=====SHOT $1 END=====" +} +for n in 1 2 3 4; do + sleep 15 + shot "$n" || { echo "Emulator stopped answering after shot $((n - 1))."; break; } +done +echo "=====LOG BEGIN=====" +grep -iE 'recomplauncher|RustStdoutStderr|chromium|Tauri|AndroidRuntime|FATAL|ActivityManager|lowmemory' logcat.txt | tail -400 +echo "=====LOG END=====" diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 7b48c381..b4a395a6 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -11,6 +11,7 @@ on: - src-tauri/gen/android/** - src-tauri/src/mobile.rs - src-tauri/src/*_mobile.rs + - .github/scripts/android-smoke.sh permissions: contents: read @@ -55,7 +56,7 @@ jobs: run: | export NDK_HOME="${ANDROID_NDK_LATEST_HOME:-$ANDROID_NDK_HOME}" echo "NDK: $NDK_HOME" - npx tauri android build --debug --apk --target aarch64 + npx tauri android build --debug --apk --target aarch64 --target x86_64 - uses: actions/upload-artifact@v5 with: @@ -63,3 +64,23 @@ jobs: path: src-tauri/gen/android/app/build/outputs/apk/**/*.apk retention-days: 1 if-no-files-found: error + + # Opens the APK on an Android emulator and prints two small screenshots and the app's log into + # this job's log, so a build can be checked without a phone. + - name: Enable KVM for the emulator + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - name: Open it on an emulator + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 34 + arch: x86_64 + target: google_apis + profile: pixel_6 + ram-size: 4096M + emulator-options: -no-window -gpu guest -noaudio -no-boot-anim -no-snapshot + disable-animations: true + script: bash .github/scripts/android-smoke.sh diff --git a/docs/BUILDING.md b/docs/BUILDING.md index dd75d323..d8625251 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -158,8 +158,15 @@ export ANDROID_HOME= NDK_HOME=$ANDROID_HOME/ndk/ npx tauri android build --debug --apk --target aarch64 ``` +On Android the launcher is always in Big Picture mode, held sideways: there's no desktop view to +leave for, and Settings leaves out what only a PC has (monitor, tray, start with your PC, Discord, +controller as a mouse). A finger drags a page or a row of games, a tap opens, and Android's Back is +B. On a phone, Auto size draws the stage a little bigger (1600×900) so words stay readable. + The Android workflow (`.github/workflows/android.yml`) builds the same APK on GitHub when the -Android parts change, or when run by hand, and keeps it for a day. +Android parts change, or when run by hand, and keeps it for a day. It also opens the APK on an +Android emulator and prints two small screenshots (base64 JPEG between `=====SHOT` lines) and +the app's log into the job's log (`.github/scripts/android-smoke.sh`). ## Pull request builds diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 91659c55..3c9fdbc8 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -45,6 +45,9 @@ fn main() { } if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") { empty_pthread(); + // unrar is C++ built against the NDK's libc++, which Android doesn't have on the phone: + // it goes into the launcher's library, or the app stops at start (length_error not found). + android_cxx(); } tauri_build::build() } @@ -73,6 +76,21 @@ fn empty_pthread() { } } +/// Links the NDK's static libc++ (and libc++abi), found where the NDK's own clang keeps them. +fn android_cxx() { + let cc = cc::Build::new().get_compiler(); + let out = std::process::Command::new(cc.path()).arg("-print-file-name=libc++_static.a").output(); + let path = out.ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()); + let Some(dir) = path.as_deref().map(std::path::Path::new).filter(|p| p.is_file()).and_then(|p| p.parent()) else { + println!("cargo:warning=the NDK's libc++_static.a wasn't found; the app may stop at start"); + return; + }; + // Handed to the linker as files (not as static libraries Rust bundles into the rlib, which + // brings in Rust's own runtime a second time: rust_eh_personality defined twice). + println!("cargo:rustc-link-arg={}", dir.join("libc++_static.a").display()); + println!("cargo:rustc-link-arg={}", dir.join("libc++abi.a").display()); +} + /// unrar_sys's C++ sources, in Cargo's download folder. fn unrar_src() -> Option { let home = std::env::var_os("CARGO_HOME").map(std::path::PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".cargo")))?; diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index c93d3778..a5b2db72 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -24,6 +24,9 @@ "core:window:allow-is-fullscreen", "core:window:allow-hide", "core:window:allow-show", - "core:window:allow-set-focus" + "core:window:allow-set-focus", + "core:app:allow-register-listener", + "core:app:allow-remove-listener", + "notification:default" ] } diff --git a/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/src-tauri/gen/android/app/src/main/AndroidManifest.xml index 6dba3e22..d332897a 100644 --- a/src-tauri/gen/android/app/src/main/AndroidManifest.xml +++ b/src-tauri/gen/android/app/src/main/AndroidManifest.xml @@ -13,6 +13,7 @@ diff --git a/src-tauri/src/assets.rs b/src-tauri/src/assets.rs index 3ec8312e..6d42033d 100644 --- a/src-tauri/src/assets.rs +++ b/src-tauri/src/assets.rs @@ -26,6 +26,9 @@ pub fn os_now() -> &'static str { "windows" } else if cfg!(target_os = "macos") { "macos" + } else if cfg!(target_os = "android") { + // Android games are APKs (assets.android in the Android catalog), never the Linux builds. + "android" } else { "linux" } diff --git a/tests/android-tv.test.cjs b/tests/android-tv.test.cjs new file mode 100644 index 00000000..b73a97c7 --- /dev/null +++ b/tests/android-tv.test.cjs @@ -0,0 +1,47 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const app = fs.readFileSync(path.join(__dirname, '../ui/app.js'), 'utf8'); +const tv = fs.readFileSync(path.join(__dirname, '../ui/tv.js'), 'utf8'); +const fn = (src, name, indent = '') => src.match(new RegExp(`^${indent}(?:async )?function ${name}\\([^]*?^${indent}}`, 'm'))[0]; + +function settingsContext(os) { + const c = vm.createContext({ + S: { os, settings: {}, libs: [], library: {}, owned: {}, steam: false }, + t: (s) => s, N_: (s) => s, tc: (s) => s, esc: String, + tf: (s, values) => s.replace(/\{(\w+)\}/g, (_, k) => values[k]), + backdrop: () => '', bar: () => '', region: (s) => s, pageHead: (s, sub) => `${s}|${sub}`, + homePinned: () => false, bgMode: () => '', langName: () => 'English', + svg: () => '', hints: () => '', HEART: '', clockRow: () => '', startAtLoginNote: () => '', + }); + c.window = c; + c.monitorPicked = () => ''; c.monitorName = () => ''; + vm.runInContext(fn(tv, 'pageSettings', ' '), c); + return c; +} + +test('Big Picture on Android leaves out the PC-only settings', () => { + const html = settingsContext('android').pageSettings(); + for (const gone of ['Leave Big Picture mode', 'Start in Big Picture mode', 'Close to tray', 'Discord status', 'Controller as a Mouse', 'Monitor']) { + assert.doesNotMatch(html, new RegExp(gone), gone); + } + assert.match(html, /Auto-Install/); +}); + +test('Big Picture on a PC keeps them', () => { + const html = settingsContext('windows').pageSettings(); + for (const kept of ['Leave Big Picture mode', 'Start in Big Picture mode', 'Close to tray', 'Discord status', 'Controller as a Mouse', 'Monitor']) { + assert.match(html, new RegExp(kept), kept); + } +}); + +test('Android always starts in Big Picture mode', () => { + const c = vm.createContext({ S: { os: 'android', settings: {}, desktopArg: true } }); + vm.runInContext(fn(app, 'startsInTV'), c); + assert.equal(c.startsInTV(), true); + c.S.os = 'windows'; + assert.equal(c.startsInTV(), false); +}); diff --git a/ui/app.js b/ui/app.js index d07bc4bf..05242849 100644 --- a/ui/app.js +++ b/ui/app.js @@ -13,7 +13,7 @@ function screenLabels(su) { } const GENRES = { action: N_('Action'), adventure: N_('Adventure'), platformer: N_('Platformers'), racing: N_('Racing'), fighting: N_('Fighting'), shooter: N_('Shooters'), sports: N_('Sports'), rpg: N_('RPG'), puzzle: N_('Puzzle') }; -const OS_NAME = { windows: 'Windows', macos: 'Mac', linux: 'Linux' }; +const OS_NAME = { windows: 'Windows', macos: 'Mac', linux: 'Linux', android: 'Android' }; // Text for searching: lower case and without accents, so "pokemon" finds Pokémon. const fold = (x) => String(x || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase(); // Search: accents folded and punctuation as spaces, so "sky racer", "skyracer" and "Sky-Racer!!" @@ -8292,7 +8292,8 @@ const selfAuto = () => !S.flatpak && !!(S.settings.ui || {}).self_auto_update; const ARROW_R = ''; // An update restart returns to the mode that was on screen. -function startsInTV() { return !S.desktopArg && !!(S.settings.start_in_tv || S.bigArg); } +// Android has no desktop view: it's always Big Picture mode. +function startsInTV() { return S.os === 'android' || (!S.desktopArg && !!(S.settings.start_in_tv || S.bigArg)); } // The update window at start: not during first-time setup, in Big Picture, with a game running // (started from a shortcut) or a window already open (a game link, a Set Up), and not for a @@ -10807,6 +10808,9 @@ T.event.listen('screenshot', ({ payload: p }) => { delete S.shots[p.id]; forgetL upd.finally(() => loadNews()); // The first time: the setup, like a new console. After that, TV mode if that's how they play. if (document.readyState === 'loading') await new Promise((ok) => addEventListener('DOMContentLoaded', ok, { once: true })); + // Android skips the desktop's first-time setup (folders, the PC's own options): Big Picture asks + // what it needs. + if (!S.settings.setup_done && S.os === 'android') await saveSettings({ setup_done: true, asked_location: true }, true); if (!S.settings.setup_done && window.firstRun) window.firstRun(); else if (window.startTV && startsInTV()) window.startTV(); else setTimeout(askData, 800); diff --git a/ui/tv.js b/ui/tv.js index 6e816475..f92d9030 100644 --- a/ui/tv.js +++ b/ui/tv.js @@ -21,6 +21,8 @@ return TABS.filter(([k]) => k === 'settings' || k === 'home' || k === 'library' || !hide.has(k)).sort((a, b) => rank(a[0]) - rank(b[0])); }; const SX = 96; // the side margin, in stage pixels + // Android: no desktop view to go back to, and no PC-only settings (see pageSettings). + const android = () => S.os === 'android'; const MARK = ''; const ICON = { plus: '', @@ -120,8 +122,12 @@ // ---------- the stage ---------- // A bigger stage makes everything smaller on screen. const SIZES = { small: [2400, 1350], medium: [2133, 1200], large: [1920, 1080] }; + // A phone held sideways is about 400 points tall: the TV stage would shrink its words to a few + // points, so Auto draws a little bigger there. + const PHONE = [1600, 900]; function stageSize() { let k = S.settings.tv_size; + if (!SIZES[k] && android() && Math.min(innerWidth, innerHeight) < 600) return PHONE; if (!SIZES[k]) { const w = screen.width * (devicePixelRatio || 1); k = w >= 3000 ? 'small' : w >= 2200 ? 'medium' : 'large'; } return SIZES[k]; } @@ -199,6 +205,7 @@ if (TV.on) return; TV.on = true; TV.booting = true; + hookAndroidBack(); TV.enteredAt = performance.now(); root.innerHTML = ''; root.hidden = false; @@ -217,6 +224,7 @@ boot(); } async function leave() { + if (android()) return; root.classList.add('tv-cover', 'out'); await wait(still() ? 0 : 220); TV.on = false; @@ -1386,18 +1394,20 @@ // Settings in groups, with the focused one shown large on the right (what it does, and its value). function pageSettings() { + // Android: no desktop view to leave for, and none of the PC-only settings. + const droid = S.os === 'android'; const sw = (k, label, sub, on = !!S.settings[k]) => ``; const size = { small: 'Smaller', medium: 'Medium', large: 'Larger' }[S.settings.tv_size] || 'Auto'; const head = (n) => `

${esc(n)}

`; return `${backdrop(null)}${bar()} - ${region(`${pageHead(t('Settings'), t('Folders, updates and the rest are in the desktop view.'))} + ${region(`${pageHead(t('Settings'), droid ? '' : t('Folders, updates and the rest are in the desktop view.'))}
${head(t('Account'))} ${S.account && S.account.signedIn ? `` : ``} ${head(t('Display'))} - ${(() => { + ${droid ? '' : (() => { const m = window.monitorPicked(S.monitors, S.settings.tv_monitor); const now = m ? window.monitorName(m) : t('Main Display'); return ``; @@ -1412,19 +1422,19 @@ ${clockRow()} ${S.noSound ? '' : sw('sounds', t('Sounds'), t('The start-up sound and a soft click as you move around'), S.settings.sounds !== false)} ${sw('pad_stick', t('Move with the left stick'), t('Turn it off if your stick drifts. The d-pad still works.'), S.settings.pad_stick !== false)} - ${sw('pad_desktop', t('Controller as a Mouse'), t('On: the desktop view ignores your controller\'s buttons, so a mouse mapping doesn\'t press things twice. Big Picture mode always uses the controller.'), S.settings.pad_desktop === false)} - ${head(t('Starting up'))} + ${droid ? '' : sw('pad_desktop', t('Controller as a Mouse'), t('On: the desktop view ignores your controller\'s buttons, so a mouse mapping doesn\'t press things twice. Big Picture mode always uses the controller.'), S.settings.pad_desktop === false)} + ${droid ? '' : `${head(t('Starting up'))} ${sw('start_in_tv', t('Start in Big Picture mode'), t('Open full screen, ready for a controller'))} ${S.canStartAtLogin ? sw('start_at_login', t('Start with your PC'), startAtLoginNote()) : ''} ${head(t('When you close the window'))} - ${sw('close_to_tray', t('Close to tray'), t('Keep RecompLauncher running when you close the window. Turn off to exit on close. Quit always exits.'))} + ${sw('close_to_tray', t('Close to tray'), t('Keep RecompLauncher running when you close the window. Turn off to exit on close. Quit always exits.'))}`} ${head(t('Games and updates'))} ${sw('notify', t('Notifications'), t('When a new recomp comes out for a game you own'))} ${sw('auto_update_all', t('Update All Games Automatically'), t('Every installed game takes a new release as soon as the launcher finds one'))} ${sw('backup_before_update', t('Back up saves before updates'), t('The newest five copies of each game\'s saves'))} ${sw('auto_install', t('Auto-Install'), t('Open a game\'s setup or installer as soon as it finishes downloading'), S.settings.auto_install !== false)} ${sw('hide_ai', t('Hide AI-assisted recomps'), t('They won\'t show in the Catalog'))} - ${sw('discord', t('Discord status'), t('Show the game you\'re playing on your Discord profile'), S.settings.discord !== false)} + ${droid ? '' : sw('discord', t('Discord status'), t('Show the game you\'re playing on your Discord profile'), S.settings.discord !== false)} ${(() => { const on = window.reviewAskOn ? window.reviewAskOn() : true; return ``; })()} ${S.steam ? sw('steam_sync', t('Keep Steam in Sync'), t('Installed games go in your Steam library, in a RecompLauncher collection, and leave it when you uninstall them')) : ''} ${S.steam && S.settings.steam_sync ? `` : ''} @@ -1434,8 +1444,8 @@ ${head(t('Controller'))} ${(() => { const g = (S.settings.ui || {}).tv_glyphs; const v = g === 'ps' ? 'PlayStation' : g === 'xbox' ? 'Xbox' : g === 'nintendo' ? 'Nintendo' : g === 'steam' ? 'Steam' : 'Automatic'; return ``; })()} - ${head(t('Big Picture mode'))} - + ${droid ? '' : `${head(t('Big Picture mode'))} + `} ${head(t('About'))} @@ -3080,8 +3090,8 @@ if (!b) { if (TV.view !== 'home') { TV.view = 'home'; TV.enter = 'back'; draw(); return; } // Back on Home: offer the way out, like Steam (B or Esc, then A). - return sheet(t('Leave Big Picture mode'), [ - { label: t('Leave Big Picture mode'), sub: t('Back to the desktop view, for mouse and keyboard'), icon: 'chevL', run: () => leave() }, + return sheet(android() ? t('Quit RecompLauncher') : t('Leave Big Picture mode'), [ + ...(android() ? [] : [{ label: t('Leave Big Picture mode'), sub: t('Back to the desktop view, for mouse and keyboard'), icon: 'chevL', run: () => leave() }]), { label: t('Quit RecompLauncher'), icon: 'close', run: () => invoke('quit_launcher').catch(fail) }, { label: t('Cancel'), icon: 'check', run: () => {} }, ]); @@ -3549,6 +3559,60 @@ activate(el); }); + // Touch screens (Android): drag a page up and down, or a row of games sideways, as the d-pad + // moves them. A tap is a click, so it picks and opens like a mouse; a drag never counts as one. + const touch = { at: null, dragEnd: 0 }; + const rowX = (r) => -new DOMMatrixReadOnly(getComputedStyle(r).transform).m41 || 0; + root.addEventListener('touchstart', (e) => { + if (e.touches.length !== 1 || TV.sheet) { touch.at = null; return; } + const p = e.touches[0]; + const row = e.target.closest('.tv-row'); + touch.at = { x: p.clientX, y: p.clientY, y0: TV.scrollY || 0, row, x0: row ? rowX(row) : 0, axis: '' }; + root.classList.remove('mouse-off'); + }, { passive: true }); + root.addEventListener('touchmove', (e) => { + const at = touch.at; + if (!at || TV.sheet) return; + const p = e.touches[0]; + const k = TV.k || 1; + const dx = (p.clientX - at.x) / k, dy = (p.clientY - at.y) / k; + if (!at.axis) { + if (Math.abs(dx) < 14 && Math.abs(dy) < 14) return; + at.axis = at.row && Math.abs(dx) > Math.abs(dy) ? 'x' : 'y'; + } + if (at.axis === 'y') { setScroll(at.y0 - dy, true); return; } + const view = at.row.parentElement; + const maxX = Math.max(0, at.row.scrollWidth - (view.clientWidth - SX * 2)); + at.row.style.transition = 'none'; + at.row.style.transform = `translateX(${-Math.max(0, Math.min(maxX, at.x0 - dx))}px)`; + }, { passive: true }); + const touchDone = () => { + const at = touch.at; + touch.at = null; + if (!at || !at.axis) return; + touch.dragEnd = performance.now(); + const sc = $('#tv-scroll', root); + if (sc) sc.style.transition = ''; + if (at.row) at.row.style.transition = ''; + }; + root.addEventListener('touchend', touchDone, { passive: true }); + root.addEventListener('touchcancel', touchDone, { passive: true }); + // The click a browser sends at the end of a drag is dropped. + root.addEventListener('click', (e) => { + if (performance.now() - touch.dragEnd > 350) return; + e.stopPropagation(); + e.preventDefault(); + }, true); + + // Android's Back (the gesture or the button) is B: back a page, and on Home the way out. + let backHooked = false; + function hookAndroidBack() { + const app = window.__TAURI__ && window.__TAURI__.app; + if (backHooked || !android() || !app || !app.onBackButtonPress) return; + backHooked = true; + app.onBackButtonPress(() => { if (TV.on) press('b'); }).catch(() => { backHooked = false; }); + } + // Keep the pages current while things happen elsewhere. let redraw = 0; const soon = () => { if (!TV.on || TV.booting || $('.tv-boot', root)) return; clearTimeout(redraw); redraw = setTimeout(() => draw(true), 120); };