Compare commits

..
13 changed files with 74 additions and 694 deletions

No files matched your search

+3 -11
View File
@@ -300,20 +300,12 @@ def stageGogNotices = tasks.register('stageGogNotices', Copy) {
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('gogNotices'))
tasks.named('preBuild').configure { dependsOn(stageGogNotices) }
// CI publishes its packs; a local build pins packs nobody hosts (see addonPacks), so the APK carries them.
if (!ciBuild) {
def stageLocalPacks = tasks.register('stageLocalPacks', Sync) {
from(layout.buildDirectory.dir('packs')) { include '*.tar.zst' }
into(layout.buildDirectory.dir('localPackAssets/packs'))
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('localPackAssets'))
tasks.named('preBuild').configure { dependsOn(stageLocalPacks) }
}
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'
def allowStale = (project.findProperty('allowStaleRuntime')
?: localBuildOptions.getProperty('droiddeck.allowStaleRuntime', 'false')).toString().toBoolean()
commandLine([pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'] + (allowStale ? ['--allow-stale-sources'] : []))
}
tasks.configureEach { task ->
if (task.name in ['packageDebug', 'packageRelease']) task.dependsOn(verifyRuntimeInputs)
@@ -581,9 +581,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
// begin() moves the phase on, so the block below never runs for a new session; reset per-session flags here.
SessionState.secondScreenAutoOpened = false
SessionState.secondScreenProvisional = false
}
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
@@ -591,6 +588,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
SessionState.steamVr = intent.getBooleanExtra(EXTRA_STEAMVR, false)
SessionState.secondScreenAutoOpened = false
SessionState.secondScreenProvisional = false
} else if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
SessionState.steamVr = true
}
@@ -22,7 +22,6 @@ import java.io.FileInputStream
internal class AddonPack(
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
) {
sealed interface State {
data object Missing : State
@@ -105,7 +104,7 @@ internal class AddonPack(
}
val root = root(context).apply { mkdirs() }
val archive = File(root, "$sha256.tar.zst")
val downloaded = bundled(context, archive) || urls.any { url ->
val downloaded = urls.any { url ->
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
.also { if (!it) archive.delete() }
}
@@ -127,17 +126,6 @@ internal class AddonPack(
return true
}
// A local build pins the packs it compiled, which no release hosts, so it ships them as assets.
internal fun bundled(context: Context, archive: File): Boolean {
val copied = runCatching {
bundle(context).use { input -> archive.outputStream().use { input.copyTo(it) } }
}.isSuccess
if (copied && Hashes.sha256(archive).equals(sha256, ignoreCase = true)) return true
if (copied) Log.w(TAG, "$name: the bundled pack does not match the pinned digest")
archive.delete()
return false
}
companion object {
private const val TAG = "AddonPack"
private const val REPO = "Droid-Deck/DroidDeck-Components"
@@ -64,12 +64,10 @@ class DualPanelModel(
object DualScreenPanel {
var model by mutableStateOf<DualPanelModel?>(null)
private var displayId = -1
private var presentation: DualScreenPresentation? = null
set(value) { field = value; available = value != null || activity != null || launching }
private var activity: DualScreenActivity? = null
set(value) { field = value; available = value != null || presentation != null || launching }
set(value) { field = value; available = value != null || launching }
private var launching = false
set(value) { field = value; available = value || activity != null || presentation != null }
set(value) { field = value; available = value || activity != null }
private var ownerTask = -1
private var ownerYielded = false
private var ownerPaused = false
@@ -79,8 +77,8 @@ object DualScreenPanel {
var typingShown by mutableStateOf(false)
private set
val shownOn: Int get() = if (presentation != null || activity != null || launching) displayId else -1
val attached: Boolean get() = presentation != null || activity != null
val shownOn: Int get() = if (activity != null || launching) displayId else -1
val attached: Boolean get() = activity != null
var available by mutableStateOf(false)
private set
@@ -125,20 +123,6 @@ object DualScreenPanel {
ownerYielded = false
ownerPaused = false
launching = true
val host = context as? ComponentActivity
val target = host?.getSystemService(Context.DISPLAY_SERVICE)
?.let { (it as android.hardware.display.DisplayManager).getDisplay(display) }
// A second-display activity makes the system launcher treat its bottom home as lost and bring itself forward;
// a presentation belongs to this task and leaves that home alone.
if (host != null && target != null) {
val shown = runCatching { DualScreenPresentation(host, target).also { it.show() } }
if (shown.isSuccess) {
presentation = shown.getOrThrow()
launching = false
return
}
android.util.Log.w("DualScreenPanel", "bottom panel presentation failed; falling back to an activity", shown.exceptionOrNull())
}
val intent = Intent(context, DualScreenActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
runCatching {
@@ -150,8 +134,6 @@ object DualScreenPanel {
stopTyping()
launching = false
displayId = -1
presentation?.dismiss()
presentation = null
activity?.finishAndRemoveTask()
activity = null
}
@@ -162,8 +144,6 @@ object DualScreenPanel {
internal fun attach(host: DualScreenActivity): Boolean {
if (!launching && activity == null) return false
presentation?.dismiss()
presentation = null
if (activity !== host) activity?.finishAndRemoveTask()
activity = host
launching = false
@@ -208,13 +188,6 @@ object DualScreenPanel {
displayId = -1
}
}
internal fun detach(host: DualScreenPresentation) {
if (presentation === host) {
presentation = null
displayId = -1
}
}
}
class DualScreenActivity : ComponentActivity() {
@@ -1,99 +0,0 @@
package com.droiddeck.launcher.ui
import android.app.Presentation
import android.os.Bundle
import android.view.Display
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.core.AppUiPrefs
internal class DualScreenPresentation(
private val host: ComponentActivity,
display: Display,
) : Presentation(host, display) {
private var content: ComposeView? = null
init {
setCancelable(false)
setCanceledOnTouchOutside(false)
setOnDismissListener { DualScreenPanel.detach(this) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
applyImmersiveMode()
val decor = window?.decorView ?: return
decor.setViewTreeLifecycleOwner(host)
decor.setViewTreeViewModelStoreOwner(host)
decor.setViewTreeSavedStateRegistryOwner(host)
decor.setViewTreeOnBackPressedDispatcherOwner(host)
val view = ComposeView(context)
content = view
view.setContent {
val model = DualScreenPanel.model
val request = DualScreenPanel.typing
val typingOn = request != null && DualScreenPanel.typingShown
LaunchedEffect(typingOn) { acceptFocus(typingOn) }
DroidDeckTheme(model?.theme, appScale = model?.appScale ?: AppUiPrefs.DEFAULT_SCALE) {
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
if (request != null && typingOn) TypingPanel(request) {
if (DualScreenPanel.typing === request) DualScreenPanel.finishTyping()
} else if (model != null) DualPanelContent(model)
}
}
}
setContentView(view)
}
private fun acceptFocus(on: Boolean) {
val window = window ?: return
if (on) {
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
content?.requestFocus()
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
host.window?.decorView?.requestFocus()
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) applyImmersiveMode()
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onBackPressed() {
if (DualScreenPanel.typingShown) DualScreenPanel.finishTyping()
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (DualScreenPanel.typingShown && event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) DualScreenPanel.finishTyping()
return true
}
return super.dispatchKeyEvent(event)
}
private fun applyImmersiveMode() {
@Suppress("DEPRECATION")
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
}
}
@@ -2,9 +2,6 @@ package com.droiddeck.launcher.core
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -57,35 +54,4 @@ class AddonPackTest {
installed("b".repeat(64))
assertFalse(AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = false).installed(context))
}
@Test fun localBuildInstallsTheBundledPackWithoutDownloading() {
val archive = tarZst("tool" to "x")
val pack = AddonPack("sample", Hashes.sha256(archive), archive.length(), listOf("tool"), bundle = { archive.inputStream() })
assertTrue(pack.await(context))
assertEquals("x", pack.file(context, "tool").readText())
}
@Test fun bundledPackWithTheWrongDigestIsRejected() {
val archive = tarZst("tool" to "x")
val pack = AddonPack("sample", "a".repeat(64), archive.length(), listOf("tool"),
bundle = { archive.inputStream() })
val copy = File(context.cacheDir, "copy.tar.zst")
assertFalse(pack.bundled(context, copy))
assertFalse(copy.exists())
}
private fun tarZst(vararg files: Pair<String, String>): File =
File(context.cacheDir, "sample-${System.nanoTime()}.tar.zst").apply {
TarArchiveOutputStream(ZstdOutputStream(outputStream())).use { tar ->
for ((path, text) in files) {
val bytes = text.toByteArray()
tar.putArchiveEntry(TarArchiveEntry(path).apply { size = bytes.size.toLong() })
tar.write(bytes)
tar.closeArchiveEntry()
}
}
}
}
@@ -1,15 +1,7 @@
#!/usr/bin/python3
import json
import os
import re
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import urllib.parse
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
@@ -19,22 +11,6 @@ gi.require_version("Flatpak", "1.0")
from gi.repository import Flatpak, Gio, GLib
REMOTE = "flathub"
SYSTEM_BUS = "/run/dbus/system_bus_socket"
BUS_COMMANDS = ("install", "install-bundle", "uninstall", "update", "prune")
BUS_CONFIG = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>system</type>
<listen>unix:path=%s</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
"""
def prepare_rootfs():
@@ -57,116 +33,6 @@ def prepare_rootfs():
emit(e="warning", message="could not prepare %s: %s" % (target, err))
def bus_reachable(path):
if isinstance(path, tuple):
try:
socket.create_connection(path, timeout=1).close()
return True
except (OSError, ValueError):
return False
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.connect(path)
return True
except OSError:
return False
finally:
sock.close()
def system_bus_paths():
address = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS", "")
if not address:
return [SYSTEM_BUS]
paths = []
for entry in filter(None, address.split(";")):
found = None
kind, _, params = entry.partition(":")
values = dict(part.partition("=")[::2] for part in params.split(","))
if kind == "unix":
if values.get("path"):
found = urllib.parse.unquote_to_bytes(values["path"])
elif values.get("abstract"):
found = b"\0" + urllib.parse.unquote_to_bytes(values["abstract"])
elif kind == "tcp":
port = urllib.parse.unquote(values.get("port", ""))
digits = port.lstrip("0")
if not re.fullmatch(r"[0-9]+", port, re.ASCII) or not 0 < len(digits) <= 5 or int(digits) > 65535:
continue
found = (urllib.parse.unquote(values.get("host", "localhost")), int(digits))
if found is None:
return None
paths.append(found)
return paths
def system_bus_reachable():
paths = system_bus_paths()
return paths is None or any(bus_reachable(path) for path in paths)
def stop_system_bus(bus):
if not bus:
return
proc, work, conf, path = bus
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
remove_bus_files(work, conf, path)
def remove_bus_files(work, conf, path):
for name in (path, conf):
try:
os.unlink(name)
except OSError:
pass
try:
os.rmdir(work)
except OSError:
pass
def private_system_bus():
if system_bus_reachable():
return None
daemon = shutil.which("dbus-daemon")
if not daemon:
emit(e="warning", message="no system bus and no dbus-daemon to start one")
return None
try:
work = tempfile.mkdtemp(prefix="droiddeck-flatpak-bus-")
except OSError as err:
emit(e="warning", message="could not start a private system bus: %s" % err)
return None
conf = os.path.join(work, "bus.conf")
path = os.path.join(work, "bus")
try:
with open(conf, "w") as f:
f.write(BUS_CONFIG % path)
proc = subprocess.Popen([daemon, "--config-file=" + conf, "--nofork", "--nopidfile"],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError as err:
remove_bus_files(work, conf, path)
emit(e="warning", message="could not start a private system bus: %s" % err)
return None
bus = (proc, work, conf, path)
for _ in range(50):
if bus_reachable(path) or proc.poll() is not None:
break
time.sleep(0.1)
if not bus_reachable(path):
stop_system_bus(bus)
emit(e="warning", message="the private system bus did not start")
return None
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path
return bus
def emit(**kw):
sys.stdout.write(json.dumps(kw) + "\n")
sys.stdout.flush()
@@ -391,16 +257,6 @@ def main():
cmd, args = sys.argv[1], sys.argv[2:]
if cmd in ("install", "install-bundle", "update"):
prepare_rootfs()
bus = private_system_bus() if cmd in BUS_COMMANDS else None
if bus:
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(128 + signum))
try:
return command(cmd, args)
finally:
stop_system_bus(bus)
def command(cmd, args):
if cmd == "install" and args:
return install(args[0])
if cmd == "install-bundle" and args:
@@ -143,12 +143,6 @@ def protonfixes_off(game):
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
@fix
def little_nightmares_threads(game):
if game.stem == "littlenightmares":
return {"PROTONFIXES_DISABLE": "1"}, [], "Little Nightmares: umu-protonfixes off (its -onethread puts the game and renderer on one thread)"
@fix
def caravan_sandwitch_feature_level(game):
if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping":
@@ -856,55 +850,6 @@ def restore_dirt_ws2(prefix, proton):
return False
EGO_RESTRICTIONS = "system/hardware_settings_restrictions.xml"
EGO_CORE_RULE = re.compile(r'[ \t]*<restrict_if name="cores" op="(int_[a-z]+)" value="(\d+)">.*?</restrict_if>[ \t]*\r?\n', re.S)
EGO_OPS = {"int_eq": int.__eq__, "int_ne": int.__ne__, "int_ge": int.__ge__, "int_gt": int.__gt__,
"int_le": int.__le__, "int_lt": int.__lt__}
def windows_core_count(env):
count = (env.get("WINE_CPU_TOPOLOGY") or "").split(":", 1)[0]
return int(count) if count.isdigit() and int(count) > 0 else None
def ego_core_plan(command, env):
"""Codemasters EGO games (DiRT 3, DiRT Showdown, GRID, F1 ...) pick their thread plan by core count from
system/hardware_settings_restrictions.xml. A count with no plan (5 when a phone's slow cores are left out) puts
every worker on one core, and DiRT 3 then stops on a loading screen. Adds a plan for the count Windows sees,
copied from the nearest smaller one; the file as it was is kept beside it. Returns a note, or None."""
count = windows_core_count(env)
if not count or len(command) < 3:
return None
folder = Path(command[2]).parent
path = folder / EGO_RESTRICTIONS
try:
raw = path.read_bytes()
except OSError:
return None
text = raw.decode("latin-1")
start, end = text.find("<cpu>"), text.find("</cpu>")
if start < 0 or end < start:
return None
rules = list(EGO_CORE_RULE.finditer(text, start, end))
if not rules or any(EGO_OPS.get(rule.group(1), lambda a, b: True)(count, int(rule.group(2))) for rule in rules):
return None
smaller = [rule for rule in rules if rule.group(1) == "int_eq" and int(rule.group(2)) < count]
if not smaller:
return None
source = max(smaller, key=lambda rule: int(rule.group(2)))
worker_map = re.search(r'workerMapFile="([^"]+)"', source.group(0))
if worker_map and not (folder / worker_map.group(1)).is_file():
return None
plan = source.group(0).replace('value="%s"' % source.group(2), 'value="%d"' % count, 1)
saved = path.with_name(path.name + DIRT_SAVED)
if not os.path.lexists(saved):
saved.write_bytes(raw)
staged = path.with_name(path.name + ".droiddeck-tmp")
staged.write_bytes((text[:source.end()] + plan + text[source.end():]).encode("latin-1"))
os.replace(staged, path)
return "%s had no thread plan for %d cores; added a copy of its %s-core plan" % (EGO_RESTRICTIONS, count, source.group(2))
def wait_forwarding_signals(process):
def forward(signum, frame):
try:
@@ -1012,13 +957,6 @@ def main():
env = force_ssbs(command, env)
game_cores(env)
cpu_topology(env, command)
if app_id and len(command) > 2 and command[1] == "waitforexitandrun":
try:
note = ego_core_plan(command, env)
except OSError as error:
note = "no thread plan added for this core count (%s)" % error
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
+2 -1
View File
@@ -23,7 +23,8 @@ while IFS= read -r dir; do
done < <(ls -d "${sdk_dir}"/build-tools/* 2>/dev/null | sort -rV)
[[ -n "${build_tools}" ]] || { echo "No build-tools with aapt, zipalign and apksigner under ${sdk_dir}." >&2; exit 1; }
./gradlew -q :app:assembleRelease
# Runtime assets from another branch are fine for a Kotlin/UI loop; CI and releases stay strict.
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease
(
cd "$(dirname "${signing_env}")"
set -a; . "${signing_env}"; set +a
+26 -4
View File
@@ -31,6 +31,16 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'app/src/main/cpp/waylandcomp/src/spatialpose_shm.h',
'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
# Gradle reads these pins directly, so prepared assets built from other pins cannot be reused.
STRICT_SOURCE_PREFIXES = ('tools/packs/tracking/',)
def staged_scripts(root):
"""Outputs Gradle's stageSessionScripts copies from source on every build."""
overlay = root / 'tools/linuxfs/overlay'
patterns = ['usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**/*']
return {'assets/linuxfs/' + path.relative_to(overlay).as_posix()
for pattern in patterns for path in overlay.glob(pattern) if path.is_file()}
def digest(path):
@@ -149,19 +159,31 @@ def record(root=ROOT):
(root / MANIFEST).write_text(json.dumps(data, sort_keys=True, indent=2) + '\n')
def verify(root=ROOT):
def verify(root=ROOT, stale_sources_ok=False):
try:
data = json.loads((root / MANIFEST).read_text())
except (OSError, ValueError):
raise ValueError('Runtime inputs have not been prepared. Run tools/build_local.sh.')
if data.get('version') != 1 or data.get('sources') != sources(root):
if data.get('version') != 1:
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
current = sources(root)
if data.get('sources') != current:
if not stale_sources_ok:
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
recorded = data.get('sources') or {}
changed = sorted(name for name in recorded.keys() | current.keys() if recorded.get(name) != current.get(name))
pinned = [name for name in changed if name.startswith(STRICT_SOURCE_PREFIXES)]
if pinned:
raise ValueError('Runtime pins changed since preparation (' + ', '.join(pinned) + '). Run tools/build_local.sh.')
print('Warning: reusing runtime assets prepared from other sources (run tools/build_local.sh if these matter):\n '
+ '\n '.join(changed[:20]) + ('\n ...' if len(changed) > 20 else ''), file=sys.stderr)
for name in required():
if name not in data['outputs']:
raise ValueError('Runtime manifest missing ' + name)
restaged = staged_scripts(root) if stale_sources_ok else set()
for name, output in data['outputs'].items():
path = root / output['path']
if not path.is_file() or digest(path) != output['sha256']:
if not path.is_file() or (digest(path) != output['sha256'] and name not in restaged):
raise ValueError('Missing or changed runtime input: ' + name + '. Run tools/build_local.sh.')
if outputs(root) != {name: output['path'] for name, output in data['outputs'].items()}:
raise ValueError('Runtime file set changed. Run tools/build_local.sh.')
@@ -224,7 +246,7 @@ if __name__ == '__main__':
if sys.argv[1] == 'record':
record()
elif sys.argv[1] == 'verify':
verify()
verify(stale_sources_ok='--allow-stale-sources' in sys.argv[2:])
elif sys.argv[1] == 'apk':
check_apk(sys.argv[2])
else:
-199
View File
@@ -1,199 +0,0 @@
import importlib.machinery
import importlib.util
import os
from pathlib import Path
import socket
import sys
import tempfile
import types
import unittest
from unittest import mock
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak"
def load():
repository = types.ModuleType("gi.repository")
repository.Flatpak = types.SimpleNamespace()
repository.Gio = types.SimpleNamespace()
repository.GLib = types.SimpleNamespace(Error=RuntimeError)
gi = types.ModuleType("gi")
gi.require_version = lambda *args: None
gi.repository = repository
saved = {name: sys.modules.get(name) for name in ("gi", "gi.repository")}
sys.modules["gi"] = gi
sys.modules["gi.repository"] = repository
try:
loader = importlib.machinery.SourceFileLoader("droiddeck_flatpak_bus", str(SCRIPT))
module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
loader.exec_module(module)
finally:
for name, value in saved.items():
if value is None:
sys.modules.pop(name, None)
else:
sys.modules[name] = value
return module
class FakeDaemon:
started = []
def __init__(self, argv, **kwargs):
conf = next(a for a in argv if a.startswith("--config-file=")).split("=", 1)[1]
text = open(conf).read()
self.path = text.split("<listen>unix:path=", 1)[1].split("</listen>", 1)[0]
self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.server.bind(self.path)
self.server.listen(4)
self.running = True
FakeDaemon.started.append(self)
def poll(self):
return None if self.running else 0
def terminate(self):
self.running = False
self.server.close()
def wait(self, timeout=None):
return 0
def kill(self):
self.terminate()
class FlatpakSystemBusTest(unittest.TestCase):
def setUp(self):
self.module = load()
self.tmp = tempfile.mkdtemp()
self.env = mock.patch.dict(os.environ, {"DBUS_SYSTEM_BUS_ADDRESS": "unix:path=" + os.path.join(self.tmp, "missing")})
self.env.start()
FakeDaemon.started = []
def tearDown(self):
self.env.stop()
os.rmdir(self.tmp)
def test_a_reachable_system_bus_is_used_as_it_is(self):
path = os.path.join(self.tmp, "system")
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(path)
server.listen(1)
try:
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path
with mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
self.assertIsNone(self.module.private_system_bus())
self.assertEqual([], FakeDaemon.started)
finally:
server.close()
os.unlink(path)
def test_without_a_system_bus_a_private_one_runs_for_the_command_and_is_removed_after(self):
with mock.patch.object(self.module.shutil, "which", return_value="/usr/bin/dbus-daemon"), \
mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
bus = self.module.private_system_bus()
self.assertIsNotNone(bus)
_, work, conf, path = bus
self.assertEqual("unix:path=" + path, os.environ["DBUS_SYSTEM_BUS_ADDRESS"])
self.assertTrue(self.module.bus_reachable(path))
self.module.stop_system_bus(bus)
self.assertFalse(os.path.exists(work))
def test_any_reachable_address_in_a_list_counts_as_the_system_bus(self):
path = os.path.join(self.tmp, "system")
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(path)
server.listen(1)
try:
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=%s;unix:guid=1,path=%s" % (os.path.join(self.tmp, "missing"), path)
with mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
self.assertIsNone(self.module.private_system_bus())
self.assertEqual([], FakeDaemon.started)
finally:
server.close()
os.unlink(path)
def test_escaped_and_abstract_addresses_are_probed_as_dbus_reads_them(self):
path = os.path.join(self.tmp, "sys-bus")
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(path)
server.listen(1)
abstract = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
abstract.bind(b"\0droiddeck-flatpak-test-%d\xff" % os.getpid())
abstract.listen(1)
try:
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path.replace("-", "%2D")
self.assertTrue(self.module.system_bus_reachable())
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=%s;unix:abstract=droiddeck-flatpak-test-%d%%FF" % (os.path.join(self.tmp, "missing"), os.getpid())
self.assertTrue(self.module.system_bus_reachable())
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:abstract=droiddeck-flatpak-missing-%d" % os.getpid()
self.assertFalse(self.module.system_bus_reachable())
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind(("127.0.0.1", 0))
listener.listen(8)
port = listener.getsockname()[1]
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:abstract=droiddeck-flatpak-missing-%d;tcp:host=127.0.0.1,port=%d" % (os.getpid(), port)
self.assertTrue(self.module.system_bus_reachable())
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=" + "".join("%%%02X" % ord(c) for c in str(port))
self.assertTrue(self.module.system_bus_reachable())
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=000%d" % port
self.assertTrue(self.module.system_bus_reachable())
listener.close()
self.assertFalse(self.module.system_bus_reachable())
for bad in ("%C2%B2", "65536", "0", "000", "x", "9" * 5000):
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=" + bad
self.assertEqual([], self.module.system_bus_paths())
self.assertFalse(self.module.system_bus_reachable())
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "launchd:env=DBUS_LAUNCHD_SESSION_BUS_SOCKET"
self.assertTrue(self.module.system_bus_reachable())
finally:
abstract.close()
server.close()
os.unlink(path)
def test_a_daemon_that_cannot_launch_leaves_no_files_and_warns(self):
made = []
real = tempfile.mkdtemp
def mkdtemp(**kwargs):
made.append(real(**kwargs))
return made[-1]
with mock.patch.object(self.module.shutil, "which", return_value="/usr/bin/dbus-daemon"), \
mock.patch.object(self.module.tempfile, "mkdtemp", mkdtemp), \
mock.patch.object(self.module.subprocess, "Popen", side_effect=OSError("exec failed")), \
mock.patch.object(self.module, "emit") as emit:
self.assertIsNone(self.module.private_system_bus())
emit.assert_called_once()
self.assertFalse(os.path.exists(made[0]))
def test_without_dbus_daemon_the_command_still_runs_and_warns(self):
with mock.patch.object(self.module.shutil, "which", return_value=None), \
mock.patch.object(self.module, "emit") as emit:
self.assertIsNone(self.module.private_system_bus())
emit.assert_called_once()
def test_every_command_that_changes_apps_gets_a_system_bus(self):
calls = []
self.module.private_system_bus = lambda: calls.append("start") or "bus"
self.module.stop_system_bus = lambda bus: calls.append("stop:%s" % bus)
self.module.prepare_rootfs = lambda: None
self.module.install = lambda app_id: calls.append("install") or 0
self.module.updates = lambda: calls.append("updates") or 0
with mock.patch.object(sys, "argv", ["droiddeck-flatpak", "install", "org.example.App"]), \
mock.patch.object(self.module.signal, "signal") as handler:
self.assertEqual(0, self.module.main())
self.assertEqual(["start", "install", "stop:bus"], calls)
self.assertEqual(self.module.signal.SIGTERM, handler.call_args[0][0])
with self.assertRaises(SystemExit):
handler.call_args[0][1](self.module.signal.SIGTERM, None)
calls.clear()
with mock.patch.object(sys, "argv", ["droiddeck-flatpak", "updates"]):
self.assertEqual(0, self.module.main())
self.assertNotIn("start", calls)
self.assertIn("updates", calls)
if __name__ == "__main__":
unittest.main()
-93
View File
@@ -245,93 +245,6 @@ class DirtTelemetryFixTest(unittest.TestCase):
self.assertEqual(calls, ["restored"])
class EgoCorePlanTest(unittest.TestCase):
"""DiRT 3's restrictions as shipped: plans for 2, 3, 4, 6 and 8+ cores, one core for anything else."""
@staticmethod
def rule(op, value, worker_map):
return (' <restrict_if name="cores" op="%s" value="%d">\r\n <restrict_add>\r\n'
' <threadStrategy parallelUpdateRender="true" workerMapFile="system/%s" updateProcessor="2" />\r\n'
' </restrict_add>\r\n </restrict_if>\r\n' % (op, value, worker_map))
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.system = Path(self.tmp.name) / "DiRT 3/system"
self.system.mkdir(parents=True)
cpu = "".join(self.rule("int_eq", n, "workerMap%dCore.xml" % n) for n in (2, 3, 4, 6)) + self.rule("int_ge", 8, "workerMap8Core.xml")
self.shipped = ('<?xml version="1.0" encoding="UTF-8" ?>\r\n<hardware_settings_restrictions>\r\n <cpu>\r\n'
' <restrict_info>\r\n' + cpu +
' <restrict_else>\r\n <restrict_add>\r\n'
' <threadStrategy parallelUpdateRender="false" workerMapFile="system/workerMap.xml" />\r\n'
' </restrict_add>\r\n </restrict_else>\r\n </restrict_info>\r\n </cpu>\r\n'
' <audio_card>\r\n' + self.rule("int_eq", 5, "audio.xml") + ' </audio_card>\r\n'
'</hardware_settings_restrictions>').encode("latin-1")
self.path = self.system / "hardware_settings_restrictions.xml"
self.path.write_bytes(self.shipped)
for name in ("workerMap.xml", "workerMap2Core.xml", "workerMap3Core.xml", "workerMap4Core.xml", "workerMap6Core.xml", "workerMap8Core.xml"):
(self.system / name).write_text("<workerMap />")
self.command = ["/proton", "waitforexitandrun", str(self.system.parent / "dirt3_game.exe")]
self.saved = self.path.with_name(self.path.name + ".droiddeck-original")
def plan(self, topology, command=None):
env = {} if topology is None else {"WINE_CPU_TOPOLOGY": topology}
return MODULE["ego_core_plan"](command or self.command, env)
def test_five_cores_get_a_copy_of_the_four_core_plan(self):
note = self.plan("5:7,3,4,5,6")
self.assertIn("5 cores", note)
self.assertIn("4-core plan", note)
text = self.path.read_bytes()
four = self.rule("int_eq", 4, "workerMap4Core.xml").encode("latin-1")
five = self.rule("int_eq", 5, "workerMap4Core.xml").encode("latin-1")
self.assertEqual(text, self.shipped.replace(four, four + five))
self.assertNotIn(b"\n", text.replace(b"\r\n", b""))
self.assertEqual(self.saved.read_bytes(), self.shipped)
self.assertIsNone(self.plan("5:7,3,4,5,6"))
self.assertEqual(self.path.read_bytes(), text)
self.assertEqual(self.saved.read_bytes(), self.shipped)
def test_seven_cores_get_the_six_core_plan(self):
self.assertIn("6-core plan", self.plan("7:7,1,2,3,4,5,6"))
self.assertIn(b'value="7">\r\n <restrict_add>\r\n <threadStrategy parallelUpdateRender="true" '
b'workerMapFile="system/workerMap6Core.xml"', self.path.read_bytes())
def test_counts_with_a_plan_are_left_alone(self):
for topology in ("2:7,6", "4:7,3,4,5", "6:7,3,4,5,6,2", "8:7,2,3,4,5,6,0,1", "12:0,1,2,3,4,5,6,7,8,9,10,11"):
self.assertIsNone(self.plan(topology), topology)
self.assertEqual(self.path.read_bytes(), self.shipped)
self.assertFalse(os.path.lexists(self.saved))
def test_nothing_changes_without_a_core_count_a_restrictions_file_a_smaller_plan_or_its_worker_map(self):
self.assertIsNone(self.plan(None))
self.assertIsNone(self.plan(""))
self.assertIsNone(self.plan("x:1"))
self.assertIsNone(self.plan("1:7"))
self.assertIsNone(self.plan("5:7,3,4,5,6", ["/proton", "waitforexitandrun"]))
self.assertIsNone(self.plan("5:7,3,4,5,6", ["/proton", "waitforexitandrun", "/elsewhere/game.exe"]))
(self.system / "workerMap4Core.xml").unlink()
self.assertIsNone(self.plan("5:7,3,4,5,6"))
self.assertEqual(self.path.read_bytes(), self.shipped)
self.assertFalse(os.path.lexists(self.saved))
def test_an_unknown_comparison_counts_as_a_plan(self):
self.path.write_bytes(self.shipped.replace(b'op="int_ge" value="8"', b'op="int_between" value="8"'))
self.assertIsNone(self.plan("5:7,3,4,5,6"))
def test_main_adds_the_plan_before_the_game_starts(self):
with tempfile.TemporaryDirectory() as tmp:
probe = Path(tmp) / "probe"
probe.write_text('#!/bin/sh\ngrep -c \'value="5"\' "%s"\n' % self.path)
probe.chmod(0o755)
env = {k: v for k, v in os.environ.items() if not k.startswith(("WINE", "PROTON", "DROIDDECK", "BL_", "STEAM"))}
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/3791535942", WINE_CPU_TOPOLOGY="5:7,3,4,5,6")
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun", self.command[2]],
env=env, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.strip(), "2", result.stderr)
self.assertIn("added a copy of its 4-core plan", result.stderr)
class GameDebugLoggingTest(unittest.TestCase):
def test_maintenance_precision_survives_run_with_performance_game_settings(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -887,12 +800,6 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertTrue(notes)
self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], []))
def test_little_nightmares_keeps_its_render_thread(self):
env, extra, notes = MODULE["engine_fixes"]("/game/Little Nightmares/Atlas/Binaries/Win64/LittleNightmares.exe", [])
self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, []))
self.assertTrue(notes)
self.assertEqual(MODULE["engine_fixes"]("/game/Little Nightmares II/Moonlight/Binaries/Win64/LittleNightmaresII.exe", []), ({}, [], []))
def test_game_cores_are_parsed_from_lists_and_ranges(self):
parse = MODULE["parse_cores"]
self.assertEqual(parse("0-3,6"), {0, 1, 2, 3, 6})
+36
View File
@@ -88,6 +88,42 @@ class RuntimeInputsTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_dev_loop_can_reuse_assets_from_other_sources(self):
runtime.record(self.root)
self.source.write_text('new implementation')
with mock.patch('sys.stderr', new_callable=io.StringIO) as stderr:
runtime.verify(self.root, stale_sources_ok=True)
self.assertIn('tools/linuxfs/preload/test.c', stderr.getvalue())
def test_dev_loop_still_rejects_changed_outputs(self):
runtime.record(self.root)
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
with self.assertRaisesRegex(ValueError, 'changed runtime input'):
runtime.verify(self.root, stale_sources_ok=True)
def test_dev_loop_accepts_restaged_session_scripts(self):
script = self.root / 'tools/linuxfs/overlay/usr/local/bin/droiddeck-test'
staged = self.root / 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test'
for path in (script, staged):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('old script')
runtime.record(self.root)
script.write_text('new script')
staged.write_text('new script')
with mock.patch('sys.stderr', new_callable=io.StringIO):
runtime.verify(self.root, stale_sources_ok=True)
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_dev_loop_rejects_changed_tracking_pins(self):
pins = self.root / 'tools/packs/tracking/release.env'
pins.parent.mkdir(parents=True)
pins.write_text('OPENCV_VERSION=4.10.0')
runtime.record(self.root)
pins.write_text('OPENCV_VERSION=4.11.0')
with self.assertRaisesRegex(ValueError, 'pins changed'):
runtime.verify(self.root, stale_sources_ok=True)
def test_changed_quest_source_rejects_old_outputs(self):
source = self.root / 'tools/quest/kgsl_compat.c'
source.parent.mkdir(parents=True)