mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 04:46:08 +00:00
Merge current main into PR #564
This commit is contained in:
commit
184409f33c
37 files changed
+1500
-146
No files matched your search
@@ -0,0 +1,40 @@
|
||||
name: Build validation
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened, edited, ready_for_review]
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_run:
|
||||
workflows: [Build APK]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr_number:
|
||||
description: Pull request to validate; empty for main
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
pull-requests: read
|
||||
statuses: write
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Build APK
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.workflow_sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Validate source and APK compilation
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh auth setup-git
|
||||
python3 tools/release/validate_apk.py
|
||||
+15
-10
@@ -87,7 +87,7 @@ jobs:
|
||||
|
||||
build:
|
||||
needs: xbox
|
||||
name: Build APK
|
||||
name: Compile and test APK
|
||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
@@ -100,17 +100,22 @@ jobs:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check co-authors
|
||||
if: github.event_name == 'pull_request'
|
||||
- name: Check human authorship
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
BEFORE: ${{ github.event.before }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch --no-tags origin main
|
||||
base=$(git merge-base origin/main HEAD)
|
||||
messages=$(git log --format=%B "$base..HEAD")
|
||||
messages+=$'\n'"$(jq -r '.pull_request.title, (.pull_request.body // "")' "$GITHUB_EVENT_PATH")"
|
||||
if grep -Eiq '^[[:space:]]*Co-authored-by:.*(Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\])' <<<"$messages"; then
|
||||
echo "::error::AI and bot identities cannot be co-authors; remove the Co-authored-by trailer."
|
||||
exit 1
|
||||
if [ "$EVENT_NAME" = pull_request ]; then
|
||||
git fetch --no-tags origin main
|
||||
base=$(git merge-base origin/main HEAD)
|
||||
checker="$RUNNER_TEMP/droiddeck-check-authorship.py"
|
||||
git show origin/main:tools/release/check_authorship.py > "$checker"
|
||||
python3 "$checker" "$base..HEAD" --event "$GITHUB_EVENT_PATH"
|
||||
elif [ "$EVENT_NAME" = push ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then
|
||||
python3 tools/release/check_authorship.py "$BEFORE..HEAD"
|
||||
else
|
||||
python3 tools/release/check_authorship.py HEAD
|
||||
fi
|
||||
|
||||
- name: The packages a signed build ships as
|
||||
|
||||
@@ -2650,6 +2650,38 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw &
|
||||
static constexpr uint32_t TRITON_HWID = 72;
|
||||
static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3;
|
||||
|
||||
// Steam compares the controller's firmware with TRITON_FW_TS in its bundled hardwareupdater.cfg (and blocks
|
||||
// with a required update below MUST_UPDATE_TRITON_FW_TS), so the emulated pad reports at least the build
|
||||
// Steam ships.
|
||||
static uint32_t triton_fw_timestamp() {
|
||||
static const uint32_t timestamp = [] {
|
||||
std::vector<std::string> roots;
|
||||
char exe[PATH_MAX];
|
||||
ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
|
||||
if (n > 0) {
|
||||
std::string path(exe, static_cast<size_t>(n));
|
||||
size_t bin = path.rfind('/');
|
||||
size_t root = bin == std::string::npos || bin == 0 ? std::string::npos : path.rfind('/', bin - 1);
|
||||
if (bin != std::string::npos && bin > 0) roots.push_back(path.substr(0, bin));
|
||||
if (root != std::string::npos) roots.push_back(path.substr(0, root));
|
||||
}
|
||||
if (const char *home = getenv("HOME")) roots.push_back(std::string(home) + "/.local/share/Steam");
|
||||
uint32_t newest = TRITON_FW_TIMESTAMP;
|
||||
for (const std::string &root : roots) {
|
||||
std::ifstream cfg(root + "/bin/hardwareupdater/hardwareupdater.cfg");
|
||||
std::string line;
|
||||
while (std::getline(cfg, line)) {
|
||||
if (line.rfind("TRITON_FW_TS:", 0) != 0) continue;
|
||||
uint32_t shipped = static_cast<uint32_t>(strtoul(line.c_str() + 13, nullptr, 16));
|
||||
if (shipped > newest) newest = shipped;
|
||||
}
|
||||
}
|
||||
if (newest != TRITON_FW_TIMESTAMP) Logger::log("triton: reporting firmware %08x, the build Steam ships\n", newest);
|
||||
return newest;
|
||||
}();
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw &triton, uint8_t *buf, size_t size, bool set) {
|
||||
if (!buf || size < 2) {
|
||||
errno = EINVAL;
|
||||
@@ -2670,7 +2702,7 @@ __attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw &
|
||||
switch (triton.pending_feature) {
|
||||
case DECK_GET_ATTRIBUTES_VALUES: {
|
||||
static const uint8_t kIds[] = {0x01, 0x02, 0x04, 0x09, 0x0a, 0x0b};
|
||||
const uint32_t values[] = {static_cast<uint32_t>(TRITON_WIRED_PRODUCT), 0, TRITON_FW_TIMESTAMP, TRITON_HWID, 0, 4000};
|
||||
const uint32_t values[] = {static_cast<uint32_t>(TRITON_WIRED_PRODUCT), 0, triton_fw_timestamp(), TRITON_HWID, 0, 4000};
|
||||
reply[2] = sizeof(kIds) * 5;
|
||||
for (size_t i = 0; i < sizeof(kIds); i++) {
|
||||
reply[3 + i * 5] = kIds[i];
|
||||
|
||||
@@ -1661,6 +1661,7 @@ class MainActivity : ComponentActivity() {
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
|
||||
com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||
@@ -1727,6 +1728,9 @@ class MainActivity : ComponentActivity() {
|
||||
onZramCompression = { on -> SessionPrefs.setZramCompression(this, on); zramCompression = on },
|
||||
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
|
||||
onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on },
|
||||
onUnfoldedControlsWithController = { on ->
|
||||
SessionPrefs.setUnfoldedControlsWithController(this, on); unfoldedControlsWithController = on
|
||||
},
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||
@@ -1915,10 +1919,12 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
private var pipAutoEnter by mutableStateOf(false)
|
||||
private var unfoldedControls by mutableStateOf(false)
|
||||
private var unfoldedControlsWithController by mutableStateOf(false)
|
||||
|
||||
private fun loadModeSettings(mode: String) {
|
||||
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
||||
unfoldedControls = SessionPrefs.unfoldedControls(this)
|
||||
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
|
||||
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
forceSsbs = SessionPrefs.forceSsbs(this)
|
||||
|
||||
@@ -134,6 +134,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var pipUi by mutableStateOf(false)
|
||||
private var pipAutoEnter by mutableStateOf(false)
|
||||
private var unfoldedControls by mutableStateOf(false)
|
||||
private var unfoldedControlsWithController by mutableStateOf(false)
|
||||
private var picturePosition by mutableStateOf("center")
|
||||
|
||||
private fun applyGameAlignment() {
|
||||
@@ -366,17 +367,46 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay)
|
||||
private var started = false
|
||||
private var sessionActivityDisplayId = Display.DEFAULT_DISPLAY
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private var secondScreenPresentation: SecondScreenPresentation? = null
|
||||
private val displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayAdded(displayId: Int) {
|
||||
notifyActivityDisplayStateChanged(displayId)
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
override fun onDisplayRemoved(displayId: Int) {
|
||||
if (refreshActivityDisplayId() && started) {
|
||||
SessionService.setActivityDisplay(this@SessionActivity, sessionActivityDisplayId)
|
||||
}
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
notifyActivityDisplayStateChanged(displayId)
|
||||
followPanelRefresh(displayId)
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun currentActivityDisplayId(): Int = windowManager.defaultDisplay.displayId
|
||||
|
||||
private fun refreshActivityDisplayId(): Boolean {
|
||||
val current = if (Build.VERSION.SDK_INT >= 30) display?.displayId ?: currentActivityDisplayId()
|
||||
else currentActivityDisplayId()
|
||||
val changed = sessionActivityDisplayId != current
|
||||
sessionActivityDisplayId = current
|
||||
SessionState.activityDisplayId = current
|
||||
return changed
|
||||
}
|
||||
|
||||
private fun notifyActivityDisplayStateChanged(changedDisplayId: Int) {
|
||||
val changed = refreshActivityDisplayId()
|
||||
if (started && (changed || changedDisplayId == sessionActivityDisplayId)) {
|
||||
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
|
||||
}
|
||||
}
|
||||
|
||||
private fun followPanelRefresh(displayId: Int) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val output = glassesScreen?.display
|
||||
@@ -923,6 +953,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
},
|
||||
unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null,
|
||||
onUnfoldedControls = ::chooseUnfoldedControls,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
|
||||
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
|
||||
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||
@@ -1407,6 +1439,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun readPrefs() {
|
||||
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
||||
unfoldedControls = SessionPrefs.unfoldedControls(this)
|
||||
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
|
||||
picturePosition = SessionPrefs.picturePosition(this)
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
hudFps = SessionPrefs.hudShowFps(this)
|
||||
@@ -1678,7 +1711,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
intent.getStringExtra(SessionService.EXTRA_STEAM_UI),
|
||||
intent.getStringExtra(SessionService.EXTRA_STEAM_URL),
|
||||
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
|
||||
shownOnDisplayId,
|
||||
sessionActivityDisplayId,
|
||||
)
|
||||
}
|
||||
applyFrameGen()
|
||||
@@ -1729,7 +1762,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
if (started) SessionService.setActivityDisplay(this, shownOnDisplayId)
|
||||
if (refreshActivityDisplayId() && started) {
|
||||
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
|
||||
}
|
||||
cancelTouchGestures()
|
||||
applyFollowOrientation(newConfig)
|
||||
applyUnfoldedControls()
|
||||
@@ -2456,6 +2491,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
applyUnfoldedControls()
|
||||
}
|
||||
|
||||
private fun chooseUnfoldedControlsWithController(on: Boolean) {
|
||||
SessionPrefs.setUnfoldedControlsWithController(this, on)
|
||||
unfoldedControlsWithController = on
|
||||
applyUnfoldedControls()
|
||||
}
|
||||
|
||||
private fun refreshControls() {
|
||||
applyUnfoldedControls()
|
||||
updateOnScreenControls()
|
||||
@@ -2465,11 +2506,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (!::sessionRoot.isInitialized) return
|
||||
val width = sessionRoot.width
|
||||
val height = sessionRoot.height
|
||||
val wanted = unfoldedControls && com.droiddeck.launcher.session.SessionDisplay.foldable(this) &&
|
||||
!PadBridge.anyControllerConnected() && !SteamControllerBle.connected &&
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad &&
|
||||
!pipUi && !isInPictureInPictureMode && width > 0 && height > 0 &&
|
||||
resources.configuration.smallestScreenWidthDp >= com.droiddeck.launcher.session.SessionDisplay.UNFOLDED_MIN_DP
|
||||
val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted(
|
||||
enabled = unfoldedControls,
|
||||
foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this),
|
||||
controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected,
|
||||
keepWithController = unfoldedControlsWithController,
|
||||
steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad,
|
||||
pip = pipUi || isInPictureInPictureMode,
|
||||
width = width,
|
||||
height = height,
|
||||
smallestWidthDp = resources.configuration.smallestScreenWidthDp,
|
||||
)
|
||||
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
|
||||
else FrameLayout.LayoutParams.MATCH_PARENT
|
||||
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
|
||||
@@ -2888,11 +2935,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
super.onStart()
|
||||
if (runtimeRemovalBlocked) return
|
||||
started = true
|
||||
refreshActivityDisplayId()
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
refreshSecondScreenDisplays()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
startedScreens++
|
||||
SessionService.setActivityVisible(this, true, shownOnDisplayId)
|
||||
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
|
||||
Glasses.rescan()
|
||||
updateGlassesScreen()
|
||||
updateHandCamera()
|
||||
@@ -2906,7 +2954,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
closeSecondScreen(reset = false)
|
||||
startedScreens = (startedScreens - 1).coerceAtLeast(0)
|
||||
updateGlassesScreen()
|
||||
if (startedScreens == 0) SessionService.setActivityVisible(this, false)
|
||||
if (startedScreens == 0) SessionService.setActivityVisible(this, false, sessionActivityDisplayId)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
@@ -2937,6 +2985,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (refreshActivityDisplayId() && started) {
|
||||
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
|
||||
}
|
||||
applyFollowOrientation(resources.configuration)
|
||||
if (runtimeRemovalBlocked) return
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
|
||||
@@ -44,6 +44,19 @@ object SessionDisplay {
|
||||
fun unfoldedGameHeight(width: Int, height: Int): Int =
|
||||
minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) and 1.inv()
|
||||
|
||||
fun unfoldedControlsWanted(
|
||||
enabled: Boolean,
|
||||
foldable: Boolean,
|
||||
controllerConnected: Boolean,
|
||||
keepWithController: Boolean,
|
||||
steamDeckPad: Boolean,
|
||||
pip: Boolean,
|
||||
width: Int,
|
||||
height: Int,
|
||||
smallestWidthDp: Int,
|
||||
): Boolean = enabled && foldable && (keepWithController || !controllerConnected) && steamDeckPad &&
|
||||
!pip && width > 0 && height > 0 && smallestWidthDp >= UNFOLDED_MIN_DP
|
||||
|
||||
|
||||
fun panelSize(context: Context): Pair<Int, Int> {
|
||||
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
|
||||
@@ -213,6 +213,7 @@ object SessionFiles {
|
||||
if (!FileUtils.writeString(File(etc, "steam-compatibility-label"), context.getString(R.string.steam_compat_label))) {
|
||||
Log.e(TAG, "could not write steam-compatibility-label")
|
||||
}
|
||||
writeCjkFontConfig(root, etc)
|
||||
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
|
||||
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
|
||||
if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n")
|
||||
@@ -554,4 +555,96 @@ object SessionFiles {
|
||||
).joinToString(newline)
|
||||
|
||||
fun logDirectory(context: Context): File = LinuxRuntime.logDir(context).apply { mkdirs() }
|
||||
|
||||
/**
|
||||
* Registers the Android system fonts (which include CJK faces such as Noto Sans CJK /
|
||||
* MiSans) with the container's fontconfig, so the Steam Deck UI (CEF/webkit renderer)
|
||||
* resolves Chinese/Japanese glyphs instead of showing tofu / mojibake.
|
||||
* The fonts themselves are bind-mounted by LinuxRuntime.bindSystemFonts() into
|
||||
* /usr/local/share/fonts/android; here we only need to point fontconfig at them.
|
||||
*/
|
||||
private fun writeCjkFontConfig(root: File, etc: File) {
|
||||
try {
|
||||
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
|
||||
val conf = File(confDir, "99-droiddeck-cjk.conf")
|
||||
val xml = """<?xml version="1.0"?>
|
||||
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
|
||||
<fontconfig>
|
||||
<dir>/usr/local/share/fonts/android</dir>
|
||||
<dir>/system/fonts</dir>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="contains"><string>ja</string></test>
|
||||
<test name="family" qual="any"><string>sans-serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK JP</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="contains"><string>ja</string></test>
|
||||
<test name="family" qual="any"><string>serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK JP</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="eq"><string>zh</string></test>
|
||||
<test name="family" qual="any"><string>sans-serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK SC</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="eq"><string>zh</string></test>
|
||||
<test name="family" qual="any"><string>serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK SC</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="eq"><string>zh-cn</string></test>
|
||||
<test name="family" qual="any"><string>sans-serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK SC</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="eq"><string>zh-cn</string></test>
|
||||
<test name="family" qual="any"><string>serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK SC</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="eq"><string>zh-tw</string></test>
|
||||
<test name="family" qual="any"><string>sans-serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK TC</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="eq"><string>zh-tw</string></test>
|
||||
<test name="family" qual="any"><string>serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK TC</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="eq"><string>zh-hk</string></test>
|
||||
<test name="family" qual="any"><string>sans-serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK TC</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="eq"><string>zh-hk</string></test>
|
||||
<test name="family" qual="any"><string>serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK TC</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="contains"><string>ko</string></test>
|
||||
<test name="family" qual="any"><string>sans-serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK KR</string></edit>
|
||||
</match>
|
||||
<match target="pattern">
|
||||
<test name="lang" compare="contains"><string>ko</string></test>
|
||||
<test name="family" qual="any"><string>serif</string></test>
|
||||
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK KR</string></edit>
|
||||
</match>
|
||||
</fontconfig>
|
||||
"""
|
||||
if (!conf.isFile || FileUtils.readString(conf) != xml) {
|
||||
val staged = File(confDir, conf.name + ".staged")
|
||||
if (FileUtils.writeString(staged, xml) && staged.renameTo(conf)) {
|
||||
Log.i(TAG, "Wrote CJK fontconfig 99-droiddeck-cjk.conf")
|
||||
} else {
|
||||
staged.delete()
|
||||
Log.e(TAG, "Could not write CJK fontconfig")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "CJK fontconfig setup failed", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1001,6 +1001,13 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("unfoldedControls", enabled).apply()
|
||||
}
|
||||
|
||||
fun unfoldedControlsWithController(context: Context): Boolean =
|
||||
prefs(context).getBoolean("unfoldedControlsWithController", false)
|
||||
|
||||
fun setUnfoldedControlsWithController(context: Context, enabled: Boolean) {
|
||||
prefs(context).edit().putBoolean("unfoldedControlsWithController", enabled).apply()
|
||||
}
|
||||
|
||||
const val SURFACE_STICK = "stick"
|
||||
const val SURFACE_TRACKPAD = "trackpad"
|
||||
|
||||
|
||||
@@ -76,9 +76,16 @@ class SessionService : Service() {
|
||||
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
|
||||
private var steamDownloadsInBackground = false
|
||||
private var activityVisible = true
|
||||
private var activityDisplayId = Display.DEFAULT_DISPLAY
|
||||
private var xrActivityVisible = false
|
||||
private var signInHold = false
|
||||
private val hasVisibleSurface get() = sessionHasVisibleSurface(activityVisible || signInHold, screenOn, xrActivityVisible)
|
||||
private val hasVisibleSurface get() = !SessionVisibilityPolicy.isHidden(
|
||||
activityStarted = activityVisible || signInHold,
|
||||
defaultDisplayOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn,
|
||||
activityOnDefaultDisplay = activityDisplayId == Display.DEFAULT_DISPLAY,
|
||||
activityDisplayOn = activityDisplayOn(),
|
||||
xrActivityVisible = xrActivityVisible,
|
||||
)
|
||||
private var screenOn = true
|
||||
private var sessionDisplayId = Display.DEFAULT_DISPLAY
|
||||
private var manualPauseRequested = false
|
||||
@@ -115,12 +122,22 @@ class SessionService : Service() {
|
||||
private val displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) {}
|
||||
override fun onDisplayRemoved(displayId: Int) {
|
||||
if (displayId != sessionDisplayId) return
|
||||
sessionDisplayId = Display.DEFAULT_DISPLAY
|
||||
refreshScreenOn()
|
||||
if (displayId == sessionDisplayId) {
|
||||
sessionDisplayId = Display.DEFAULT_DISPLAY
|
||||
refreshScreenOn()
|
||||
}
|
||||
if (displayId == activityDisplayId) {
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
}
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
if (displayId == sessionDisplayId && displayId != Display.DEFAULT_DISPLAY) refreshScreenOn()
|
||||
if (displayId == activityDisplayId) {
|
||||
resumeSteamSleepOnReturn()
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,6 +149,14 @@ class SessionService : Service() {
|
||||
interactive ?: (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true, state)
|
||||
}
|
||||
|
||||
private fun activityDisplayOn(): Boolean {
|
||||
if (activityDisplayId == Display.DEFAULT_DISPLAY) {
|
||||
return (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn
|
||||
}
|
||||
val displays = getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager ?: return false
|
||||
return displays.getDisplay(activityDisplayId)?.state == Display.STATE_ON
|
||||
}
|
||||
|
||||
private fun refreshScreenOn() {
|
||||
val on = readScreenOn()
|
||||
if (on == screenOn) return
|
||||
@@ -202,6 +227,7 @@ class SessionService : Service() {
|
||||
ACTION_ACTIVITY_VISIBLE -> {
|
||||
if (!SessionState.pipActive) pipTask = false
|
||||
activityVisible = true
|
||||
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
|
||||
sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId)
|
||||
screenOn = readScreenOn()
|
||||
suspendDownloadNow = false
|
||||
@@ -215,8 +241,16 @@ class SessionService : Service() {
|
||||
refreshScreenOn()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_ACTIVITY_DISPLAY_CHANGED -> {
|
||||
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
|
||||
resumeSteamSleepOnReturn()
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_ACTIVITY_HIDDEN -> {
|
||||
activityVisible = false
|
||||
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
@@ -279,6 +313,7 @@ class SessionService : Service() {
|
||||
xrActivityVisible = false
|
||||
signInHold = false
|
||||
sessionDisplayId = intent?.getIntExtra(EXTRA_DISPLAY_ID, Display.DEFAULT_DISPLAY) ?: Display.DEFAULT_DISPLAY
|
||||
activityDisplayId = intent?.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, sessionDisplayId) ?: sessionDisplayId
|
||||
screenOn = readScreenOn()
|
||||
manualPauseRequested = false
|
||||
suspendDownloadNow = false
|
||||
@@ -1849,7 +1884,9 @@ class SessionService : Service() {
|
||||
private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE"
|
||||
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
|
||||
private const val ACTION_ACTIVITY_DISPLAY = "com.droiddeck.launcher.ACTIVITY_DISPLAY"
|
||||
private const val ACTION_ACTIVITY_DISPLAY_CHANGED = "com.droiddeck.launcher.ACTIVITY_DISPLAY_CHANGED"
|
||||
private const val EXTRA_DISPLAY_ID = "displayId"
|
||||
private const val EXTRA_ACTIVITY_DISPLAY_ID = "activityDisplayId"
|
||||
private const val ACTION_XR_ACTIVITY_VISIBLE = "com.droiddeck.launcher.XR_ACTIVITY_VISIBLE"
|
||||
private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN"
|
||||
private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD"
|
||||
@@ -1894,8 +1931,10 @@ class SessionService : Service() {
|
||||
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
|
||||
displayId: Int = Display.DEFAULT_DISPLAY,
|
||||
) {
|
||||
SessionState.activityDisplayId = displayId
|
||||
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
|
||||
.putExtra(EXTRA_DISPLAY_ID, displayId)
|
||||
.putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId)
|
||||
if (program != null) intent.putExtra(EXTRA_PROGRAM, program)
|
||||
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
|
||||
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
|
||||
@@ -1916,15 +1955,29 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PIP_BEGIN))
|
||||
}
|
||||
|
||||
fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = Display.DEFAULT_DISPLAY) {
|
||||
fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = contextDisplayId(context)) {
|
||||
if (!SessionState.running) return
|
||||
val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(action).putExtra(EXTRA_DISPLAY_ID, displayId))
|
||||
SessionState.activityDisplayId = displayId
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(action)
|
||||
.putExtra(EXTRA_DISPLAY_ID, displayId)
|
||||
.putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId))
|
||||
}
|
||||
|
||||
fun setActivityDisplay(context: Context, displayId: Int) {
|
||||
if (!SessionState.running) return
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY).putExtra(EXTRA_DISPLAY_ID, displayId))
|
||||
SessionState.activityDisplayId = displayId
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY)
|
||||
.putExtra(EXTRA_DISPLAY_ID, displayId))
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY_CHANGED)
|
||||
.putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId))
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun contextDisplayId(context: Context): Int {
|
||||
val activity = context as? android.app.Activity ?: return Display.DEFAULT_DISPLAY
|
||||
return if (Build.VERSION.SDK_INT >= 30) activity.display?.displayId ?: activity.windowManager.defaultDisplay.displayId
|
||||
else activity.windowManager.defaultDisplay.displayId
|
||||
}
|
||||
|
||||
fun setXrActivityVisible(context: Context, visible: Boolean) {
|
||||
|
||||
@@ -42,6 +42,8 @@ object SessionState {
|
||||
@Volatile
|
||||
var running = false
|
||||
@Volatile
|
||||
var activityDisplayId = 0
|
||||
@Volatile
|
||||
var runtimeDriver: String? = null
|
||||
var suspended by mutableStateOf(false)
|
||||
@Volatile var pipActive = false
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
internal object SessionVisibilityPolicy {
|
||||
fun isHidden(
|
||||
activityStarted: Boolean,
|
||||
defaultDisplayOn: Boolean,
|
||||
activityOnDefaultDisplay: Boolean,
|
||||
activityDisplayOn: Boolean,
|
||||
xrActivityVisible: Boolean = false,
|
||||
): Boolean = !sessionHasVisibleSurface(
|
||||
panelVisible = activityStarted,
|
||||
screenOn = if (activityOnDefaultDisplay) defaultDisplayOn else activityDisplayOn,
|
||||
xrVisible = xrActivityVisible,
|
||||
)
|
||||
}
|
||||
@@ -15,7 +15,8 @@ object SettingsReset {
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "stretch16x9", "picturePosition",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
|
||||
@@ -88,6 +88,7 @@ class ModeSettings(
|
||||
val mangoapp: Boolean = true,
|
||||
val steamController: String? = null,
|
||||
val unfoldedControls: Boolean? = null,
|
||||
val unfoldedControlsWithController: Boolean = false,
|
||||
val runSteamAtStartup: Boolean = false,
|
||||
val bootMovie: String? = null,
|
||||
val bootMovieSound: Boolean = true,
|
||||
@@ -140,6 +141,7 @@ class ModeSettingsActions(
|
||||
val onReturnAfterGame: (Boolean) -> Unit = {},
|
||||
val onSteamController: (String) -> Unit = {},
|
||||
val onUnfoldedControls: (Boolean) -> Unit = {},
|
||||
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
|
||||
val onRunSteamAtStartup: (Boolean) -> Unit = {},
|
||||
val onBootMovie: (String) -> Unit = {},
|
||||
val onBootMovieSound: (Boolean) -> Unit = {},
|
||||
@@ -290,6 +292,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
stringResource(R.string.unfolded_controls_hint),
|
||||
s.unfoldedControls, onChange = a.onUnfoldedControls,
|
||||
)
|
||||
if (steam && s.unfoldedControls == true) ToggleRow(
|
||||
host, "unfolded-controls-with-controller", stringResource(R.string.unfolded_controls_with_controller),
|
||||
stringResource(R.string.unfolded_controls_with_controller_hint),
|
||||
s.unfoldedControlsWithController, onChange = a.onUnfoldedControlsWithController,
|
||||
)
|
||||
if (steam) ChoiceRow(
|
||||
host, "back-actions", stringResource(R.string.mode_back), stringResource(SessionPrefs.backActionsOrder(s.backActionsInverted)),
|
||||
listOf(
|
||||
|
||||
@@ -278,6 +278,8 @@ class DrawerActions(
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
val unfoldedControls: Boolean? = null,
|
||||
val onUnfoldedControls: (Boolean) -> Unit = {},
|
||||
val unfoldedControlsWithController: Boolean = false,
|
||||
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
|
||||
val onShareLogs: () -> Unit,
|
||||
val onStop: () -> Unit,
|
||||
val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null,
|
||||
@@ -575,6 +577,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
|
||||
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
|
||||
chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls)
|
||||
if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller",
|
||||
stringResource(R.string.unfolded_controls_with_controller),
|
||||
stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController,
|
||||
chipModifier = focus.track(page, "unfolded-controls-with-controller"),
|
||||
onChange = a.onUnfoldedControlsWithController)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.drawer_latency)) {
|
||||
ToggleRow(host, "low-latency-controller", stringResource(R.string.drawer_low_latency_controller),
|
||||
|
||||
@@ -1159,6 +1159,8 @@
|
||||
<string name="pip_auto">Otomatik olarak PiP moduna geç</string>
|
||||
<string name="unfolded_controls">Açılmış ekrandaki kontroller</string>
|
||||
<string name="unfolded_controls_hint">Cihaz açıkken oyun, Steam Deck dokunmatik yüzeylerinin ve arka tutamaklarının üstünde durur. Katlıyken oyun tam ekran olur.</string>
|
||||
<string name="unfolded_controls_with_controller">Kumanda bağlıyken de göster</string>
|
||||
<string name="unfolded_controls_with_controller_hint">Telefonu tutan kumandalar için, kumanda bağlıyken de açılmış ekrandaki kontrolleri gösterir.</string>
|
||||
<string name="pip_suspended">Askıya alındı</string>
|
||||
<string name="pip_not_ready">Pencere içinde pencere, oturum hazır olduğunda kullanılabilir.</string>
|
||||
<string name="pip_permission">Android ayarlarında DroidDeck için pencere içinde pencereye izin verin.</string>
|
||||
|
||||
@@ -1210,6 +1210,8 @@
|
||||
<string name="pip_auto">Automatically enter PiP</string>
|
||||
<string name="unfolded_controls">Controls on the unfolded screen</string>
|
||||
<string name="unfolded_controls_hint">Unfolded, the game sits above the Steam Deck trackpads and back grips. Folded, the game is full screen.</string>
|
||||
<string name="unfolded_controls_with_controller">Keep them with a controller</string>
|
||||
<string name="unfolded_controls_with_controller_hint">Also show the unfolded controls while a controller is connected, for controllers that hold the phone.</string>
|
||||
<string name="pip_suspended">Suspended</string>
|
||||
<string name="pip_not_ready">Picture in picture is available once the session is ready.</string>
|
||||
<string name="pip_permission">Allow picture in picture for DroidDeck in Android settings.</string>
|
||||
|
||||
@@ -40,6 +40,33 @@ class SessionDisplayTest {
|
||||
assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080))
|
||||
}
|
||||
|
||||
private fun unfoldedWanted(
|
||||
enabled: Boolean = true,
|
||||
controller: Boolean = false,
|
||||
keepWithController: Boolean = false,
|
||||
foldable: Boolean = true,
|
||||
steamDeckPad: Boolean = true,
|
||||
pip: Boolean = false,
|
||||
smallestWidthDp: Int = 700,
|
||||
) = SessionDisplay.unfoldedControlsWanted(enabled, foldable, controller, keepWithController, steamDeckPad, pip,
|
||||
2448, 1848, smallestWidthDp)
|
||||
|
||||
@Test fun unfoldedControlsHideForAControllerUnlessKeptWithOne() {
|
||||
assertTrue(unfoldedWanted())
|
||||
assertFalse(unfoldedWanted(controller = true))
|
||||
assertTrue(unfoldedWanted(controller = true, keepWithController = true))
|
||||
assertTrue(unfoldedWanted(keepWithController = true))
|
||||
}
|
||||
|
||||
@Test fun keepingUnfoldedControlsWithAControllerLeavesTheOtherConditions() {
|
||||
assertFalse(unfoldedWanted(enabled = false, controller = true, keepWithController = true))
|
||||
assertFalse(unfoldedWanted(foldable = false, keepWithController = true))
|
||||
assertFalse(unfoldedWanted(steamDeckPad = false, keepWithController = true))
|
||||
assertFalse(unfoldedWanted(pip = true, keepWithController = true))
|
||||
assertFalse(unfoldedWanted(smallestWidthDp = 599, keepWithController = true))
|
||||
assertFalse(SessionDisplay.unfoldedControlsWanted(true, true, true, true, true, false, 0, 1848, 700))
|
||||
}
|
||||
|
||||
|
||||
@Test fun followScreenKeepsTheWindowShapeAndSkipsTinyWindows() {
|
||||
assertEquals(2520 to 1080, SessionDisplay.resolveChoice(1080 to 2520, SessionDisplay.FOLLOW_SCREEN))
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SessionVisibilityPolicyTest {
|
||||
@Test fun handsetScreenStateControlsActivityOnDefaultDisplay() {
|
||||
assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false))
|
||||
assertTrue(SessionVisibilityPolicy.isHidden(true, false, true, true))
|
||||
}
|
||||
|
||||
@Test fun externalDisplayStateControlsActivityIndependentlyOfHandset() {
|
||||
assertFalse(SessionVisibilityPolicy.isHidden(true, false, false, true))
|
||||
assertTrue(SessionVisibilityPolicy.isHidden(true, true, false, false))
|
||||
}
|
||||
|
||||
@Test fun missingActivityDisplayIsHiddenUntilActivityMoves() {
|
||||
assertTrue(SessionVisibilityPolicy.isHidden(true, true, false, false))
|
||||
assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false))
|
||||
}
|
||||
|
||||
@Test fun stoppedActivityIsHiddenButVisibleXrKeepsSessionVisible() {
|
||||
assertTrue(SessionVisibilityPolicy.isHidden(false, true, true, true))
|
||||
assertFalse(SessionVisibilityPolicy.isHidden(false, false, true, false, xrActivityVisible = true))
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ class SettingsResetTest {
|
||||
|
||||
@Test fun settingsGoBackToTheirDefaults() {
|
||||
SessionPrefs.setTheme(app, "ocean")
|
||||
SessionPrefs.setUnfoldedControlsWithController(app, true)
|
||||
SessionPrefs.setNoXalia(app, false)
|
||||
SessionPrefs.setFpsLimit(app, SessionService.MODE_STEAM, 30)
|
||||
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
|
||||
@@ -45,6 +46,7 @@ class SettingsResetTest {
|
||||
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
|
||||
|
||||
assertEquals("graphite", SessionPrefs.theme(app))
|
||||
assertFalse(SessionPrefs.unfoldedControlsWithController(app))
|
||||
assertTrue(SessionPrefs.noXalia(app))
|
||||
assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM))
|
||||
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
|
||||
|
||||
@@ -22,9 +22,11 @@ through `kwin_wayland_wrapper`. KWin composites in software (QPainter) - the Adr
|
||||
DRM device - so games and emulators from the menu go through `droiddeck-gpu`, and Steam goes back
|
||||
to the app as a Steam session.
|
||||
|
||||
`build-kwin.sh` builds KWin 6.7.5's Wayland executable and library on a native ARM64 runner, using a disposable
|
||||
Arch Linux ARM chroot with every build package signature-checked. The KDE source tarball is pinned
|
||||
by SHA-256 (the same digest in Arch's KWin PKGBUILD); `patches/0001-respect-nested-desktop-scale.patch`
|
||||
`kwin.env` pins the KWin version shared by the build and packaging jobs. `build-kwin.sh` builds that version's
|
||||
Wayland executable and library on a native ARM64 runner, using a disposable
|
||||
Arch Linux ARM chroot with every build package signature-checked. It matches the current KWin package
|
||||
in Arch Linux ARM even when that repository trails KDE's latest release. The source tarball is pinned
|
||||
by SHA-256 from KDE's official source inventory; `patches/0001-respect-nested-desktop-scale.patch`
|
||||
lets Display Settings control the inner desktop scale independently of the outer window size.
|
||||
It keeps layer sizes, pointer/touch coordinates and the cursor in the same physical pixels.
|
||||
The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop script supplies.
|
||||
@@ -32,7 +34,7 @@ The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop sc
|
||||
The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest
|
||||
comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch,
|
||||
executable, library and build package hashes. Corresponding source is
|
||||
https://download.kde.org/stable/plasma/6.7.5/kwin-6.7.5.tar.xz plus the patch in this repository.
|
||||
https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz plus the patch in this repository.
|
||||
|
||||
The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips
|
||||
its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes.
|
||||
|
||||
@@ -3,8 +3,9 @@ set -euo pipefail
|
||||
out=$(realpath -m "${1:?out dir}")
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
[ "$(uname -m)" = aarch64 ] || { echo 'KWin needs a native aarch64 runner' >&2; exit 1; }
|
||||
version=6.7.5
|
||||
source_sha=6baa910b732d93c48c90f9c1cc685cc93d0b8de0cdf138c24192c045bc3a48e2
|
||||
source "$here/kwin.env"
|
||||
version=$DESKTOP_KWIN_VERSION
|
||||
source_sha=4bfaf31e29a8f9fdf231dc3bbb9b09b0ce07cae9fee7a01cfc86425ece796258
|
||||
mirror=https://fl.us.mirror.archlinuxarm.org/aarch64
|
||||
builder=68B3537F39A313B3E574D06777193F152BDBE6A6
|
||||
work=$(mktemp -d)
|
||||
@@ -18,7 +19,11 @@ for repo in core extra alarm; do
|
||||
done
|
||||
touch "$work/runtime.txt"
|
||||
python3 "$here/closure.py" "$work/db" "$work/runtime.txt" "$here/kwin-build-seeds.txt" > "$work/packages.txt"
|
||||
grep -Eq '^extra/kwin-6\.7\.5-[0-9]+-aarch64\.pkg\.tar\.' "$work/packages.txt"
|
||||
kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/packages.txt")
|
||||
case $kwin_package in
|
||||
"extra/kwin-$version"-[0-9]*-aarch64.pkg.tar.*) ;;
|
||||
*) echo "KWin package $kwin_package does not match source KWin $version" >&2; exit 1 ;;
|
||||
esac
|
||||
export work mirror builder here
|
||||
download() {
|
||||
local entry=$1 sum=$2 file=${1#*/}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
set -euo pipefail
|
||||
out=${1:?out dir}
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
source "$here/kwin.env"
|
||||
mirror=${ALARM_MIRROR:-https://fl.us.mirror.archlinuxarm.org/aarch64}
|
||||
case $mirror in https://*) ;; *) echo "ALARM_MIRROR must be https" >&2; exit 1 ;; esac
|
||||
builder=68B3537F39A313B3E574D06777193F152BDBE6A6
|
||||
@@ -36,8 +37,13 @@ done < "$work/pkglist.txt"
|
||||
cp -a "$here/overlay/." "$work/root/"
|
||||
|
||||
if [ -n "${KDE_KWIN_OVERRIDE:-}" ]; then
|
||||
kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/pkglist.txt")
|
||||
case $kwin_package in
|
||||
"extra/kwin-$DESKTOP_KWIN_VERSION"-[0-9]*-aarch64.pkg.tar.*) ;;
|
||||
*) echo "KWin package $kwin_package does not match the built KWin $DESKTOP_KWIN_VERSION" >&2; exit 1 ;;
|
||||
esac
|
||||
install -m 755 "$KDE_KWIN_OVERRIDE/kwin_wayland" "$work/root/usr/bin/kwin_wayland"
|
||||
install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.6.7.5" "$work/root/usr/lib/libkwin.so.6.7.5"
|
||||
install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.$DESKTOP_KWIN_VERSION" "$work/root/usr/lib/libkwin.so.$DESKTOP_KWIN_VERSION"
|
||||
fi
|
||||
|
||||
if [ -d "$work/root/usr/share/locale" ]; then
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DESKTOP_KWIN_VERSION=6.8.0
|
||||
@@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay)
|
||||
- steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme),
|
||||
GPL-3.0.
|
||||
|
||||
- kwin_wayland: KWin 6.7.5, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
|
||||
Corresponding source: https://download.kde.org/stable/plasma/6.7.5/kwin-6.7.5.tar.xz and
|
||||
- kwin_wayland: KWin 6.8.0, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
|
||||
Corresponding source: https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz and
|
||||
https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches
|
||||
(the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package).
|
||||
|
||||
|
||||
@@ -1,78 +1,27 @@
|
||||
--- a/src/backends/wayland/wayland_output.cpp
|
||||
+++ b/src/backends/wayland/wayland_output.cpp
|
||||
@@ -294,6 +294,11 @@
|
||||
}
|
||||
}
|
||||
|
||||
+qreal WaylandOutput::presentationScale() const
|
||||
+{
|
||||
+ return qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ? m_pendingScale : scale();
|
||||
+}
|
||||
+
|
||||
bool WaylandOutput::present(const QList<OutputLayer *> &layersToUpdate, const std::shared_ptr<OutputFrame> &frame)
|
||||
{
|
||||
auto cursorLayers = layersToUpdate | std::views::filter([](OutputLayer *layer) {
|
||||
@@ -312,7 +317,7 @@
|
||||
m_surface->attachBuffer(buffer);
|
||||
m_mapped = true;
|
||||
}
|
||||
- m_viewport->setDestination(QSize(std::round(modeSize().width() / scale()), std::round(modeSize().height() / scale())));
|
||||
+ m_viewport->setDestination(QSize(std::round(modeSize().width() / presentationScale()), std::round(modeSize().height() / presentationScale())));
|
||||
m_surface->setScale(1);
|
||||
// commit the subsurfaces before the main surface
|
||||
for (OutputLayer *layer : layersToUpdate) {
|
||||
@@ -375,9 +380,11 @@
|
||||
next.enabled = props->enabled.value_or(m_state.enabled);
|
||||
next.transform = props->transform.value_or(m_state.transform);
|
||||
next.position = props->pos.value_or(m_state.position);
|
||||
- // intentionally ignored, as it would get overwritten
|
||||
- // with the fractional scale protocol anyways
|
||||
- // next.scale = props->scale.value_or(m_state.scale);
|
||||
+
|
||||
+ if (qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
|
||||
+ next.scale = props->scale.value_or(m_state.scale);
|
||||
+ next.scaleSetting = props->scaleSetting.value_or(m_state.scaleSetting);
|
||||
+ }
|
||||
next.desiredMode = props->desiredMode.value_or(m_state.desiredMode);
|
||||
next.uuid = props->uuid.value_or(m_state.uuid);
|
||||
next.replicationSource = props->replicationSource.value_or(m_state.replicationSource);
|
||||
@@ -466,7 +473,9 @@
|
||||
State next = m_state;
|
||||
next.modes = {mode};
|
||||
next.currentMode = mode;
|
||||
- next.scale = m_pendingScale;
|
||||
+ if (!qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
|
||||
+ next.scale = m_pendingScale;
|
||||
+ }
|
||||
setState(next);
|
||||
|
||||
Q_EMIT m_backend->outputsQueried();
|
||||
--- a/src/backends/wayland/wayland_output.h
|
||||
+++ b/src/backends/wayland/wayland_output.h
|
||||
@@ -93,6 +93,8 @@
|
||||
|
||||
void init(const QSize &pixelSize, qreal scale, bool fullscreen);
|
||||
|
||||
+
|
||||
+ qreal presentationScale() const;
|
||||
bool isReady() const;
|
||||
KWayland::Client::Surface *surface() const;
|
||||
WaylandCursor *cursor() const;
|
||||
diff --git a/src/backends/wayland/wayland_backend.cpp b/src/backends/wayland/wayland_backend.cpp
|
||||
index f43f03d..211ef09 100644
|
||||
--- a/src/backends/wayland/wayland_backend.cpp
|
||||
+++ b/src/backends/wayland/wayland_backend.cpp
|
||||
@@ -107,8 +107,9 @@
|
||||
@@ -106,16 +106,8 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Pointer *pointer, Wayla
|
||||
WaylandOutput *output = m_seat->backend()->findOutput(m_pointer->enteredSurface());
|
||||
Q_ASSERT(output);
|
||||
const auto subsurface = m_seat->backend()->findSubSurface(m_pointer->enteredSurface());
|
||||
- const QPointF absolutePos = output->position() + relativeToSurface
|
||||
- + (subsurface ? subsurface->position() : QPoint());
|
||||
+ const QPointF absolutePos = output->position()
|
||||
+ + (relativeToSurface + (subsurface ? subsurface->position() : QPoint()))
|
||||
+ * output->presentationScale() / output->scale();
|
||||
- // A position in the host window is in the coordinates the panel is driven in, while
|
||||
- // the compositor works in the picture as the user sees it. On a rotated display those
|
||||
- // are not the same, so the position has to be turned back.
|
||||
- const QPointF inPanel = relativeToSurface + (subsurface ? subsurface->position() : QPoint());
|
||||
- // Exactly the size the surface is given in WaylandOutput::present(), rounding and all -
|
||||
- // turning a position needs the bounds it was expressed in, and being off by the
|
||||
- // rounding here shifts the pointer by a little more the further it travels.
|
||||
- const QSizeF panelSize = QSize(std::round(output->modeSize().width() / output->scale()),
|
||||
- std::round(output->modeSize().height() / output->scale()));
|
||||
- const QPointF absolutePos = output->position() + output->transform().inverted().map(inPanel, panelSize);
|
||||
+ const QPointF hostPosition = relativeToSurface + (subsurface ? subsurface->position() : QPoint());
|
||||
+ const QPointF absolutePos = output->mapToOutput(hostPosition);
|
||||
Q_EMIT pointerMotionAbsolute(absolutePos, std::chrono::milliseconds(time), this);
|
||||
});
|
||||
connect(pointer, &Pointer::buttonStateChanged, this, [this](quint32 serial, quint32 time, quint32 button, Pointer::ButtonState nativeState) {
|
||||
@@ -182,7 +183,11 @@
|
||||
@@ -189,7 +181,11 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::RelativePointer *relati
|
||||
, m_relativePointer(relativePointer)
|
||||
{
|
||||
connect(relativePointer, &RelativePointer::relativeMotion, this, [this](const QSizeF &delta, const QSizeF &deltaNonAccelerated, quint64 timestamp) {
|
||||
@@ -84,16 +33,17 @@
|
||||
+ Q_EMIT pointerMotion(sizeToPoint(delta) * factor, sizeToPoint(deltaNonAccelerated) * factor, std::chrono::microseconds(timestamp), this);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -199,13 +204,19 @@
|
||||
|
||||
@@ -206,13 +202,21 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Touch *touch, WaylandSe
|
||||
connect(touch, &Touch::sequenceStarted, this, [this](TouchPoint *tp) {
|
||||
auto o = m_seat->backend()->findOutput(tp->surface());
|
||||
Q_ASSERT(o);
|
||||
- const QPointF position = o->position() + tp->position();
|
||||
+ const auto subsurface = m_seat->backend()->findSubSurface(tp->surface());
|
||||
+ const QPointF position = o->position()
|
||||
+ + (tp->position() + (subsurface ? subsurface->position() : QPoint()))
|
||||
+ * o->presentationScale() / o->scale();
|
||||
+ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint());
|
||||
+ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")
|
||||
+ ? o->mapToOutput(hostPosition)
|
||||
+ : o->position() + tp->position();
|
||||
Q_EMIT touchDown(tp->id(), position, std::chrono::milliseconds(tp->time()), this);
|
||||
});
|
||||
connect(touch, &Touch::pointAdded, this, [this](TouchPoint *tp) {
|
||||
@@ -101,27 +51,46 @@
|
||||
Q_ASSERT(o);
|
||||
- const QPointF position = o->position() + tp->position();
|
||||
+ const auto subsurface = m_seat->backend()->findSubSurface(tp->surface());
|
||||
+ const QPointF position = o->position()
|
||||
+ + (tp->position() + (subsurface ? subsurface->position() : QPoint()))
|
||||
+ * o->presentationScale() / o->scale();
|
||||
+ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint());
|
||||
+ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")
|
||||
+ ? o->mapToOutput(hostPosition)
|
||||
+ : o->position() + tp->position();
|
||||
Q_EMIT touchDown(tp->id(), position, std::chrono::milliseconds(tp->time()), this);
|
||||
});
|
||||
connect(touch, &Touch::pointRemoved, this, [this](TouchPoint *tp) {
|
||||
@@ -214,7 +225,10 @@
|
||||
@@ -221,7 +225,11 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Touch *touch, WaylandSe
|
||||
connect(touch, &Touch::pointMoved, this, [this](TouchPoint *tp) {
|
||||
auto o = m_seat->backend()->findOutput(tp->surface());
|
||||
Q_ASSERT(o);
|
||||
- const QPointF position = o->position() + tp->position();
|
||||
+ const auto subsurface = m_seat->backend()->findSubSurface(tp->surface());
|
||||
+ const QPointF position = o->position()
|
||||
+ + (tp->position() + (subsurface ? subsurface->position() : QPoint()))
|
||||
+ * o->presentationScale() / o->scale();
|
||||
+ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint());
|
||||
+ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")
|
||||
+ ? o->mapToOutput(hostPosition)
|
||||
+ : o->position() + tp->position();
|
||||
Q_EMIT touchMotion(tp->id(), position, std::chrono::milliseconds(tp->time()), this);
|
||||
});
|
||||
}
|
||||
diff --git a/src/backends/wayland/wayland_egl_backend.cpp b/src/backends/wayland/wayland_egl_backend.cpp
|
||||
index 0c03222..c587db5 100644
|
||||
--- a/src/backends/wayland/wayland_egl_backend.cpp
|
||||
+++ b/src/backends/wayland/wayland_egl_backend.cpp
|
||||
@@ -232,7 +232,9 @@ bool WaylandEglCursorLayer::endFrame(const Region &renderedDeviceRegion, const R
|
||||
wl_buffer *buffer = m_backend->backend()->importBuffer(m_buffer->buffer());
|
||||
Q_ASSERT(buffer);
|
||||
|
||||
- static_cast<WaylandOutput *>(m_output.get())->cursor()->update(buffer, m_buffer->buffer()->size() / m_output->scale(), (hotspot() / m_output->scale()).toPoint());
|
||||
+ auto output = static_cast<WaylandOutput *>(m_output.get());
|
||||
+ output->cursor()->update(buffer, m_buffer->buffer()->size() / output->presentationScale(),
|
||||
+ (hotspot() / output->presentationScale()).toPoint());
|
||||
|
||||
EGLNativeFence releaseFence{m_backend->eglDisplayObject()};
|
||||
m_swapchain->release(m_buffer, releaseFence.takeFileDescriptor());
|
||||
diff --git a/src/backends/wayland/wayland_layer.cpp b/src/backends/wayland/wayland_layer.cpp
|
||||
index 311be7f..f91a3fb 100644
|
||||
--- a/src/backends/wayland/wayland_layer.cpp
|
||||
+++ b/src/backends/wayland/wayland_layer.cpp
|
||||
@@ -95,7 +95,7 @@
|
||||
@@ -95,7 +95,7 @@ void WaylandLayer::commit(PresentationMode presentationMode)
|
||||
// this is a bit annoying, we need a new Wayland protocol
|
||||
// to do this properly with fractional scaling. Until we
|
||||
// have that, it may cause blurriness in some cases!
|
||||
@@ -130,29 +99,74 @@
|
||||
if (m_viewport) {
|
||||
m_viewport->setSource(sourceRect());
|
||||
m_viewport->setDestination(logicalTarget.size());
|
||||
--- a/src/backends/wayland/wayland_qpainter_backend.cpp
|
||||
+++ b/src/backends/wayland/wayland_qpainter_backend.cpp
|
||||
@@ -124,7 +124,9 @@
|
||||
wl_buffer *buffer = static_cast<WaylandOutput *>(m_output.get())->backend()->importBuffer(m_back->buffer());
|
||||
Q_ASSERT(buffer);
|
||||
|
||||
- static_cast<WaylandOutput *>(m_output.get())->cursor()->update(buffer, m_back->buffer()->size() / m_output->scale(), hotspot().toPoint());
|
||||
+ auto output = static_cast<WaylandOutput *>(m_output.get());
|
||||
+ output->cursor()->update(buffer, m_back->buffer()->size() / output->presentationScale(),
|
||||
+ (hotspot() * output->scale() / output->presentationScale()).toPoint());
|
||||
m_swapchain->release(m_back);
|
||||
return true;
|
||||
diff --git a/src/backends/wayland/wayland_output.cpp b/src/backends/wayland/wayland_output.cpp
|
||||
index 1543058..a22d974 100644
|
||||
--- a/src/backends/wayland/wayland_output.cpp
|
||||
+++ b/src/backends/wayland/wayland_output.cpp
|
||||
@@ -314,7 +314,7 @@ std::expected<void, OutputError> WaylandOutput::present(const QList<OutputLayer
|
||||
m_surface->attachBuffer(buffer);
|
||||
m_mapped = true;
|
||||
}
|
||||
- const Rect rect(QPoint(), QSize(std::round(modeSize().width() / scale()), std::round(modeSize().height() / scale())));
|
||||
+ const Rect rect(QPoint(), QSize(std::round(modeSize().width() / presentationScale()), std::round(modeSize().height() / presentationScale())));
|
||||
m_xdgShellSurface->setWindowGeometry(rect);
|
||||
m_viewport->setDestination(rect.size());
|
||||
m_surface->setScale(1);
|
||||
@@ -379,9 +379,10 @@ void WaylandOutput::applyChanges(const OutputConfiguration &config)
|
||||
next.enabled = props->enabled.value_or(m_state.enabled);
|
||||
next.transform = props->transform.value_or(m_state.transform);
|
||||
next.position = props->pos.value_or(m_state.position);
|
||||
- // intentionally ignored, as it would get overwritten
|
||||
- // with the fractional scale protocol anyways
|
||||
- // next.scale = props->scale.value_or(m_state.scale);
|
||||
+ if (qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
|
||||
+ next.scale = props->scale.value_or(m_state.scale);
|
||||
+ next.scaleSetting = props->scaleSetting.value_or(m_state.scaleSetting);
|
||||
+ }
|
||||
next.desiredMode = props->desiredMode.value_or(m_state.desiredMode);
|
||||
next.uuid = props->uuid.value_or(m_state.uuid);
|
||||
next.replicationSource = props->replicationSource.value_or(m_state.replicationSource);
|
||||
@@ -397,6 +398,19 @@ void WaylandOutput::applyChanges(const OutputConfiguration &config)
|
||||
setState(next);
|
||||
}
|
||||
--- a/src/backends/wayland/wayland_egl_backend.cpp
|
||||
+++ b/src/backends/wayland/wayland_egl_backend.cpp
|
||||
@@ -202,7 +202,9 @@
|
||||
wl_buffer *buffer = m_backend->backend()->importBuffer(m_buffer->buffer());
|
||||
Q_ASSERT(buffer);
|
||||
|
||||
- static_cast<WaylandOutput *>(m_output.get())->cursor()->update(buffer, m_buffer->buffer()->size() / m_output->scale(), (hotspot() / m_output->scale()).toPoint());
|
||||
+ auto output = static_cast<WaylandOutput *>(m_output.get());
|
||||
+ output->cursor()->update(buffer, m_buffer->buffer()->size() / output->presentationScale(),
|
||||
+ (hotspot() / output->presentationScale()).toPoint());
|
||||
|
||||
EGLNativeFence releaseFence{m_backend->eglDisplayObject()};
|
||||
m_swapchain->release(m_buffer, releaseFence.takeFileDescriptor());
|
||||
|
||||
+qreal WaylandOutput::presentationScale() const
|
||||
+{
|
||||
+ return qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ? m_pendingScale : scale();
|
||||
+}
|
||||
+
|
||||
+QPointF WaylandOutput::mapToOutput(const QPointF &hostPosition) const
|
||||
+{
|
||||
+ const QPointF inPanel = hostPosition * presentationScale() / scale();
|
||||
+ const QSizeF panelSize = QSize(std::round(modeSize().width() / scale()),
|
||||
+ std::round(modeSize().height() / scale()));
|
||||
+ return position() + transform().inverted().map(inPanel, panelSize);
|
||||
+}
|
||||
+
|
||||
bool WaylandOutput::isReady() const
|
||||
{
|
||||
return m_ready;
|
||||
@@ -472,7 +486,9 @@ void WaylandOutput::applyConfigure(const QSize &size, quint32 serial)
|
||||
State next = m_state;
|
||||
next.modes = {mode};
|
||||
next.currentMode = mode;
|
||||
- next.scale = m_pendingScale;
|
||||
+ if (!qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
|
||||
+ next.scale = m_pendingScale;
|
||||
+ }
|
||||
setState(next);
|
||||
|
||||
Q_EMIT m_backend->outputsQueried();
|
||||
diff --git a/src/backends/wayland/wayland_output.h b/src/backends/wayland/wayland_output.h
|
||||
index dab061b..c019577 100644
|
||||
--- a/src/backends/wayland/wayland_output.h
|
||||
+++ b/src/backends/wayland/wayland_output.h
|
||||
@@ -92,6 +92,8 @@ public:
|
||||
|
||||
void init(const QSize &pixelSize, qreal scale, bool fullscreen);
|
||||
|
||||
+ qreal presentationScale() const;
|
||||
+ QPointF mapToOutput(const QPointF &hostPosition) const;
|
||||
bool isReady() const;
|
||||
KWayland::Client::Surface *surface() const;
|
||||
WaylandCursor *cursor() const;
|
||||
Executable
+287
@@ -0,0 +1,287 @@
|
||||
#!/usr/bin/env bash
|
||||
# Smoke test of a DroidDeck build on a real device, over plain adb (no python, no root).
|
||||
#
|
||||
# What it does, in order, and restores afterwards:
|
||||
# 1. prints the device (model, Android, kernel, page size, SoC);
|
||||
# 2. installs --apk when given and launches the app;
|
||||
# 3. checks that the app starts and that nothing in the crash buffer belongs to it;
|
||||
# 4. changes the display density and the window size and checks the app keeps its process
|
||||
# (and does not recreate the activity that is on top);
|
||||
# 5. on a foldable cycles the device state (half-opened, and with --closed also closed) through
|
||||
# `cmd device_state`, then puts the original state back;
|
||||
# 6. reads the newest session folder of a debug build: first frame, last frame rate, the
|
||||
# memory page size and the last process exits.
|
||||
#
|
||||
# Usage: tools/device-smoke.sh [--serial SERIAL] [--apk FILE] [--pkg PACKAGE]
|
||||
# [--no-density] [--no-size] [--no-fold] [--closed]
|
||||
# Exit status: 0 when no check failed, 1 when one did, 2 for a usage or device problem.
|
||||
#
|
||||
# Not a replacement for tools/droiddeck-scenario, which drives a game through the agent bridge;
|
||||
# this covers what that does not: display changes and foldable states.
|
||||
set -u
|
||||
export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*'
|
||||
|
||||
pkg=com.droiddeck.launcher
|
||||
serial=${ANDROID_SERIAL:-}
|
||||
apk=
|
||||
do_density=1
|
||||
do_size=1
|
||||
do_fold=1
|
||||
do_closed=0
|
||||
adb_bin=${ADB:-adb}
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--serial) [ $# -ge 2 ] || { echo "--serial needs a value" >&2; exit 2; }; serial=$2; shift ;;
|
||||
--apk) [ $# -ge 2 ] || { echo "--apk needs a value" >&2; exit 2; }; apk=$2; shift ;;
|
||||
--pkg) [ $# -ge 2 ] || { echo "--pkg needs a value" >&2; exit 2; }; pkg=$2; shift ;;
|
||||
--no-density) do_density=0 ;;
|
||||
--no-size) do_size=0 ;;
|
||||
--no-fold) do_fold=0 ;;
|
||||
--closed) do_closed=1 ;;
|
||||
-h|--help) sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
|
||||
*) echo "unknown option: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
adb_cmd=("$adb_bin")
|
||||
[ -n "$serial" ] && adb_cmd+=(-s "$serial")
|
||||
A() {
|
||||
local out rc
|
||||
out=$("${adb_cmd[@]}" "$@" 2>&1); rc=$?
|
||||
[ -z "$out" ] || printf '%s\n' "$out" | tr -d '\r'
|
||||
return $rc
|
||||
}
|
||||
sh_() {
|
||||
local command= arg
|
||||
for arg in "$@"; do command+="'${arg//\'/\'\\\'\'}' "; done
|
||||
A shell "$command"
|
||||
}
|
||||
|
||||
pass=0 fail=0 skip=0
|
||||
ok() { echo " PASS $*"; pass=$((pass + 1)); }
|
||||
bad() { echo " FAIL $*"; fail=$((fail + 1)); }
|
||||
note() { echo " SKIP $*"; skip=$((skip + 1)); }
|
||||
head_() { printf '\n== %s\n' "$*"; }
|
||||
|
||||
state=$(A get-state)
|
||||
if [ "$state" != "device" ]; then
|
||||
echo "no authorized device (adb get-state: $state)" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
density_snapshot=$(sh_ wm density) || density_snapshot=
|
||||
size_snapshot=$(sh_ wm size) || size_snapshot=
|
||||
orig_density=$(echo "$density_snapshot" | sed -n 's/.*Physical density: \([0-9]*\).*/\1/p' | head -1)
|
||||
override_density=$(echo "$density_snapshot" | sed -n 's/.*Override density: \([0-9]*\).*/\1/p' | head -1)
|
||||
override_size=$(echo "$size_snapshot" | sed -n 's/.*Override size: \([0-9]*x[0-9]*\).*/\1/p' | head -1)
|
||||
ds=$(sh_ cmd device_state state 2>/dev/null)
|
||||
orig_state=$(echo "$ds" | sed -n "s/.*Committed state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1)
|
||||
pre_override=$(echo "$ds" | sed -n "s/.*Override state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1)
|
||||
|
||||
density_changed=0 size_changed=0 fold_changed=0
|
||||
wm_override() { sed -n "s/.*Override $1: \\([0-9x]*\\).*/\\1/p" | head -1; }
|
||||
restore_density() {
|
||||
sh_ wm density "${override_density:-reset}" >/dev/null || return 1
|
||||
local current
|
||||
current=$(sh_ wm density) || return 1
|
||||
echo "$current" | grep -q 'Physical density:' || return 1
|
||||
[ "$(echo "$current" | wm_override density)" = "$override_density" ]
|
||||
}
|
||||
restore_size() {
|
||||
sh_ wm size "${override_size:-reset}" >/dev/null || return 1
|
||||
local current
|
||||
current=$(sh_ wm size) || return 1
|
||||
echo "$current" | grep -q 'Physical size:' || return 1
|
||||
[ "$(echo "$current" | wm_override size)" = "$override_size" ]
|
||||
}
|
||||
# An override that was already in place (a test lab pins one) is put back; otherwise the request is cancelled.
|
||||
restore_fold() { if [ -n "$pre_override" ]; then sh_ cmd device_state state "$pre_override" >/dev/null; else sh_ cmd device_state state reset >/dev/null; fi; }
|
||||
|
||||
restore() {
|
||||
local failed=0
|
||||
if [ "$density_changed" = 1 ]; then
|
||||
if restore_density; then density_changed=0; else bad "could not restore display density"; failed=1; fi
|
||||
fi
|
||||
if [ "$size_changed" = 1 ]; then
|
||||
if restore_size; then size_changed=0; else bad "could not restore window size"; failed=1; fi
|
||||
fi
|
||||
if [ "$fold_changed" = 1 ]; then
|
||||
if restore_fold; then fold_changed=0; else bad "could not restore fold override"; failed=1; fi
|
||||
fi
|
||||
return "$failed"
|
||||
}
|
||||
finish() {
|
||||
local status=$?
|
||||
restore || status=1
|
||||
printf '\n%d passed, %d failed, %d skipped\n' "$pass" "$fail" "$skip"
|
||||
[ "$fail" = 0 ] || status=1
|
||||
exit "$status"
|
||||
}
|
||||
trap finish EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
top_activity() {
|
||||
sh_ dumpsys activity activities 2>/dev/null | sed -n 's/.*topResumedActivity=ActivityRecord{[^ ]* u[0-9]* \([^ ]*\) .*/\1/p' | head -1
|
||||
}
|
||||
app_pid() { sh_ pidof "$pkg" | awk '{print $1}'; }
|
||||
app_crashes() {
|
||||
local out pat
|
||||
out=$(sh_ logcat -b crash -d) || return 1
|
||||
pat=$(printf '%s' "$pkg" | sed 's/[.[\*^$]/\\&/g')
|
||||
printf '%s\n' "$out" | grep -c -E "(Process: |Cmdline: |>>> )$pat([ ,<:]|$)" || true
|
||||
}
|
||||
relaunches_of() { # $1 = activity class fragment
|
||||
sh_ logcat -b events -d 2>/dev/null | grep -E 'wm_(relaunch|destroy|create)_activity' | grep -c "$1"
|
||||
}
|
||||
|
||||
head_ "Device"
|
||||
echo " model $(sh_ getprop ro.product.manufacturer) $(sh_ getprop ro.product.model)"
|
||||
echo " android $(sh_ getprop ro.build.version.release) (API $(sh_ getprop ro.build.version.sdk)), One UI $(sh_ getprop ro.build.version.oneui)"
|
||||
echo " kernel $(sh_ uname -r)"
|
||||
page=$(sh_ getconf PAGE_SIZE)
|
||||
echo " page size $page"
|
||||
echo " soc $(sh_ getprop ro.soc.manufacturer) $(sh_ getprop ro.soc.model) ($(sh_ getprop ro.board.platform))"
|
||||
echo " gpu $(sh_ cat /sys/class/kgsl/kgsl-3d0/gpu_model 2>/dev/null)"
|
||||
echo " display $(sh_ wm size | tr '\n' ' ') $(sh_ wm density | tr '\n' ' ')"
|
||||
[ "$page" = 4096 ] || [ "$page" = 16384 ] && ok "page size is $page" || bad "page size reads '$page'"
|
||||
|
||||
head_ "Install and launch"
|
||||
sh_ logcat -b crash -c >/dev/null
|
||||
sh_ logcat -b events -c >/dev/null
|
||||
if [ -n "$apk" ]; then
|
||||
r=$(A install -r -t "$apk" | tail -1)
|
||||
case $r in *Success*) ok "installed $(basename "$apk")" ;; *) bad "install: $r"; exit 1 ;; esac
|
||||
fi
|
||||
packages=$(sh_ pm list packages "$pkg") || { echo "could not query installed packages" >&2; exit 2; }
|
||||
if ! printf '%s\n' "$packages" | grep -Fxq "package:$pkg"; then echo "package $pkg is not installed" >&2; exit 2; fi
|
||||
if ! launch=$(sh_ am start -n "$pkg/.MainActivity") || printf '%s\n' "$launch" | grep -q '^Error'; then
|
||||
bad "could not launch $pkg/.MainActivity"
|
||||
fi
|
||||
sleep 6
|
||||
pid=$(app_pid)
|
||||
[ -n "$pid" ] && ok "process running (pid $pid)" || bad "the app has no process after launch"
|
||||
t=$(top_activity)
|
||||
case $t in
|
||||
"$pkg"/*|*permissioncontroller*|*GrantPermissions*) ok "top activity: $t" ;;
|
||||
*) bad "top activity is '$t'" ;;
|
||||
esac
|
||||
if c=$(app_crashes); then
|
||||
[ "${c:-0}" = 0 ] && ok "nothing in the crash buffer belongs to the app" || bad "$c crash entries mention the app"
|
||||
else
|
||||
bad "could not read the crash buffer"
|
||||
fi
|
||||
|
||||
if [ "$do_density" = 1 ] && [ -n "$orig_density" ]; then
|
||||
head_ "Density change"
|
||||
target=$((orig_density * 5 / 4))
|
||||
before=$(top_activity); pid0=$(app_pid)
|
||||
sh_ logcat -b events -c >/dev/null
|
||||
density_changed=1
|
||||
wm_status=0
|
||||
sh_ wm density "$target" >/dev/null || wm_status=$?
|
||||
sleep 6
|
||||
applied=$(sh_ wm density) || wm_status=1
|
||||
after=$(top_activity); pid1=$(app_pid)
|
||||
if [ "$wm_status" -ne 0 ] || [ "$(echo "$applied" | wm_override density)" != "$target" ]; then
|
||||
bad "wm density failed"
|
||||
else
|
||||
if [ -n "$pid1" ] && [ "$pid0" = "$pid1" ]; then
|
||||
ok "same process after $orig_density -> $target dpi"
|
||||
else
|
||||
bad "process changed ($pid0 -> $pid1)"
|
||||
fi
|
||||
case $before in "$pkg"/*)
|
||||
n=$(relaunches_of "${before#*/}")
|
||||
[ "${n:-0}" = 0 ] && ok "$before was not recreated" || bad "$before was recreated ${n}x"
|
||||
[ "$after" = "$before" ] && ok "same top activity after the change" || bad "top activity changed ($before -> $after)"
|
||||
;; *) note "top activity was not the app ($before)" ;; esac
|
||||
fi
|
||||
if restore_density; then
|
||||
density_changed=0
|
||||
else
|
||||
bad "could not restore display density"
|
||||
fi
|
||||
sleep 3
|
||||
elif [ "$do_density" = 1 ]; then
|
||||
note "could not read the original display density"
|
||||
fi
|
||||
|
||||
if [ "$do_size" = 1 ]; then
|
||||
head_ "Window size change"
|
||||
phys=$(echo "$size_snapshot" | sed -n 's/.*Physical size: \([0-9]*\)x\([0-9]*\).*/\1 \2/p' | head -1)
|
||||
set -- $phys
|
||||
if [ -n "${1:-}" ]; then
|
||||
w=$(( ($2 * 2 / 3) / 2 * 2 )); h=$1 # a narrower, taller window, like a cover screen
|
||||
pid0=$(app_pid)
|
||||
size_changed=1
|
||||
wm_status=0
|
||||
sh_ wm size "${w}x${h}" >/dev/null || wm_status=$?
|
||||
sleep 6
|
||||
applied=$(sh_ wm size) || wm_status=1
|
||||
pid1=$(app_pid)
|
||||
if [ "$wm_status" -ne 0 ] || [ "$(echo "$applied" | wm_override size)" != "${w}x${h}" ]; then
|
||||
bad "wm size failed"
|
||||
elif [ -n "$pid1" ] && [ "$pid0" = "$pid1" ]; then
|
||||
ok "same process at ${w}x${h}"
|
||||
else
|
||||
bad "process changed ($pid0 -> $pid1)"
|
||||
fi
|
||||
if restore_size; then
|
||||
size_changed=0
|
||||
else
|
||||
bad "could not restore window size"
|
||||
fi
|
||||
sleep 3
|
||||
else
|
||||
note "could not read the physical size"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$do_fold" = 1 ]; then
|
||||
head_ "Foldable states"
|
||||
states=$(sh_ cmd device_state print-states 2>/dev/null)
|
||||
if ! echo "$states" | grep -q "identifier"; then
|
||||
note "no device_state service (not a foldable, or not permitted)"
|
||||
elif [ -z "$orig_state" ]; then
|
||||
note "could not read the current device_state identifier"
|
||||
else
|
||||
id_of() { echo "$states" | sed -n "s/.*identifier=\([0-9]*\), name='$1'.*/\1/p" | head -1; }
|
||||
half=$(id_of HALF_OPENED); closed=$(id_of CLOSED)
|
||||
cycle() { # $1 name $2 id
|
||||
pid0=$(app_pid)
|
||||
fold_changed=1
|
||||
sh_ cmd device_state state "$2" >/dev/null; sleep 8
|
||||
got=$(sh_ cmd device_state state | sed -n "s/.*Committed state: DeviceState{identifier=[0-9]*, name='\([A-Z_]*\)'.*/\1/p" | head -1)
|
||||
pid1=$(app_pid)
|
||||
[ "$got" = "$1" ] && ok "device state is $1" || note "asked for $1, committed '$got'"
|
||||
[ -n "$pid1" ] && [ "$pid0" = "$pid1" ] && ok "same process in $1" || bad "process changed in $1 ($pid0 -> $pid1)"
|
||||
restore_fold; sleep 6
|
||||
}
|
||||
if [ -n "$half" ]; then cycle HALF_OPENED "$half"; else note "no HALF_OPENED state"; fi
|
||||
if [ "$do_closed" = 1 ] && [ -n "$closed" ]; then
|
||||
cycle CLOSED "$closed"
|
||||
note "CLOSED turns the screens off: the session pauses (Background behaviour), Resume it from the app"
|
||||
fi
|
||||
got=$(sh_ cmd device_state state | sed -n "s/.*Committed state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1)
|
||||
[ "$got" = "$orig_state" ] && ok "device state restored ($orig_state)" || bad "device state is $got, was $orig_state"
|
||||
fi
|
||||
fi
|
||||
|
||||
head_ "Session log (debug builds)"
|
||||
dir=$(sh_ run-as "$pkg" ls -t files/logs 2>/dev/null | head -1)
|
||||
if [ -z "$dir" ] || echo "$dir" | grep -q -i "not debuggable\|unknown package"; then
|
||||
note "no readable session folder (release build, or no session has run)"
|
||||
else
|
||||
echo " newest session $dir"
|
||||
ev=$(sh_ run-as "$pkg" cat "files/logs/$dir/events.jsonl" 2>/dev/null)
|
||||
echo "$ev" | grep -q '"frame.first"' && ok "first frame was drawn" || note "no frame.first in $dir"
|
||||
echo "$ev" | grep -q '"session.failed"' && bad "session.failed: $(echo "$ev" | grep '"session.failed"' | tail -1 | cut -c1-160)"
|
||||
fps=$(sh_ run-as "$pkg" cat "files/logs/$dir/app.log" 2>/dev/null | grep 'last 10 s:' | tail -1 | sed 's/.*last 10 s: //' | cut -c1-70)
|
||||
[ -n "$fps" ] && echo " last stats $fps"
|
||||
sh_ run-as "$pkg" cat "files/logs/$dir/device.txt" 2>/dev/null | grep -E 'Memory page size|^Kernel' | sed 's/^/ report /'
|
||||
fi
|
||||
|
||||
[ "$fail" = 0 ]
|
||||
@@ -3,7 +3,7 @@ set -u
|
||||
export HOME=${HOME:-/root}
|
||||
mode=${1:-desktop}
|
||||
shift || true
|
||||
step() { echo "== STEP $(date -u +%H:%M:%S) $*"; }
|
||||
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
|
||||
steam_setup_failed() {
|
||||
echo "== steam: the Steam client could not be set up (status $1)"
|
||||
[ -z "${BL_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$BL_STEAM_EXIT_FILE"
|
||||
|
||||
@@ -182,6 +182,20 @@ SWITCH_JS = r"""
|
||||
})()
|
||||
""".replace("__BINDING__", SWITCH_BINDING)
|
||||
SESSION_SELECT = "/usr/bin/steamos-session-select"
|
||||
# Steam opens its Steam Controller welcome tour at every start while the client setting
|
||||
# controller_show_ibex_tour (CMsgClientSettings field 140014) is on, and only a finished tour turns it
|
||||
# off; closing it leaves it on. The app's pad is an emulated controller, so the tour never applies.
|
||||
# A pending firmware update still opens Steam's updater, which checks the update priority instead.
|
||||
TOUR_JS = r"""
|
||||
(() => {
|
||||
let key = 140014 * 8;
|
||||
const bytes = [];
|
||||
while (key > 127) { bytes.push((key & 127) | 128); key = Math.floor(key / 128); }
|
||||
bytes.push(key, 0);
|
||||
SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
|
||||
return "off";
|
||||
})()
|
||||
"""
|
||||
VR_BINDING = "droiddeckLaunchSteamVr"
|
||||
VR_HELPER = "/usr/local/bin/droiddeck-steamvr"
|
||||
VR_JS = r"""
|
||||
@@ -528,6 +542,11 @@ class Helper:
|
||||
page.call("Runtime.addBinding", {"name": BINDING})
|
||||
page.call("Runtime.addBinding", {"name": VR_BINDING})
|
||||
page.evaluate(VR_JS)
|
||||
try:
|
||||
page.evaluate(TOUR_JS)
|
||||
except RuntimeError:
|
||||
# The optional tour setting must not block the compat bridge.
|
||||
pass
|
||||
if not self.steamos:
|
||||
page.call("Runtime.addBinding", {"name": SWITCH_BINDING})
|
||||
page.evaluate(SWITCH_JS)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from check_authorship import BOT, COAUTHOR, check_revision
|
||||
|
||||
|
||||
def main():
|
||||
hook, *args = sys.argv[1:]
|
||||
payload = sys.stdin.buffer.read() if hook == "pre-push" else None
|
||||
if hook == "pre-push":
|
||||
checked = set()
|
||||
for line in payload.decode().splitlines():
|
||||
local_ref, local_sha, _, _ = line.split()
|
||||
if local_sha == "0" * 40 or local_sha in checked:
|
||||
continue
|
||||
checked.add(local_sha)
|
||||
_, errors = check_revision(local_sha)
|
||||
if errors:
|
||||
print("\n".join(errors), file=sys.stderr)
|
||||
return 1
|
||||
else:
|
||||
identity = subprocess.check_output(["git", "var", "GIT_AUTHOR_IDENT"], text=True)
|
||||
if BOT.search(identity):
|
||||
print("Bot commit author is forbidden: " + identity.strip(), file=sys.stderr)
|
||||
return 1
|
||||
message = Path(args[0])
|
||||
original = message.read_text(encoding="utf-8")
|
||||
cleaned = "".join(line for line in original.splitlines(keepends=True)
|
||||
if not (COAUTHOR.match(line) and BOT.search(line)))
|
||||
if cleaned != original:
|
||||
message.write_text(cleaned, encoding="utf-8")
|
||||
print("Removed bot co-author trailers; human credits preserved.", file=sys.stderr)
|
||||
legacy = Path(__file__).with_name("legacy-" + hook)
|
||||
if legacy.exists() and os.access(legacy, os.X_OK):
|
||||
return subprocess.run([str(legacy), *args], input=payload).returncode
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reject bot authors and bot co-author trailers without executing reviewed code."""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
BOT = re.compile(
|
||||
r"Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|"
|
||||
r"Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\]|github-actions|"
|
||||
r"dependabot|renovate(?:\[bot\])?",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
COAUTHOR = re.compile(r"^\s*Co-authored-by\s*:", re.IGNORECASE)
|
||||
|
||||
|
||||
def commit_violations(commit, raw):
|
||||
header, separator, message = raw.partition(b"\n\n")
|
||||
if not separator:
|
||||
return [f"{commit}: invalid commit object"]
|
||||
authors = [line[7:] for line in header.splitlines() if line.startswith(b"author ")]
|
||||
if len(authors) != 1:
|
||||
return [f"{commit}: expected one author"]
|
||||
identity = authors[0].decode("utf-8", errors="replace")
|
||||
errors = []
|
||||
if BOT.search(identity):
|
||||
errors.append(f"{commit}: bot author: {identity}")
|
||||
for line in message.decode("utf-8", errors="replace").splitlines():
|
||||
if COAUTHOR.match(line) and BOT.search(line):
|
||||
errors.append(f"{commit}: bot co-author: {line.strip()}")
|
||||
return errors
|
||||
|
||||
|
||||
def event_violations(event):
|
||||
pr = event.get("pull_request", {})
|
||||
user = pr.get("user", {})
|
||||
errors = []
|
||||
if user.get("type") == "Bot" or BOT.search(user.get("login", "")):
|
||||
errors.append("pull request: bot authorship is forbidden")
|
||||
for field in ("title", "body"):
|
||||
for line in (pr.get(field) or "").splitlines():
|
||||
if COAUTHOR.match(line) and BOT.search(line):
|
||||
errors.append(f"pull request {field}: bot co-author trailer")
|
||||
return errors
|
||||
|
||||
|
||||
def check_revision(revision):
|
||||
commits = subprocess.check_output(["git", "rev-list", revision], text=True).splitlines()
|
||||
errors = []
|
||||
with subprocess.Popen(["git", "cat-file", "--batch"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as process:
|
||||
for commit in commits:
|
||||
process.stdin.write((commit + "\n").encode("ascii"))
|
||||
process.stdin.flush()
|
||||
descriptor = process.stdout.readline().split()
|
||||
if len(descriptor) != 3 or descriptor[1] != b"commit":
|
||||
raise RuntimeError(f"Cannot read commit {commit}")
|
||||
size = int(descriptor[2])
|
||||
raw = process.stdout.read(size)
|
||||
if len(raw) != size or process.stdout.read(1) != b"\n":
|
||||
raise RuntimeError(f"Truncated commit {commit}")
|
||||
errors.extend(commit_violations(commit, raw))
|
||||
process.stdin.close()
|
||||
if process.wait() != 0:
|
||||
raise RuntimeError("git cat-file failed")
|
||||
return commits, errors
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("revision")
|
||||
parser.add_argument("--event")
|
||||
args = parser.parse_args()
|
||||
commits, errors = check_revision(args.revision)
|
||||
if args.event:
|
||||
with open(args.event, encoding="utf-8") as source:
|
||||
errors.extend(event_violations(json.load(source)))
|
||||
for error in errors:
|
||||
print(f"::error::{error}", file=sys.stderr)
|
||||
if errors:
|
||||
return 1
|
||||
print(f"Human authorship verified for {len(commits)} commits.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install shared worktree hooks while preserving existing executable hooks."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
MARKER = "# DroidDeck human authorship hook"
|
||||
|
||||
|
||||
def install():
|
||||
common = Path(subprocess.check_output(["git", "rev-parse", "--git-common-dir"], text=True).strip()).resolve()
|
||||
configured = subprocess.run(["git", "config", "--get", "core.hooksPath"], capture_output=True, text=True)
|
||||
hooks = Path(configured.stdout.strip()).resolve() if configured.returncode == 0 else common / "hooks"
|
||||
target = common / "authorship-hooks"
|
||||
hooks.mkdir(parents=True, exist_ok=True)
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
for name in ("check_authorship.py", "authorship_hook.py"):
|
||||
shutil.copyfile(Path(__file__).with_name(name), target / name)
|
||||
for name in ("prepare-commit-msg", "commit-msg", "pre-push"):
|
||||
path = hooks / name
|
||||
if path.exists() and MARKER not in path.read_text(errors="replace"):
|
||||
legacy = target / ("legacy-" + name)
|
||||
if legacy.exists():
|
||||
raise RuntimeError(f"Refusing to replace existing saved hook: {legacy}")
|
||||
shutil.copy2(path, legacy)
|
||||
path.write_text(
|
||||
'#!/bin/sh\n' + MARKER + '\n'
|
||||
'exec python3 "$(git rev-parse --git-common-dir)/authorship-hooks/authorship_hook.py" '
|
||||
+ name + ' "$@"\n'
|
||||
)
|
||||
path.chmod(0o755)
|
||||
print(f"Human authorship hooks installed in {hooks}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
install()
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish the APK result only after trusted source and metadata validation."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from check_authorship import check_revision, event_violations
|
||||
|
||||
|
||||
def api(path, *args):
|
||||
return json.loads(subprocess.check_output(["gh", "api", path, *args], text=True))
|
||||
|
||||
|
||||
def compilation_state(run, jobs):
|
||||
for job in jobs:
|
||||
if job["name"] in ("Compile and test APK", "Build APK"):
|
||||
if job["status"] != "completed":
|
||||
return "pending"
|
||||
return "success" if job["conclusion"] == "success" else "failure"
|
||||
return "failure" if run["status"] == "completed" else "pending"
|
||||
|
||||
|
||||
def fetch_source(ref, sha):
|
||||
subprocess.run(["git", "fetch", "--no-tags", "origin", ref], check=True)
|
||||
fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], text=True).strip()
|
||||
if fetched != sha:
|
||||
raise RuntimeError("Pull request changed while validating")
|
||||
|
||||
|
||||
def documentation_only(sha):
|
||||
base = subprocess.check_output(["git", "merge-base", "origin/main", sha], text=True).strip()
|
||||
paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", base, sha]).split(b"\0")
|
||||
return all(path.endswith(b".md") or path in (b"LICENSE", b".gitignore") for path in paths if path)
|
||||
|
||||
|
||||
def main():
|
||||
with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as source:
|
||||
event = json.load(source)
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
event_name = os.environ["GITHUB_EVENT_NAME"]
|
||||
pr_number = event.get("number") if event_name == "pull_request_target" else None
|
||||
if event_name == "workflow_dispatch":
|
||||
pr_number = int(event.get("inputs", {}).get("pr_number") or 0)
|
||||
run = event.get("workflow_run", {})
|
||||
expected = event.get("pull_request", {}).get("head", {}).get("sha")
|
||||
if event_name == "workflow_run":
|
||||
expected = run["head_sha"]
|
||||
if run["event"] == "pull_request":
|
||||
prs = api(f"repos/{repo}/commits/{expected}/pulls")
|
||||
pr_number = next((pr["number"] for pr in prs
|
||||
if pr["state"] == "open" and pr["head"]["sha"] == expected), None)
|
||||
if pr_number is None:
|
||||
print("Ignoring a superseded or closed pull request build")
|
||||
return
|
||||
elif run["head_branch"] != event["repository"]["default_branch"]:
|
||||
return
|
||||
if pr_number:
|
||||
pr = api(f"repos/{repo}/pulls/{pr_number}")
|
||||
sha = pr["head"]["sha"]
|
||||
if pr["state"] != "open" or (expected and sha != expected):
|
||||
print("Ignoring a superseded or closed pull request event")
|
||||
return
|
||||
ref = f"refs/pull/{pr_number}/head"
|
||||
source_event = "pull_request"
|
||||
else:
|
||||
pr = None
|
||||
sha = expected or event.get("after") or os.environ["GITHUB_SHA"]
|
||||
ref = sha
|
||||
source_event = "push"
|
||||
state = "failure"
|
||||
description = "APK source validation failed"
|
||||
target = f"https://github.com/{repo}/actions/runs/{os.environ['GITHUB_RUN_ID']}"
|
||||
try:
|
||||
fetch_source(ref, sha)
|
||||
commits, errors = check_revision(sha)
|
||||
if pr:
|
||||
errors.extend(event_violations({"pull_request": pr}))
|
||||
if errors:
|
||||
raise RuntimeError("\n".join(errors))
|
||||
print(f"Source and metadata validated for {len(commits)} commits")
|
||||
if pr and documentation_only(sha):
|
||||
state = "success"
|
||||
description = "Source validated; no APK source changes"
|
||||
return
|
||||
query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20})
|
||||
runs = api(f"repos/{repo}/actions/workflows/build.yml/runs?{query}")["workflow_runs"]
|
||||
runs = [item for item in runs if item["head_sha"] == sha]
|
||||
if runs:
|
||||
latest = max(runs, key=lambda item: item["id"])
|
||||
jobs = api(f"repos/{repo}/actions/runs/{latest['id']}/jobs?per_page=100")["jobs"]
|
||||
state = compilation_state(latest, jobs)
|
||||
target = latest["html_url"]
|
||||
else:
|
||||
state = "pending"
|
||||
description = {"pending": "Source validated; awaiting APK compilation",
|
||||
"success": "Source validation and APK compilation passed",
|
||||
"failure": "APK compilation failed"}[state]
|
||||
finally:
|
||||
api(f"repos/{repo}/statuses/{sha}", "--method", "POST",
|
||||
"-f", "context=Build APK", "-f", f"state={state}",
|
||||
"-f", f"description={description}", "-f", f"target_url={target}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,83 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
path = Path(__file__).resolve().parents[1] / "release/check_authorship.py"
|
||||
spec = importlib.util.spec_from_file_location("check_authorship", path)
|
||||
check = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(check)
|
||||
|
||||
|
||||
class AuthorshipTest(unittest.TestCase):
|
||||
def commit(self, author="Human Contributor <human@example.com>", message="Fix a bug\n"):
|
||||
return (f"tree {'0' * 40}\nauthor {author} 1 +0000\n"
|
||||
"committer GitHub <noreply@github.com> 1 +0000\n\n" + message).encode()
|
||||
|
||||
def test_bot_primary_author_is_rejected_without_a_trailer(self):
|
||||
for author in ("OpenAI Codex <codex@openai.com>", "Claude <noreply@anthropic.com>",
|
||||
"github-actions[bot] <actions@example.com>"):
|
||||
with self.subTest(author=author):
|
||||
self.assertTrue(check.commit_violations("abc", self.commit(author=author)))
|
||||
|
||||
def test_bot_trailers_are_rejected_even_after_human_trailers(self):
|
||||
message = "Fix\n\nCo-authored-by: Resul Övür <human@example.com>\nco-AUTHORED-by: OpenAI Codex <codex@openai.com>\n"
|
||||
self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message))))
|
||||
|
||||
def test_human_authors_and_human_coauthors_are_preserved(self):
|
||||
message = "Fix the Codex configuration\n\nCo-authored-by: Resul Övür <human@example.com>\n"
|
||||
self.assertEqual([], check.commit_violations("abc", self.commit(message=message)))
|
||||
|
||||
def test_record_separator_in_message_does_not_hide_a_bot_trailer(self):
|
||||
self.assertTrue(check.commit_violations("abc", self.commit(message="Fix\x1e\nCo-authored-by: Claude <noreply@anthropic.com>\n")))
|
||||
|
||||
def test_pr_metadata_cannot_add_a_bot_to_the_squash_message(self):
|
||||
for field in ("title", "body"):
|
||||
self.assertTrue(check.event_violations({"pull_request": {field: "Co-authored-by: Copilot <bot@example.com>"}}))
|
||||
|
||||
def test_bot_pr_author_is_rejected(self):
|
||||
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}}))
|
||||
|
||||
def test_missing_author_fails_closed(self):
|
||||
self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n"))
|
||||
|
||||
|
||||
class InstalledHooksTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.repo = Path(self.directory.name)
|
||||
self.git("init", "-q")
|
||||
self.git("config", "user.name", "Human Contributor")
|
||||
self.git("config", "user.email", "human@example.com")
|
||||
installer = path.with_name("install_authorship_hooks.py")
|
||||
subprocess.run([sys.executable, str(installer)], cwd=self.repo, check=True, capture_output=True)
|
||||
(self.repo / "file").write_text("content")
|
||||
self.git("add", "file")
|
||||
|
||||
def tearDown(self):
|
||||
self.directory.cleanup()
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.run(["git", *args], cwd=self.repo, text=True, capture_output=True)
|
||||
|
||||
def test_explicit_bot_author_override_is_blocked(self):
|
||||
result = self.git("commit", "--author=OpenAI Codex <codex@openai.com>", "-m", "Fix")
|
||||
self.assertNotEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertIn("Bot commit author is forbidden", result.stderr)
|
||||
|
||||
def test_no_verify_does_not_skip_automatic_trailer_scrubbing(self):
|
||||
result = self.git("commit", "--no-verify", "-m", "Fix\n\nCo-authored-by: Another Human <other@example.com>\nCo-authored-by: Claude <noreply@anthropic.com>")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
message = self.git("log", "-1", "--format=%B").stdout
|
||||
self.assertNotIn("noreply@anthropic.com", message)
|
||||
self.assertIn("Co-authored-by: Another Human <other@example.com>", message)
|
||||
|
||||
def test_human_commit_and_human_coauthor_are_allowed(self):
|
||||
result = self.git("commit", "-m", "Fix\n\nCo-authored-by: Another Human <other@example.com>")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,123 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "device-smoke.sh"
|
||||
FAKE_ADB = r'''#!/usr/bin/env python3
|
||||
import json, os, shlex, sys
|
||||
from pathlib import Path
|
||||
p = Path(os.environ["SMOKE_STATE"])
|
||||
s = json.loads(p.read_text())
|
||||
a = sys.argv[1:]
|
||||
if a == ["get-state"]:
|
||||
print("device")
|
||||
elif a[:1] == ["shell"]:
|
||||
a = shlex.split(a[1])
|
||||
if a[:1] == ["wm"]:
|
||||
kind = a[1]
|
||||
if len(a) == 2:
|
||||
if s.get("unreadable") == kind:
|
||||
print("permission denied")
|
||||
else:
|
||||
print("Physical " + kind + ": " + ("400" if kind == "density" else "1080x1920"))
|
||||
if s.get(kind): print("Override " + kind + ": " + s[kind])
|
||||
else:
|
||||
value = a[2]
|
||||
s["writes"].append([kind, value])
|
||||
restoring = value in ("reset", "420", "1000x1800")
|
||||
if not (s.get("ignored") == kind or restoring and s.get("restore_ignored") == kind):
|
||||
s[kind] = "" if value == "reset" else value
|
||||
p.write_text(json.dumps(s))
|
||||
elif a[:1] == ["getconf"]: print("4096")
|
||||
elif a[:1] == ["pidof"]: print("123")
|
||||
elif a[:2] == ["dumpsys", "activity"]:
|
||||
print("topResumedActivity=ActivityRecord{abc u0 com.droiddeck.launcher/.MainActivity t1}")
|
||||
elif a[:3] == ["pm", "list", "packages"]:
|
||||
if s.get("query_failed"): sys.exit(1)
|
||||
print("package:" + s.get("package", "com.droiddeck.launcher"))
|
||||
elif a[:2] == ["am", "start"] and s.get("launch_failed"):
|
||||
print("Error: activity could not be started")
|
||||
sys.exit(1 if s["launch_failed"] == "exit" else 0)
|
||||
elif a[:1] == ["run-as"]:
|
||||
if s.get("session"):
|
||||
s.setdefault("log_commands", []).append(a)
|
||||
p.write_text(json.dumps(s))
|
||||
if "ls" in a: print(s["session"])
|
||||
else: print("package not debuggable")
|
||||
'''
|
||||
|
||||
|
||||
class DeviceSmokeTest(unittest.TestCase):
|
||||
def run_smoke(self, **scenario):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
adb = root / "adb"
|
||||
adb.write_text(FAKE_ADB)
|
||||
adb.chmod(0o755)
|
||||
sleep = root / "sleep"
|
||||
sleep.write_text("#!/bin/sh\nexit 0\n")
|
||||
sleep.chmod(0o755)
|
||||
state = root / "state.json"
|
||||
state.write_text(json.dumps({"density": "", "size": "", "writes": [], **scenario}))
|
||||
env = dict(os.environ, ADB=str(adb), SMOKE_STATE=str(state), PATH=str(root) + os.pathsep + os.environ["PATH"])
|
||||
result = subprocess.run(["bash", str(SCRIPT), "--no-fold"], env=env, capture_output=True, text=True, timeout=30)
|
||||
return result, json.loads(state.read_text())
|
||||
|
||||
def test_restores_preexisting_display_overrides(self):
|
||||
result, state = self.run_smoke(density="420", size="1000x1800")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertEqual("420", state["density"])
|
||||
self.assertEqual("1000x1800", state["size"])
|
||||
|
||||
def test_ignored_display_changes_do_not_pass(self):
|
||||
for kind in ("density", "size"):
|
||||
with self.subTest(kind=kind):
|
||||
result, state = self.run_smoke(ignored=kind)
|
||||
self.assertEqual(1, result.returncode, result.stdout)
|
||||
self.assertIn("wm " + kind + " failed", result.stdout)
|
||||
self.assertNotIn("PASS same process " + ("after" if kind == "density" else "at"), result.stdout)
|
||||
self.assertEqual("", state[kind])
|
||||
|
||||
def test_ignored_restore_remains_a_failure_and_is_retried_on_exit(self):
|
||||
for kind in ("density", "size"):
|
||||
with self.subTest(kind=kind):
|
||||
result, state = self.run_smoke(restore_ignored=kind)
|
||||
self.assertEqual(1, result.returncode, result.stdout)
|
||||
self.assertIn("could not restore", result.stdout)
|
||||
self.assertNotEqual("", state[kind])
|
||||
self.assertEqual(2, state["writes"].count([kind, "reset"]))
|
||||
|
||||
def test_unreadable_original_settings_are_not_changed(self):
|
||||
for kind in ("density", "size"):
|
||||
with self.subTest(kind=kind):
|
||||
result, state = self.run_smoke(unreadable=kind)
|
||||
self.assertEqual(0, result.returncode, result.stdout)
|
||||
self.assertFalse(any(item[0] == kind for item in state["writes"]))
|
||||
|
||||
def test_package_filter_does_not_accept_another_variant_or_a_failed_query(self):
|
||||
for scenario in ({"package": "com.droiddeck.launcher.debug"}, {"query_failed": True}):
|
||||
with self.subTest(scenario=scenario):
|
||||
result, state = self.run_smoke(**scenario)
|
||||
self.assertEqual(2, result.returncode, result.stdout)
|
||||
self.assertEqual([], state["writes"])
|
||||
|
||||
def test_failed_launch_is_not_masked_by_an_existing_process(self):
|
||||
for failure in ("exit", "message"):
|
||||
with self.subTest(failure=failure):
|
||||
result, _ = self.run_smoke(launch_failed=failure)
|
||||
self.assertEqual(1, result.returncode, result.stdout)
|
||||
self.assertIn("could not launch", result.stdout)
|
||||
|
||||
def test_session_name_remains_one_remote_argument(self):
|
||||
session = "x';id;#"
|
||||
result, state = self.run_smoke(session=session)
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertIn(["run-as", "com.droiddeck.launcher", "cat", "files/logs/" + session + "/events.jsonl"], state["log_commands"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,27 @@
|
||||
import re
|
||||
import subprocess
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
|
||||
def step_function():
|
||||
match = re.search(r"^step\(\) \{.*\}$", SESSION.read_text(), re.M)
|
||||
return match.group(0)
|
||||
|
||||
|
||||
class SessionStepTimeTest(unittest.TestCase):
|
||||
def test_a_step_line_carries_milliseconds_before_its_text(self):
|
||||
out = subprocess.run(["bash", "-c", step_function() + "\nstep starting the Steam client"],
|
||||
capture_output=True, text=True, timeout=30).stdout.strip()
|
||||
self.assertRegex(out, r"^== STEP \d{2}:\d{2}:\d{2}\.\d{3} starting the Steam client$")
|
||||
|
||||
def test_the_text_after_the_first_space_is_the_step_name(self):
|
||||
out = subprocess.run(["bash", "-c", step_function() + "\nstep checking the Steam client"],
|
||||
capture_output=True, text=True, timeout=30).stdout.strip()
|
||||
self.assertEqual("checking the Steam client", out.removeprefix("== STEP ").split(" ", 1)[1])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -774,6 +774,14 @@ class AttachPage:
|
||||
return {"selected": "", "fallback": "", "tools": []}
|
||||
|
||||
|
||||
class TourFailurePage(AttachPage):
|
||||
def evaluate(self, expression, timeout=30):
|
||||
self.scripts.append(expression)
|
||||
if expression == LIVE["TOUR_JS"]:
|
||||
raise RuntimeError("SteamClient.Settings.SetSetting is unavailable")
|
||||
return True
|
||||
|
||||
|
||||
class SwitchToDesktopTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.globals = LIVE["Helper"].attach.__globals__
|
||||
@@ -798,6 +806,14 @@ class SwitchToDesktopTest(unittest.TestCase):
|
||||
self.assertIn(("Runtime.addBinding", LIVE["VR_BINDING"]), helper.page.calls)
|
||||
self.assertIn(LIVE["VR_JS"], helper.page.scripts)
|
||||
|
||||
def test_missing_optional_tour_setting_does_not_block_attach(self):
|
||||
with mock.patch.dict(self.globals, {"shared_context": lambda port: "/devtools/page/1", "Page": TourFailurePage}):
|
||||
helper = LIVE["Helper"]("/steam", 1)
|
||||
self.assertTrue(helper.attach())
|
||||
self.assertIn(LIVE["VR_JS"], helper.page.scripts)
|
||||
self.assertIn(LIVE["TOUR_JS"], helper.page.scripts)
|
||||
self.assertIsNotNone(helper.page)
|
||||
|
||||
def test_vr_bridge_accepts_only_steamvr_and_coalesces_requests(self):
|
||||
helper = LIVE["Helper"]("/steam", 1)
|
||||
helper.page = mock.Mock()
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
RELEASE = Path(__file__).resolve().parents[1] / "release"
|
||||
sys.path.insert(0, str(RELEASE))
|
||||
import validate_apk
|
||||
|
||||
|
||||
class ValidateApkTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
subprocess.run(["git", "init", "-q", self.root], check=True)
|
||||
self.git("config", "user.name", "Human Developer")
|
||||
self.git("config", "user.email", "human@example.org")
|
||||
self.git("commit", "--allow-empty", "-qm", "Baseline")
|
||||
self.git("update-ref", "refs/remotes/origin/main", "HEAD")
|
||||
self.statuses = []
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip()
|
||||
|
||||
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt"):
|
||||
(self.root / filename).write_text(message)
|
||||
self.git("add", filename)
|
||||
self.git("commit", "--allow-empty", "-qm", message)
|
||||
sha = self.git("rev-parse", "HEAD")
|
||||
pr = {"number": 1, "state": "open", "head": {"sha": sha}, "user": {"login": "human", "type": "User"},
|
||||
"title": "Source change", "body": body}
|
||||
event = {"number": 1, "pull_request": {"head": {"sha": "stale" if stale else sha}}}
|
||||
if completed:
|
||||
event = {"workflow_run": {"event": "pull_request", "head_sha": "stale" if stale else sha}}
|
||||
path = self.root / "event.json"
|
||||
path.write_text(json.dumps(event))
|
||||
|
||||
def api(path, *args):
|
||||
if "/statuses/" in path:
|
||||
self.statuses.append(dict(value.split("=", 1) for value in args if "=" in value))
|
||||
return {}
|
||||
if path.endswith("/pulls/1"):
|
||||
return pr
|
||||
if "/commits/" in path and path.endswith("/pulls"):
|
||||
return [pr]
|
||||
if "workflows/build.yml/runs?" in path:
|
||||
return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", "html_url": "https://example.org/build"}]}
|
||||
if path.endswith("/jobs?per_page=100"):
|
||||
return {"jobs": [{"name": "Compile and test APK", "status": "in_progress" if result == "pending" else "completed", "conclusion": result}]}
|
||||
raise AssertionError(path)
|
||||
|
||||
env = {"GITHUB_EVENT_PATH": str(path), "GITHUB_REPOSITORY": "owner/repo",
|
||||
"GITHUB_EVENT_NAME": "workflow_run" if completed else "pull_request_target", "GITHUB_RUN_ID": "8"}
|
||||
with contextlib.chdir(self.root), patch.dict(os.environ, env), patch.object(validate_apk, "api", side_effect=api), patch.object(validate_apk, "fetch_source"):
|
||||
validate_apk.main()
|
||||
|
||||
def test_success_requires_compilation_and_clean_authorship(self):
|
||||
self.validate()
|
||||
self.assertEqual(self.statuses[-1]["state"], "success")
|
||||
|
||||
def test_successful_build_cannot_hide_bot_commit(self):
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.validate(message="Change\n\nCo-authored-by: OpenAI Codex <codex@openai.com>")
|
||||
self.assertEqual(self.statuses[-1]["state"], "failure")
|
||||
|
||||
def test_successful_build_cannot_hide_squash_metadata(self):
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.validate(body="Co-authored-by: Claude <claude@example.org>")
|
||||
self.assertEqual(self.statuses[-1]["state"], "failure")
|
||||
|
||||
def test_pending_or_failed_compilation_never_passes(self):
|
||||
for result in ("pending", "failure"):
|
||||
self.validate(result=result)
|
||||
self.assertEqual(self.statuses[-1]["state"], result)
|
||||
|
||||
def test_superseded_event_cannot_replace_current_status(self):
|
||||
self.validate(stale=True)
|
||||
self.assertEqual(self.statuses, [])
|
||||
|
||||
def test_completed_build_revalidates_current_squash_metadata(self):
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.validate(body="Co-authored-by: Claude <claude@example.org>", completed=True)
|
||||
self.assertEqual(self.statuses[-1]["state"], "failure")
|
||||
|
||||
def test_superseded_build_cannot_replace_current_status(self):
|
||||
self.validate(stale=True, completed=True)
|
||||
self.assertEqual(self.statuses, [])
|
||||
|
||||
def test_documentation_passes_without_waiting_for_a_skipped_build(self):
|
||||
self.validate(filename="README.md", result="pending")
|
||||
self.assertEqual(self.statuses[-1]["state"], "success")
|
||||
|
||||
def test_renaming_code_to_documentation_still_requires_compilation(self):
|
||||
(self.root / "source.kt").write_text("source")
|
||||
self.git("add", "source.kt")
|
||||
self.git("commit", "-qm", "Add source")
|
||||
self.git("update-ref", "refs/remotes/origin/main", "HEAD")
|
||||
self.git("mv", "source.kt", "README.md")
|
||||
self.git("commit", "-qm", "Rename source")
|
||||
with contextlib.chdir(self.root):
|
||||
self.assertFalse(validate_apk.documentation_only(self.git("rev-parse", "HEAD")))
|
||||
Reference in new issue
Block a user