Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Expand Down
133 changes: 133 additions & 0 deletions docs/wallpaper-troubleshooting.md
Original file line number Diff line number Diff line change
@@ -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.
232 changes: 232 additions & 0 deletions tool/repair_wallpaper.py
Original file line number Diff line number Diff line change
@@ -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())
Loading
Loading