diff --git a/README.md b/README.md index 22e0f95..a152588 100644 --- a/README.md +++ b/README.md @@ -276,6 +276,7 @@ Open **Tools** in the upper-right corner for these additional controls: | Wi-Fi connection fails on macOS | Allow OpenPelo under **System Settings → Privacy & Security → Local Network**, then retry. The permission covers device discovery, Wi-Fi ADB, and remote viewing. | | A remembered WiFi device stops reconnecting | Make sure it's on the same network as your computer, then try **Connect via WiFi** or **Pair using USB** again. | | An APK will not install | Check **ADB Messages** for the reason. Make sure the app supports your device and Android version. If you see **Signature Mismatch**, read the reinstall prompt before continuing. | +| Wallpaper says “Disabled by your admin” | See the [wallpaper troubleshooting guide](./docs/wallpaper-troubleshooting.md) for an opt-in ADB helper, manual commands, and device-policy limitations. This is experimental and does not change installation defaults. | | A file or setting cannot be accessed | Some system folders and settings are protected by Android. Check **ADB Messages** for details. | | Capture controls are missing from view | Scroll the home page to **Downloads & Media**, or enlarge the window. | diff --git a/docs/wallpaper-troubleshooting.md b/docs/wallpaper-troubleshooting.md new file mode 100644 index 0000000..b67c0a0 --- /dev/null +++ b/docs/wallpaper-troubleshooting.md @@ -0,0 +1,133 @@ +# Wallpaper is “Disabled by your admin” + +Related report: [OpenPelo #70](https://github.com/doudar/Openpelo/issues/70). + +Android has two relevant user restrictions: `no_set_wallpaper` blocks changing +wallpaper, while `no_wallpaper` blocks access to wallpaper APIs. A base user +restriction may be clearable over ADB. A device/profile-owner policy is separate: +clearing a base restriction does **not** override that policy. Firmware may also +omit the wallpaper service, which these commands cannot restore. + +This is an **experimental, opt-in troubleshooting tool**, not a confirmed fix +for every Peloton. It is a standalone Python helper in the source checkout, not +a new button in the packaged OpenPelo application. It does not run during app +installation or launcher setup. No affected Peloton has been hardware-tested +with this change yet. + +## Guarded helper (recommended) + +Use Python 3.10 or newer and an authorized ADB connection to your own tablet. +`adb` must be on PATH, or supply `--adb` with the full path to an existing +platform-tools `adb`/`adb.exe`. OpenPelo's selected target is **not** automatically +shared with this standalone helper. Run `adb devices` and use the intended +serial (or Wi-Fi `address:port`). Run these commands from the repository root: + +```sh +# Read-only: inspect base/effective restrictions and wallpaper-service presence. +python3 tool/repair_wallpaper.py --serial YOUR_SERIAL + +# Explicitly allow the targeted repair, then request the Android wallpaper picker. +python3 tool/repair_wallpaper.py --serial YOUR_SERIAL --apply --open-picker +``` + +On Windows, use `py -3` instead of `python3`, for example: + +```powershell +py -3 tool/repair_wallpaper.py --adb "C:\platform-tools\adb.exe" --serial YOUR_SERIAL --apply --open-picker +``` + +The helper requires **active Android user 0** and refuses guest/restricted/managed +profiles, ambiguous device selection, unfamiliar policy dumps, missing wallpaper +service, unsupported commands, and permission failures. It clears only wallpaper +flags actually found in the user's **base** restrictions. It reads the effective +restrictions again afterward and will not open the picker if verification fails. +Other restrictions, administrators, packages, provisioning settings, and app data +are left unchanged. Android errors printed with exit status zero are treated as +failures. Partial changes are reported when the post-check is available. + +Exit status `0` means the parsed wallpaper restrictions are clear, **not** that +a wallpaper was successfully applied. Status `2` means unresolved restrictions, +an unsupported/unknown state, or a command failure. Without `--apply`, a reported +restriction also returns `2`; that read-only check has changed nothing. +`--open-picker` is separately opt-in because it opens an activity on the tablet. + +Choose an image in the picker and verify the Lawnchair background. Then check +again after reopening the Peloton app and after a reboot: firmware may reapply +its restrictions. An “unable to resolve Intent” error means there is no matching +picker activity; removing restrictions cannot install a missing picker. + +## Underlying ADB commands + +First inspect, without changing anything (replace `YOUR_SERIAL`): + +```sh +adb -s YOUR_SERIAL shell am get-current-user +adb -s YOUR_SERIAL shell service check wallpaper +adb -s YOUR_SERIAL shell dumpsys user +adb -s YOUR_SERIAL shell dumpsys device_policy +adb -s YOUR_SERIAL shell pm help +``` + +Do not assume user 0 is active. In that user's dump, distinguish `Restrictions:` +(base) from `Effective restrictions:` and device-policy restrictions. A `null`, +missing, or unfamiliar effective section is **not** proof that restrictions are +absent. The helper intentionally stops in that case. + +Only with active user 0, a present wallpaper service, supported command syntax, +and the corresponding flag set in **base** restrictions, the candidate commands +are: + +```sh +adb -s YOUR_SERIAL shell pm set-user-restriction --user 0 no_set_wallpaper 0 +adb -s YOUR_SERIAL shell pm set-user-restriction --user 0 no_wallpaper 0 +adb -s YOUR_SERIAL shell dumpsys user +``` + +Run only the clear command for each flag that was originally set. Check effective +restrictions afterward; a silent command with exit status zero alone is not +verification. If both are clear, request the existing wallpaper picker: + +```sh +adb -s YOUR_SERIAL shell am start --user 0 -a android.intent.action.SET_WALLPAPER +``` + +To undo a cleared base flag, use the same `pm set-user-restriction` command with +`1` instead of `0`, **only for a flag known to have been set before this repair**. +The helper prints those restoration commands for verified base changes. Do not +set both flags blindly; that could introduce a restriction that was never there. + +## When this does not work + +A wallpaper restriction that is effective but absent from base restrictions may +be enforced by device policy. A base flag can also be cleared successfully while +a separate owner policy keeps the effective restriction enabled. These are not +successful repairs. Do not remove a device owner, disable Peloton system apps, +change provisioning flags, or factory-reset the tablet just to change wallpaper. +Likewise, `settings put ... no_set_wallpaper 0` does not operate on UserManager's +restriction storage, and granting an app wallpaper permission does not clear a +user restriction. + +For follow-up on #70, include the Android version, whether `service check +wallpaper` reports `found`, the helper's two restriction-status lines, and any +error text. Only share relevant restriction sections from diagnostic dumps; +`dumpsys user` and `dumpsys device_policy` can include account/device information. + +## Implementation references and validation + +- [Android UserManager: DISALLOW_SET_WALLPAPER](https://developer.android.com/reference/android/os/UserManager#DISALLOW_SET_WALLPAPER) +- [AOSP UserManager: both wallpaper restriction keys](https://android.googlesource.com/platform/prebuilts/fullsdk/sources/android-30/+/refs/heads/main/android/os/UserManager.java) +- [AOSP PackageManager shell: runSetUserRestriction](https://android.googlesource.com/platform/frameworks/base/+/525db8eac45707d98bb170905df754913651ec1a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java) +- [AOSP UserManagerService: separate base and effective policy restrictions](https://android.googlesource.com/platform/frameworks/base/+/ef2342c/services/core/java/com/android/server/pm/UserManagerService.java) +- [AOSP restriction-dump formatting](https://android.googlesource.com/platform/frameworks/base/+/master/services/core/java/com/android/server/pm/UserRestrictionsUtils.java) + +Run the offline tests with: + +```sh +python3 -m unittest discover -s tool/tests -p 'test_repair_wallpaper.py' -v +``` + +Fixtures model AOSP formatting; they are not captured Peloton results. Tests cover +read-only operation, device/user targeting, base versus policy restrictions, +unknown/null dumps, missing service, unsupported commands, permission errors, +partial failures, post-change verification, and conditional picker launch. +The existing build workflow's `tool/tests/test_*.py` discovery includes these tests. diff --git a/tool/repair_wallpaper.py b/tool/repair_wallpaper.py new file mode 100644 index 0000000..11fe02f --- /dev/null +++ b/tool/repair_wallpaper.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""Opt-in ADB wallpaper diagnostics/repair for OpenPelo issue #70. + +Python 3.10+, standard library only. Read-only unless --apply or --open-picker +is supplied. Never removes device administrators, changes provisioning, roots +Android, or modifies unrelated restrictions. See docs/wallpaper-troubleshooting.md. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import re +import subprocess +import sys +from typing import Callable + +WALLPAPER_KEYS = ("no_set_wallpaper", "no_wallpaper") +ERROR_OUTPUT = re.compile( + r"(?im)^\s*(?:error\b|failure\b|unknown command\b|permission denial\b|permission denied\b)" + r"|\bSecurityException\b|Exception occurred while executing" +) +USER_HEADER = re.compile(r"(?m)^([ \t]*)UserInfo\{0:.*:([0-9a-fA-F]+)\}[^\n]*$") + + +class RepairError(RuntimeError): + """An unsupported or unsafe-to-continue device state.""" + + +class Adb: + def __init__(self, executable: str = "adb", serial: str | None = None, + runner: Callable = subprocess.run): + self.executable = executable + self.serial = serial + self.runner = runner + + def run(self, *args: str, targeted: bool = True) -> str: + if targeted and not self.serial: + raise RepairError("Select an authorized device before running commands.") + command = [self.executable] + if targeted: + command += ["-s", self.serial] + command += list(args) + try: + result = self.runner(command, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=20) + except (OSError, subprocess.TimeoutExpired) as error: + raise RepairError(f"ADB command failed: {error}") from error + output = "\n".join(part for part in (result.stdout, result.stderr) if part).strip() + if result.returncode or ERROR_OUTPUT.search(output): + raise RepairError(f"ADB {' '.join(args)} failed: {output or result.returncode}") + return result.stdout.strip() + + def select_device(self) -> None: + output = self.run("devices", targeted=False) + devices = {} + for line in output.splitlines(): + parts = line.split() + if len(parts) >= 2 and not line.startswith("List of devices attached"): + devices[parts[0]] = parts[1] + if self.serial: + if devices.get(self.serial) != "device": + raise RepairError("The selected device is missing, offline, or unauthorized.") + elif len(devices) == 1 and next(iter(devices.values())) == "device": + self.serial = next(iter(devices)) + else: + raise RepairError("Connect one authorized device, or select it with --serial.") + + def require_owner_user(self) -> None: + current = self.run("shell", "am", "get-current-user") + if current != "0": + raise RepairError("Repair requires active Android user 0; user detection was not 0. " + "No fallback to a guessed user is allowed.") + + +def restriction_section(block: str, heading: str) -> frozenset[str] | None: + """Parse AOSP indented dumps; unknown/null is not proof of an empty policy.""" + lines = block.splitlines() + matches = [i for i, line in enumerate(lines) if line.strip() == heading] + if len(matches) != 1: + return None + start = matches[0] + indent = len(lines[start]) - len(lines[start].lstrip()) + entries = [] + for line in lines[start + 1:]: + if not line.strip(): + continue + if len(line) - len(line.lstrip()) <= indent: + break + entries.append(line.strip()) + if entries == ["none"]: + return frozenset() + if not entries or "null" in entries or "none" in entries: + return None + enabled = set() + for entry in entries: + match = re.fullmatch(r"([a-z][a-z0-9_]*)(?:=(true|false))?", entry) + if not match: + return None + if match[2] != "false": + enabled.add(match[1]) + return frozenset(enabled) + + +@dataclass(frozen=True) +class Restrictions: + base: frozenset[str] | None + effective: frozenset[str] | None + + +def parse_restrictions(output: str) -> Restrictions: + matches = list(USER_HEADER.finditer(output)) + if len(matches) != 1: + raise RepairError("Could not identify one user-0 block in dumpsys user.") + header = matches[0] + # UserInfo flags: GUEST=0x4, RESTRICTED=0x8, MANAGED_PROFILE=0x20. + # INITIALIZED=0x10 is deliberately allowed (normal owner flags are often 0x13). + if int(header[2], 16) & (0x4 | 0x8 | 0x20): + raise RepairError("Refusing to change a guest, restricted user, or managed profile.") + indent = len(header[1]) + lines = [] + for line in output[header.end():].splitlines(): + if line.strip() and len(line) - len(line.lstrip()) <= indent: + break + lines.append(line) + block = "\n".join(lines) + return Restrictions(restriction_section(block, "Restrictions:"), + restriction_section(block, "Effective restrictions:")) + + +def read_restrictions(adb: Adb) -> Restrictions: + adb.require_owner_user() + return parse_restrictions(adb.run("shell", "dumpsys", "user")) + + +def wallpaper_service_present(output: str) -> bool: + if output.strip() == "Service wallpaper: found": + return True + if output.strip() == "Service wallpaper: not found": + return False + raise RepairError("Wallpaper service status is unknown; no repair will be attempted.") + + +def show_restrictions(state: Restrictions, emit: Callable[[str], None]) -> None: + for key in WALLPAPER_KEYS: + base = "unknown" if state.base is None else str(key in state.base).lower() + effective = "unknown" if state.effective is None else str(key in state.effective).lower() + emit(f"{key}: base={base}, effective={effective}") + + +def repair(adb: Adb, *, apply: bool = False, open_picker: bool = False, + emit: Callable[[str], None] = print) -> int: + """Return 0 for verified-clear restrictions, 2 for unresolved/unsupported state.""" + before = read_restrictions(adb) + show_restrictions(before, emit) + if not wallpaper_service_present(adb.run("shell", "service", "check", "wallpaper")): + emit("This firmware exposes no wallpaper service. Restriction commands cannot add it.") + return 2 + if before.base is None or before.effective is None: + emit("Restriction state is unverified (missing, null, or unfamiliar dump). No changes.") + return 2 + active = set(WALLPAPER_KEYS) & before.effective + eligible = set(WALLPAPER_KEYS) & before.base + if not eligible.issubset(active): + emit("Base/effective restrictions disagree. No changes; collect fresh diagnostics.") + return 2 + if active and not apply: + emit("Read-only check. --apply can clear detected base wallpaper restrictions only.") + return 2 + if active - eligible: + emit("A wallpaper restriction has no matching base restriction; it may be enforced " + "by device policy. No changes; this tool does not remove administrators.") + return 2 + if eligible: + help_text = adb.run("shell", "pm", "help") + if not re.search(r"set-user-restriction\s+\[--user\s+[^\]]+\]", help_text): + emit("Firmware does not advertise the required pm set-user-restriction syntax.") + return 2 + errors = [] + for key in WALLPAPER_KEYS: + if key not in eligible: + continue + try: + adb.require_owner_user() + output = adb.run("shell", "pm", "set-user-restriction", "--user", "0", key, "0") + if output: + raise RepairError(f"Unexpected response while clearing {key}: {output}") + except RepairError as error: + errors.append(str(error)) + break + after = read_restrictions(adb) + emit("After attempted repair:") + show_restrictions(after, emit) + if after.base is not None: + for key in WALLPAPER_KEYS: + if key in eligible and key not in after.base: + emit(f"Cleared base {key}. To restore this original flag only: " + f"adb -s YOUR_SERIAL shell pm set-user-restriction --user 0 {key} 1") + for error in errors: + emit(error) + if (errors or after.effective is None or after.base is None + or set(WALLPAPER_KEYS) & (after.effective | after.base)): + emit("Repair is not verified. A device policy may still enforce the restriction; " + "do not treat a successful shell exit as proof of a fix.") + return 2 + emit("No wallpaper restrictions detected for user 0. This does not prove that the " + "firmware or launcher can actually apply a wallpaper; test on the tablet.") + if open_picker: + adb.require_owner_user() + adb.run("shell", "am", "start", "--user", "0", "-a", "android.intent.action.SET_WALLPAPER") + emit("Wallpaper picker requested. Confirm that it opens and applies your image.") + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--adb", default="adb", help="ADB executable path (including adb.exe on Windows)") + parser.add_argument("--serial", help="Explicit adb device serial or Wi-Fi address:port") + parser.add_argument("--apply", action="store_true", help="Clear detected base wallpaper restrictions") + parser.add_argument("--open-picker", action="store_true", help="Open picker only after verified-clear restrictions") + args = parser.parse_args(argv) + adb = Adb(args.adb, args.serial) + try: + adb.select_device() + return repair(adb, apply=args.apply, open_picker=args.open_picker) + except RepairError as error: + print(f"Stopped: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tool/tests/test_repair_wallpaper.py b/tool/tests/test_repair_wallpaper.py new file mode 100644 index 0000000..0923e67 --- /dev/null +++ b/tool/tests/test_repair_wallpaper.py @@ -0,0 +1,313 @@ +"""Offline tests: fixtures model AOSP dump formatting, not captured Peloton output.""" + +import contextlib +import io +from pathlib import Path +import subprocess +import sys +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import repair_wallpaper as rw + + +def dump(base="no_set_wallpaper", effective="no_set_wallpaper", flags="13"): + return f"""Users: + UserInfo{{0:Owner:{flags}}} serialNo=0 + State: RUNNING_UNLOCKED + Restrictions: + {base} + Device policy local restrictions: + none + Effective restrictions: + {effective} + UserInfo{{10:Work:30}} serialNo=10 + Restrictions: + no_wallpaper + Effective restrictions: + no_wallpaper + Device policy global restrictions: + no_set_wallpaper +""" + + +class FakeAdb(rw.Adb): + def __init__(self, dumps, *, service="Service wallpaper: found", + help_text="set-user-restriction [--user USER_ID] RESTRICTION VALUE", + current_users=None, responses=None): + self.dumps = list(dumps) + self.service = service + self.help_text = help_text + self.current_users = list(current_users or []) + self.responses = responses or {} + self.commands = [] + + def run(self, *args, **kwargs): + self.commands.append(args) + if args == ("shell", "am", "get-current-user"): + return self.current_users.pop(0) if self.current_users else "0" + if args == ("shell", "dumpsys", "user"): + return self.dumps.pop(0) + if args == ("shell", "service", "check", "wallpaper"): + return self.service + if args == ("shell", "pm", "help"): + return self.help_text + if args in self.responses: + result = self.responses[args] + if isinstance(result, Exception): + raise result + return result + if args[:3] == ("shell", "pm", "set-user-restriction"): + return "" + if args[:3] == ("shell", "am", "start"): + return "Starting: Intent { act=android.intent.action.SET_WALLPAPER }" + raise AssertionError(f"Unexpected command: {args}") + + @property + def writes(self): + return [c for c in self.commands if c[:3] == ("shell", "pm", "set-user-restriction")] + + @property + def picker_opened(self): + return any(c[:3] == ("shell", "am", "start") for c in self.commands) + + +CLEAR_SET = ("shell", "pm", "set-user-restriction", "--user", "0", "no_set_wallpaper", "0") +CLEAR_WALLPAPER = ("shell", "pm", "set-user-restriction", "--user", "0", "no_wallpaper", "0") + + +class ParserTests(unittest.TestCase): + def test_target_user_does_not_include_other_users_or_global_sections(self): + state = rw.parse_restrictions(dump("none", "none")) + self.assertEqual(state.base, frozenset()) + self.assertEqual(state.effective, frozenset()) + + def test_bare_keys_and_boolean_variants(self): + state = rw.parse_restrictions(dump("no_wallpaper\n no_camera", + "no_wallpaper=true\n no_set_wallpaper=false")) + self.assertEqual(state.base, {"no_wallpaper", "no_camera"}) + self.assertEqual(state.effective, {"no_wallpaper"}) + + def test_null_and_missing_are_unknown(self): + self.assertIsNone(rw.parse_restrictions(dump("null", "null")).effective) + state = rw.parse_restrictions(dump().replace("Effective restrictions:", "Unknown heading:")) + self.assertIsNone(state.effective) + + def test_unrecognized_or_duplicate_section_is_unknown(self): + self.assertIsNone(rw.parse_restrictions(dump("Bundle[{no_wallpaper=true}]")).base) + text = dump().replace(" State: RUNNING_UNLOCKED", " Restrictions:\n none") + self.assertIsNone(rw.parse_restrictions(text).base) + + def test_normal_initialized_owner_allowed(self): + self.assertEqual(rw.parse_restrictions(dump(flags="13")).base, {"no_set_wallpaper"}) + + def test_guest_restricted_and_managed_profiles_rejected(self): + for flags in ("17", "1b", "33"): + with self.subTest(flags=flags), self.assertRaises(rw.RepairError): + rw.parse_restrictions(dump(flags=flags)) + + def test_missing_and_duplicate_owner_rejected(self): + for text in ("Permission Denial", dump() + dump(), dump().replace("{0:", "{1:")): + with self.subTest(text=text[:30]), self.assertRaises(rw.RepairError): + rw.parse_restrictions(text) + + def test_crlf_and_colon_in_username(self): + text = dump().replace("Owner:", "Owner:Name:").replace("\n", "\r\n") + self.assertEqual(rw.parse_restrictions(text).effective, {"no_set_wallpaper"}) + + def test_empty_mixed_or_unrecognized_entries_are_unknown(self): + for value in ("", "none\n no_wallpaper", "unknown format!", "null\n no_wallpaper"): + with self.subTest(value=value): + self.assertIsNone(rw.parse_restrictions(dump(value)).base) + + +class AdbTests(unittest.TestCase): + def adb(self, stdout="", stderr="", code=0, serial="bike"): + runner = Mock(return_value=subprocess.CompletedProcess([], code, stdout, stderr)) + return rw.Adb("/path with spaces/adb", serial, runner), runner + + def test_targets_serial_without_host_shell_and_has_timeout(self): + adb, runner = self.adb("0") + adb.require_owner_user() + self.assertEqual(runner.call_args.args[0], + ["/path with spaces/adb", "-s", "bike", "shell", "am", "get-current-user"]) + self.assertEqual(runner.call_args.kwargs["timeout"], 20) + self.assertNotIn("shell", runner.call_args.kwargs) + + def test_exit_zero_android_errors_are_rejected(self): + for text in ("java.lang.SecurityException: denied", "Error type 3", "Unknown command: x", + "Permission Denial: blocked", "Failure [NOT_ALLOWED]"): + with self.subTest(text=text), self.assertRaises(rw.RepairError): + self.adb(text)[0].run("shell", "pm") + + def test_stderr_errors_and_nonzero_exit_are_rejected(self): + for kwargs in ({"stderr": "Permission denied"}, {"code": 1}): + with self.subTest(kwargs=kwargs), self.assertRaises(rw.RepairError): + self.adb(**kwargs)[0].run("shell", "pm") + + def test_timeout_and_missing_binary_are_wrapped(self): + for error in (FileNotFoundError("adb"), subprocess.TimeoutExpired("adb", 20)): + adb, runner = self.adb() + runner.side_effect = error + with self.assertRaises(rw.RepairError): + adb.run("devices", targeted=False) + + def test_selects_one_authorized_device(self): + adb, _ = self.adb("List of devices attached\nbike\tdevice\n", serial=None) + adb.select_device() + self.assertEqual(adb.serial, "bike") + + def test_ambiguous_absent_or_unauthorized_devices_refused(self): + for entries in ("", "bike\tunauthorized", "bike\toffline", "bike\tdevice\nother\tdevice", + "bike\tdevice\nother\trecovery", "bike\tdevice\nother\tno permissions"): + adb, _ = self.adb("List of devices attached\n" + entries, serial=None) + with self.subTest(entries=entries), self.assertRaises(rw.RepairError): + adb.select_device() + + def test_explicit_device_selection(self): + adb, _ = self.adb("List of devices attached\nbike\tdevice\nother\tdevice") + adb.select_device() + for entries in ("other\tdevice", "bike\tunauthorized"): + with self.subTest(entries=entries), self.assertRaises(rw.RepairError): + self.adb("List of devices attached\n" + entries)[0].select_device() + + def test_requires_selection_before_targeted_command(self): + with self.assertRaises(rw.RepairError): + self.adb(serial=None)[0].run("shell", "pm") + + def test_nonzero_unknown_and_injected_current_user_rejected(self): + for value in ("10", "", "current user: 0", "0; reboot", "-1"): + with self.subTest(value=value), self.assertRaises(rw.RepairError): + self.adb(value)[0].require_owner_user() + + +class RepairTests(unittest.TestCase): + def run_repair(self, adb, **kwargs): + messages = [] + result = rw.repair(adb, emit=messages.append, **kwargs) + return result, "\n".join(messages) + + def test_read_only_is_default(self): + adb = FakeAdb([dump()]) + result, _ = self.run_repair(adb) + self.assertEqual(result, 2) + self.assertEqual(adb.writes, []) + self.assertFalse(adb.picker_opened) + + def test_clears_only_detected_base_key_and_preserves_other_restrictions(self): + adb = FakeAdb([dump("no_set_wallpaper\n no_camera", "no_set_wallpaper\n no_camera"), + dump("no_camera", "no_camera")]) + result, messages = self.run_repair(adb, apply=True) + self.assertEqual(result, 0) + self.assertEqual(adb.writes, [CLEAR_SET]) + self.assertIn("no_set_wallpaper 1", messages) + self.assertNotIn("no_wallpaper 1", messages) + + def test_clears_both_keys_in_order_and_then_opens_picker(self): + keys = "no_set_wallpaper\n no_wallpaper" + adb = FakeAdb([dump(keys, keys), dump("none", "none")]) + result, _ = self.run_repair(adb, apply=True, open_picker=True) + self.assertEqual(result, 0) + self.assertEqual(adb.writes, [CLEAR_SET, CLEAR_WALLPAPER]) + self.assertTrue(adb.picker_opened) + self.assertEqual(adb.commands[-1], ("shell", "am", "start", "--user", "0", "-a", + "android.intent.action.SET_WALLPAPER")) + + def test_policy_only_restriction_is_not_modified(self): + adb = FakeAdb([dump("none", "no_set_wallpaper")]) + result, messages = self.run_repair(adb, apply=True, open_picker=True) + self.assertEqual(result, 2) + self.assertIn("device policy", messages) + self.assertEqual(adb.writes, []) + self.assertFalse(adb.picker_opened) + + def test_effective_restriction_persisting_after_success_is_not_a_fix(self): + adb = FakeAdb([dump(), dump("none", "no_set_wallpaper")]) + result, messages = self.run_repair(adb, apply=True, open_picker=True) + self.assertEqual(result, 2) + self.assertIn("Repair is not verified", messages) + self.assertFalse(adb.picker_opened) + + def test_unknown_before_or_after_cannot_claim_success(self): + for dumps in ([dump("null", "null")], [dump(), dump("none", "null")]): + adb = FakeAdb(dumps) + result, _ = self.run_repair(adb, apply=True, open_picker=True) + self.assertEqual(result, 2) + self.assertFalse(adb.picker_opened) + + def test_missing_service_prevents_changes(self): + adb = FakeAdb([dump()], service="Service wallpaper: not found") + result, _ = self.run_repair(adb, apply=True) + self.assertEqual(result, 2) + self.assertEqual(adb.writes, []) + + def test_unknown_service_prevents_changes(self): + adb = FakeAdb([dump()], service="unrecognized vendor output") + with self.assertRaises(rw.RepairError): + self.run_repair(adb, apply=True) + self.assertEqual(adb.writes, []) + + def test_unsupported_pm_syntax_prevents_changes(self): + for help_text in ("other commands", "set-user-restriction RESTRICTION VALUE"): + adb = FakeAdb([dump()], help_text=help_text) + result, _ = self.run_repair(adb, apply=True) + self.assertEqual(result, 2) + self.assertEqual(adb.writes, []) + + def test_contradictory_base_and_effective_dump_stops(self): + adb = FakeAdb([dump("no_wallpaper", "none")]) + self.assertEqual(self.run_repair(adb, apply=True)[0], 2) + self.assertEqual(adb.writes, []) + + def test_clear_device_requires_no_pm_write(self): + adb = FakeAdb([dump("none", "none")]) + result, messages = self.run_repair(adb, apply=True) + self.assertEqual(result, 0) + self.assertEqual(adb.writes, []) + self.assertNotIn(("shell", "pm", "help"), adb.commands) + self.assertIn("does not prove", messages) + + def test_command_error_is_reported_even_if_after_dump_is_clear(self): + adb = FakeAdb([dump(), dump("none", "none")], + responses={CLEAR_SET: rw.RepairError("permission denied")}) + result, messages = self.run_repair(adb, apply=True, open_picker=True) + self.assertEqual(result, 2) + self.assertIn("permission denied", messages) + self.assertFalse(adb.picker_opened) + + def test_unexpected_command_output_is_not_success(self): + adb = FakeAdb([dump(), dump("none", "none")], responses={CLEAR_SET: "Usage: pm ..."}) + self.assertEqual(self.run_repair(adb, apply=True)[0], 2) + + def test_partial_failure_exposes_actual_changed_flags(self): + keys = "no_set_wallpaper\n no_wallpaper" + adb = FakeAdb([dump(keys, keys), dump("no_wallpaper", "no_wallpaper")], + responses={CLEAR_WALLPAPER: rw.RepairError("second command failed")}) + result, messages = self.run_repair(adb, apply=True, open_picker=True) + self.assertEqual(result, 2) + self.assertIn("Cleared base no_set_wallpaper", messages) + self.assertNotIn("Cleared base no_wallpaper", messages) + self.assertFalse(adb.picker_opened) + + def test_user_switch_before_write_stops(self): + adb = FakeAdb([dump(), dump()], current_users=["0", "10", "0"]) + result, _ = self.run_repair(adb, apply=True) + self.assertEqual(result, 2) + self.assertEqual(adb.writes, []) + + def test_picker_failure_is_not_swallowed(self): + picker = ("shell", "am", "start", "--user", "0", "-a", "android.intent.action.SET_WALLPAPER") + adb = FakeAdb([dump("none", "none")], responses={picker: rw.RepairError("unable to resolve Intent")}) + with self.assertRaises(rw.RepairError): + self.run_repair(adb, open_picker=True) + + def test_cli_failure_is_concise_and_nonzero(self): + with patch.object(rw.Adb, "select_device", side_effect=rw.RepairError("not authorized")): + with contextlib.redirect_stderr(io.StringIO()) as output: + self.assertEqual(rw.main([]), 2) + self.assertIn("Stopped: not authorized", output.getvalue()) + + +if __name__ == "__main__": + unittest.main()