Compare commits

..

No commits in common. "main" and "v1.1.0" have entirely different histories.

69 changed files with 19102 additions and 29839 deletions

View file

@ -1,2 +1,6 @@
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]

13
.deepsource.toml Normal file
View file

@ -0,0 +1,13 @@
version = 1
[[analyzers]]
name = "rust"
[analyzers.meta]
msrv = "stable"
[[analyzers]]
name = "test-coverage"
[[transformers]]
name = "rustfmt"

View file

@ -62,24 +62,15 @@ body:
label: Desktop Environment
description: If relevant, please fill it
placeholder: GNOME 46, KDE Plasma 4, etc...
- type: input
id: adb-v
attributes:
label: ADB version
description: If relevant, please fill it
placeholder: 1.0.41
- type: textarea
id: logfiles
attributes:
label: Provide logs
description: "Paste the relevant (notice the line timestamps) slice (contiguous range) of [the logfile generated by UAD-ng](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/FAQ#where-are-the-logfiles)"
value: |
<details><summary>Log</summary>
render: "" # this should disable soft-wrap
validations:
required: true
```
Please replace this line by the log-file contents
```
</details>
- type: checkboxes
id: acknowledgements
attributes:

View file

@ -6,17 +6,16 @@ body:
- type: markdown
attributes:
value: |
## Consider submitting a Pull Request
We receive many package-related issues and it's hard to keep up. **Consider submitting a Pull Request yourself**—it helps us process changes much faster! See our [guide on how to contribute](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/How-to-contribute) for instructions.
---
## Document each package the best you can
**List**: `Google`|`Misc`|`OEM` (manufacturer) |`AOSP`|`Pending`|`Carrier` (ISP).
**Removal**: `Recommended`|`Advanced`|`Expert`|`Unsafe`. See the [Removal Definitions](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Debloat-Lists#removal-definitions) on the wiki for details. **Please ensure you follow these definitions when proposing changes.**
**Removal**:
- Recommended: Pointless or outright negative packages, and/or apps available through Google Play.
- Advanced: Breaks obscure or minor parts of functionality, or apps that aren't easily enabled/installed through Settings/Google Play. This category is also used for apps that are useful (default keyboard/gallery/launcher/music app.) but that can easily be replaced by a better alternative.
- Expert: Breaks widespread and/or important functionality, but nothing important to the basic operation of the operating system. Removing an Expert package should not bootloop the device (unless mentioned in the description) but we can't guarantee it 100%.
- Unsafe: Can break vital parts of the operating system. Removing an Unsafe package have an extremely high risk of bootlooping your device.
- type: textarea
id: package-listing
@ -31,15 +30,6 @@ body:
validations:
required: true
- type: checkboxes
id: removal-definitions
attributes:
label: Removal Definitions
description: Please ensure you follow the removal definitions when proposing changes.
options:
- label: I've read the [Removal Definitions](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Debloat-Lists#removal-definitions)
required: true
- type: checkboxes
id: acknowledgements
attributes:
@ -47,7 +37,6 @@ body:
description: Your bug report will be closed if you don't follow the checklist below.
options:
- label: I removed all those packages on my phone. If not, why? Explain in the issue.
- label: I'm willing to submit a Pull Request for this change.
- label: This issue is not a duplicate of an existing one.
required: true
- label: I have chosen an appropriate title.

View file

@ -3,13 +3,6 @@ description: Your phone has unexpected issues after debloating
title: "pkg(scope): "
labels: ["package::breakage"]
body:
- type: markdown
attributes:
value: |
## Consider submitting a Pull Request
If you know which package caused the issue and how the documentation should be updated, **consider submitting a Pull Request yourself**—it helps us process changes much faster! See our [guide on how to contribute](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/How-to-contribute) for instructions.
- type: textarea
id: what-happened
attributes:
@ -38,7 +31,6 @@ body:
label: Acknowledgements
description: Your bug report will be closed if you don't follow the checklist below.
options:
- label: I'm willing to submit a Pull Request to fix the package documentation.
- label: This issue is not a duplicate of an existing one.
required: true
- label: I have chosen an appropriate title.

View file

@ -6,17 +6,16 @@ body:
- type: markdown
attributes:
value: |
## Consider submitting a Pull Request
We receive many package documentation updates and it's hard to keep up. **Consider submitting a Pull Request yourself**—it helps us process changes much faster! See our [guide on how to contribute](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/How-to-contribute) for instructions.
---
## Document each package the best you can
**List**: `Google`|`Misc`|`OEM` (manufacturer) |`AOSP`|`Pending`|`Carrier` (ISP).
**Removal**: `Recommended`|`Advanced`|`Expert`|`Unsafe`. See the [Removal Definitions](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Debloat-Lists#removal-definitions) on the wiki for details. **Please ensure you follow these definitions when proposing changes.**
**Removal**:
- Recommended: Pointless or outright negative packages, and/or apps available through Google Play.
- Advanced: Breaks obscure or minor parts of functionality, or apps that aren't easily enabled/installed through Settings/Google Play. This category is also used for apps that are useful (default keyboard/gallery/launcher/music app.) but that can easily be replaced by a better alternative.
- Expert: Breaks widespread and/or important functionality, but nothing important to the basic operation of the operating system. Removing an Expert package should not bootloop the device (unless mentioned in the description) but we can't guarantee it 100%.
- Unsafe: Can break vital parts of the operating system. Removing an Unsafe package have an extremely high risk of bootlooping your device.
- type: textarea
id: package-listing
@ -34,22 +33,12 @@ body:
validations:
required: true
- type: checkboxes
id: removal-definitions
attributes:
label: Removal Definitions
description: Please ensure you follow the removal definitions when proposing changes.
options:
- label: I've read the [Removal Definitions](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Debloat-Lists#removal-definitions)
required: true
- type: checkboxes
id: acknowledgements
attributes:
label: Acknowledgements
description: Your bug report will be closed if you don't follow the checklist below.
options:
- label: I'm willing to submit a Pull Request for this change.
- label: This issue is not a duplicate of an existing one.
required: true
- label: I have chosen an appropriate title.

View file

@ -1,38 +0,0 @@
name: CI/CD
description: File an issue for CI/CD
title: "ci(scope): "
labels: ["ci"]
body:
- type: textarea
attributes:
label: Expected behavior
description: A clear and concise description of what the problem is and how it could be approached.
validations:
required: true
- type: textarea
attributes:
label: Alternate solutions
description: A clear and concise description of any alternative solutions or features you've considered.
validations:
required: false
- type: textarea
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false
- type: checkboxes
id: acknowledgements
attributes:
label: Acknowledgements
description: Your issue will be closed if you don't follow the checklist below.
options:
- label: This issue is not a duplicate of an existing issue.
required: true
- label: I have chosen an appropriate title.
required: true
- label: All requested information has been provided properly.
required: true

View file

@ -1,31 +0,0 @@
## Description
<!-- Please include a summary of your changes and any relevant context. -->
### Related issues
<!-- Link to related issues using keywords (e.g. Fixes <issue_number>) -->
<!-- Learn more: https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/using-keywords-in-issues-and-pull-requests -->
## How has this been tested?
<!-- Describe the tests you ran to verify your changes. -->
- [ ] Unit tests added/updated
- [ ] Manual testing performed
- [ ] Tested on the following environment(s):
- OS:
- Desktop Environment:
- Window System/Manager:
- ADB version:
- Rust version:
## Checklist
- [ ] I have read the [CONTRIBUTING guidelines](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/blob/main/CONTRIBUTING.md)
- [ ] My code follows the project's code style
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] My changes generate no new warnings
- [ ] I have tested the application with these changes
- [ ] The CI/CD pipeline passes

View file

@ -1,18 +0,0 @@
## Description
<!-- Please describe the documentation changes you're adding or updating. -->
<!-- Link to related issues using keywords (e.g. Fixes <issue_number>) -->
<!-- Learn more: https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/using-keywords-in-issues-and-pull-requests -->
## Documentation Changes
<!-- Briefly describe what documentation was added or modified, and why -->
## Checklist
- [ ] I have read the [CONTRIBUTING guidelines](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/blob/main/CONTRIBUTING.md)
- [ ] My changes are clear and easy to understand
- [ ] I have checked for grammar and spelling errors
- [ ] I have verified all links are correct
- [ ] I have tested any code examples provided
- [ ] The documentation is properly formatted with markdown

View file

@ -1,21 +0,0 @@
## Description
<!-- Please describe the package changes you're adding or updating. -->
<!-- Link to related issues using keywords (e.g. Fixes <issue_number>) -->
<!-- Learn more: https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/using-keywords-in-issues-and-pull-requests -->
## Testing
- [ ] I have tested these packages on a real device or emulator
- [ ] Package names follow correct naming conventions (e.g., `com.example.app`)
- [ ] Package names have been verified against device/ADB output
- [ ] Descriptions are accurate and helpful
- [ ] No duplicate packages added
## Acknowledgements
- [ ] I have read the [CONTRIBUTING guidelines](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/blob/main/CONTRIBUTING.md)
- [ ] I have followed the package addition guidelines
- [ ] I have reviewed the [Removal Definitions](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Debloat-Lists#removal-definitions) in the wiki
- [ ] All package information is accurate and tested
- [ ] I understand my PR may be modified before merging

View file

@ -1,21 +0,0 @@
## Description
<!-- Please include a clear summary of the changes in this pull request. -->
## Related issues
<!-- Link to related issues using keywords (e.g. Fixes <issue_number>) -->
<!-- Learn more: https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/using-keywords-in-issues-and-pull-requests -->
## Checklist
- [ ] I have read the [CONTRIBUTING guidelines](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/blob/main/CONTRIBUTING.md)
- [ ] I have performed a self-review of my changes
- [ ] My changes generate no new warnings
- [ ] The CI/CD pipeline passes (or is expected to pass)
<!--
Optional: specialized templates are kept in .github/PULL_REQUEST_TEMPLATE/
For app/package/documentation-focused PRs, you can use it by including the template in the URL when creating the PR, e.g.
https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/pull/new/<branch_name>?template=app.md, https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/pull/new/<branch_name>?template=package.md or https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/pull/new/<branch_name>?template=documentation.md.
-->

14
.github/release.yml vendored
View file

@ -6,18 +6,14 @@ changelog:
- title: Fixed
labels:
- bug
- title: Refactors
- title: Miscellaneous
labels:
- refactor
- title: Development
labels:
- ci
- dependencies
- title: Documentation
labels:
- documentation
- testing
- title: Packages/apps
labels:
- package::documentation
- package::addition
- package::breakage
- package::documentation
- package::addition
- package::breakage

View file

@ -9,20 +9,18 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
build_target: [linux, macos, macos-intel, windows]
build_target: [linux, macos, windows]
update_feature: [self-update, no-self-update]
exclude:
- build_target: windows
update_feature: no-self-update
include:
- build_target: linux
os: ubuntu-22.04
os: ubuntu-latest
- build_target: macos
os: macos-15
- build_target: macos-intel
os: macos-15-intel
os: macos-latest
- build_target: windows
os: windows-2022
os: windows-latest
- update_feature: self-update
update_name: "" # we don't want this in the binary filename
- update_feature: no-self-update
@ -30,6 +28,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: rui314/setup-mold@v1 # faster linker
- uses: actions/cache@v4
with:
path: |
@ -40,26 +39,26 @@ jobs:
target
key: ${{ runner.os }}-release-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.OS }}-release-
if: matrix.os == 'ubuntu-22.04'
if: matrix.os == 'ubuntu-latest'
- name: Building
run: cargo build --release -p uad-gui --no-default-features --features wgpu,${{ matrix.update_feature }},img
run: cargo build --release --no-default-features --features wgpu,${{ matrix.update_feature }}
- name: Renaming binaries [Windows]
if: matrix.os == 'windows-2022'
if: matrix.os == 'windows-latest'
run: mv target/release/uad-ng.exe uad-ng-${{ matrix.build_target }}.exe
- name: Renaming binaries [Others]
if: matrix.os != 'windows-2022'
if: matrix.os != 'windows-latest'
run: mv target/release/uad-ng uad-ng${{ matrix.update_name }}-${{ matrix.build_target }}
- name: Tarball Linux/MacOS binary
if: matrix.os != 'windows-2022'
if: matrix.os != 'windows-latest'
run: tar -czf uad-ng${{ matrix.update_name }}-${{ matrix.build_target }}{.tar.gz,}
- name: Install coreutils for macOS
if: startsWith(matrix.os, 'macos')
if: matrix.os == 'macos-latest'
run: brew install coreutils
- name: Create checksums for binaries and archives [Windows]
if: matrix.os == 'windows-2022'
if: matrix.os == 'windows-latest'
run: sha256sum uad-ng-${{ matrix.build_target }}.exe | tee uad-ng-${{ matrix.build_target }}.exe-checksum.txt
- name: Create checksums for binaries and archives [Others]
if: matrix.os != 'windows-2022'
if: matrix.os != 'windows-latest'
run: |
sha256sum uad-ng${{ matrix.update_name }}-${{ matrix.build_target }} | tee uad-ng${{ matrix.update_name }}-${{ matrix.build_target }}-checksum
sha256sum uad-ng${{ matrix.update_name }}-${{ matrix.build_target }}.tar.gz | tee uad-ng${{ matrix.update_name }}-${{ matrix.build_target }}.tar.gz-checksum
@ -68,59 +67,3 @@ jobs:
with:
name: uad-ng${{ matrix.update_name }}-${{ matrix.build_target }}
path: uad-ng-*
build-cli:
name: Building CLI ${{ matrix.build_target }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
include:
- build_target: linux
os: ubuntu-22.04
- build_target: macos
os: macos-15
- build_target: macos-intel
os: macos-15-intel
- build_target: windows
os: windows-2022
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: actions/cache@v4
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target
key: ${{ runner.os }}-release-cli-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.OS }}-release-cli-
if: matrix.os == 'ubuntu-22.04'
- name: Building
run: cargo build --release -p uad-cli
- name: Renaming binaries [Windows]
if: matrix.os == 'windows-2022'
run: mv target/release/uad.exe uad-cli-${{ matrix.build_target }}.exe
- name: Renaming binaries [Others]
if: matrix.os != 'windows-2022'
run: mv target/release/uad uad-cli-${{ matrix.build_target }}
- name: Tarball Linux/MacOS binary
if: matrix.os != 'windows-2022'
run: tar -czf uad-cli-${{ matrix.build_target }}{.tar.gz,}
- name: Install coreutils for macOS
if: startsWith(matrix.os, 'macos')
run: brew install coreutils
- name: Create checksums for binaries and archives [Windows]
if: matrix.os == 'windows-2022'
run: sha256sum uad-cli-${{ matrix.build_target }}.exe | tee uad-cli-${{ matrix.build_target }}.exe-checksum.txt
- name: Create checksums for binaries and archives [Others]
if: matrix.os != 'windows-2022'
run: |
sha256sum uad-cli-${{ matrix.build_target }} | tee uad-cli-${{ matrix.build_target }}-checksum
sha256sum uad-cli-${{ matrix.build_target }}.tar.gz | tee uad-cli-${{ matrix.build_target }}.tar.gz-checksum
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: uad-cli-${{ matrix.build_target }}
path: uad-cli-*

View file

@ -21,29 +21,29 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-22.04, windows-2022, macos-15]
os: [ubuntu-latest, windows-latest, macOS-latest]
lint: [check, test, clippy, fmt]
exclude: # https://github.com/community/community/discussions/7835
- os: windows-2022
- os: windows-latest
lint: clippy
- os: windows-2022
- os: windows-latest
lint: fmt
- os: macos-15
- os: macOS-latest
lint: clippy
- os: macos-15
- os: macOS-latest
lint: fmt
include:
- lint: check
args: " --all-features"
env-flag: "-D warnings"
- lint: test
args: ""
- lint: clippy
args: " --all-features -- -D clippy::all -W clippy::style"
args: " --all --all-features"
- lint: fmt
args: " -- --check"
args: " --all -- --check"
steps:
- uses: actions/checkout@v4
- uses: rui314/setup-mold@v1 # faster linker
- uses: actions/cache@v4
with:
path: |
@ -57,12 +57,11 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy,rustfmt
- shell: bash
run: RUSTFLAGS='${{ matrix.env-flag }}' cargo ${{ matrix.lint }}${{ matrix.args }}
- run: cargo ${{ matrix.lint }}${{ matrix.args }}
coverage:
name: coverage
runs-on: ubuntu-22.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
@ -71,6 +70,8 @@ jobs:
mkdir -p "${HOME}/.local/bin"
curl -sL https://github.com/mozilla/grcov/releases/download/v0.8.19/grcov-x86_64-unknown-linux-gnu.tar.bz2 | tar jxf - -C "${HOME}/.local/bin"
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Set up DeepSource CLI
run: curl https://deepsource.io/cli | sh
- name: Install LLVM-profdata
run: rustup component add llvm-tools-preview
- name: Run tests
@ -79,3 +80,7 @@ jobs:
run: mkdir ./target/coverage
- name: Run GRCOV
run: grcov . --binary-path ./target/debug/ -s . -t lcov --branch --ignore-not-existing --ignore '../*' --ignore "/*" -o ./target/coverage/tests.lcov
- name: Upload to DeepSource
env:
DEEPSOURCE_DSN: ${{ secrets.DEEPSOURCE_DSN }}
run: ./bin/deepsource report --analyzer test-coverage --key rust --value-file ./target/coverage/tests.lcov

View file

@ -14,7 +14,7 @@ jobs:
uses: ./.github/workflows/build_artifacts.yml
release:
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-22.04
runs-on: ubuntu-latest
needs: build
permissions:
contents: write
@ -23,12 +23,7 @@ jobs:
- name: Downloads artifacts
uses: actions/download-artifact@v4
- name: Create release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v1
with:
files: |
uad-ng-*/*
uad-cli-*/*
files: uad-ng-*/*
generate_release_notes: true
body: |
> [!NOTE]
> 📦 **Package list updates don't require a new app version**—UAD-ng automatically fetches the latest package definitions on launch (requires internet connection).

View file

@ -1,11 +0,0 @@
Rudxain <rudxain@localhost.localdomain>
Rudxain <76864299+Rudxain@users.noreply.github.com> Ricardo Fernández Serrata <76864299+Rudxain@users.noreply.github.com>
Anonymoussaurus <50231698+AnonymousWP@users.noreply.github.com> AnonymousWP <50231698+AnonymousWP@users.noreply.github.com>
Anonymoussaurus <anonymouswp@oxygenupdater.com>
# w1nst0n
# 0x192
# “Frigyes06”
# Frigyes
# Frigyes06
# Frigyes Erdosi-Szucs
# Frigyes Erdosi Szucs

View file

@ -2,42 +2,12 @@
## For who is this guide?
This guide is meant for users who want to contribute to the codebase of Universal Android Debloater Next Generation, whether that is the application code or [the "database"-file for adding packages](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/How-to-contribute). To keep all processes streamlined and consistent, we're asking you to stick to this guide whenever contributing.
This guide is meant for users who want to contribute to the codebase of Universal Android Debloater Next Generation, whether that is the application code or the JSON-file for adding packages. To keep all processes streamlined and consistent, we're asking you to stick to this guide whenever contributing.
Even though the guide is made for contributors, it's also strongly recommended that the UAD-ng team sticks to these guidelines. After all, we're a prime example.
## What are the guidelines?
### Mass edits
If you've performed massive edits via automation, you must specify what automation you used. For example, if you ran the command:
```sh
sed -i 's/a/b/' resources/assets/uad_lists.json
```
You should copy-paste that cmd to the pull-request description. This rule applies even if you use "proper" cmds such as `jq`, which safely edit structured data. And it also applies to AI, *especially* LLMs.
This is required so that we can review your big patch without reading it. This improves [transparency](https://en.wikipedia.org/wiki/Transparency_(behavior)), which makes you more trust-worthy! Bonus points if you can provide a sequence of cmds that proves your patch contains exactly what you said it does. For the simple `sed` case, something like:
```sh
# alt: `gh pr checkout 0000 && git checkout main`
git remote add fork https://github.com/user/uadng
git fetch fork
# example commit hash from upstream (not fork);
# more reproducible than branch-name
git checkout beefcafe
sed -i 's/a/b/' resources/assets/uad_lists.json
# compare unstaged change with commit from fork
git diff cafebeef
```
Should be enough.
You should be careful with mass-editing anyways. Even if the verification is successful, the effects [might not be what you expect](https://en.wikipedia.org/wiki/Scunthorpe_problem).
Since AI is non-deterministic, the version number is optional, but it's helpful to know how "intelligent" it is. AI edits are non-reproducible, so "verification scripts" are useless.
### Branching strategy
As for our branching strategy, we're using [Trunk-Based Development](https://trunkbaseddevelopment.com/#one-line-summary).
@ -54,39 +24,46 @@ Do mind that these branch names do only not apply to the addition of packages; f
This is how it looks like and works:
![Trunk-Based Development](https://trunkbaseddevelopment.com/trunk1c.png)
### Syncing branches
### Syncing branches
If you want to [back-port](https://en.wikipedia.org/wiki/Backporting) (GitHub's "Update" and "Sync" buttons) from upstream `main` to any other branch (for testing purposes, or any other reasonable case), it's recommended that you `rebase` rather than `merge` the changes.
**Don't apply changes to/from arbitrary branches**, that's a recipe for chaos! If you encounter a situation where it's absolutely necessary to sync non-`main` branches, whether to `merge` or `rebase` should be decided by the UAD-ng team (with some contributor feedback) on a case-by-case basis.
### Commit messages
As for commits, we prefer using [Conventional Commit Messages](https://gist.github.com/qoomon/5dfcdf8eec66a051ecd85625518cfd13). When working in any of the branches listed above (if there's an existing issue for it), close it using a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword). For more information regarding Conventional Commit Messages, see <https://www.conventionalcommits.org/en/v1.0.0/> as well.
### Issue labels
### Release management
When creating issues, they are automatically labeled based on the [issue template](.github/ISSUE_TEMPLATE/) you choose. These labels help categorize work and generate release notes.
#### Semantic versioning
| Label | Purpose | Issue template |
| ----- | ------- | -------------- |
| `bug` | Software bugs in UAD-ng | Bug Report |
| `enhancement` | New feature requests | Feature Request |
| `package::addition` | Adding new packages to the debloat list | Add new package(s) |
| `package::breakage` | Issues caused by debloating | Debloat issue report |
| `package::documentation` | Updating package descriptions or recommendations | Update apps description or recommendation |
| `documentation` | Improvements to docs/wiki | UAD-ng documentation |
| `ci` | CI/CD related issues | CI/CD |
| `refactor` | Code refactoring | — (maintainer-assigned) |
| `dependencies` | Dependency updates | — (maintainer-assigned) |
We're making use of [semantic versioning](https://semver.org/). We use semantic versioning for two things:
Labels are also used to automatically generate categorized [release notes](.github/release.yml). Each label maps to a changelog section:
1. GitHub Milestones
1. UAD-ng releases
| Label(s) | Changelog category |
| -------- | ------------------ |
| `enhancement` | Features |
| `bug` | Fixed |
| `refactor` | Refactors |
| `package::addition`, `package::breakage`, `package::documentation` | Packages/apps |
| `ci`, `dependencies` | Development |
| `documentation` | Documentation |
Speaking of milestones: it could be that we have a bug-fix release (e.g. 1.0.3), but a contributor submits a PR that adds a new feature. What do we do? Merge after we released 1.0.3? Change the name of the milestone to for example 1.1.0? Or another approach?
In that case, we should closely review the PR and 'compare' it with what semantic versioning has to say about the submitted feature. If the changes are significant enough, we're renaming the milestone to (for example) 1.1.0.
#### Checklist before releasing a new version
- [ ] Make sure the Milestone is completed and if not, check what needs to be done to complete it.
- [ ] Make sure all merged PRs regarding the application follow the Conventional Commit Messages style. This makes sure that when generating a changelog, the changes look consistent, which in turn improves readability.
- [ ] Make sure all merged PRs have the correct labels assigned, as the changelog is generated based on labels.
- [ ] Create a release preparation PR that bumps the Rust package version in `Cargo.toml` and `Cargo.lock`
When all the above has been checked, you can push a tag to `main` to trigger the GitHub Action that creates a release:
- Create the tag: `git tag -s v1.2.3 -am '1.2.3'`
- Push the tag: `git push origin v1.2.3`
Change the version number to whatever version we're releasing.
#### Faulty releases
If we publish a faulty release, for example containing a critical bug, this is how we should deal with it:
We issue a hotfix and keep the faulty release but we'll add warnings to the faulty release in the changelog.

4537
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,13 +1,7 @@
[workspace]
members = [
"crates/uad-core",
"crates/uad-gui",
"crates/uad-cli"
]
resolver = "2"
[workspace.package]
version = "1.2.0"
[package]
name = "uad-ng"
description = "A cross-platform GUI debloater for android devices"
version = "1.1.0"
authors = ["Universal-Debloater-Alliance"]
license = "GPL-3.0"
homepage = "https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation"
@ -15,49 +9,65 @@ repository = "https://github.com/Universal-Debloater-Alliance/universal-android-
readme = "README.md"
keywords = ["debloater", "android", "adb", "privacy", "bloatware"]
categories = ["gui"]
edition = "2024"
edition = "2021"
[workspace.dependencies]
# Core dependencies
[features]
default = ["wgpu", "self-update"]
wgpu = [] # Iced/wgpu is default
self-update = ["flate2", "tar"]
no-self-update = []
[dependencies]
dark-light = { version = "^1.0.0" }
serde = { version = "^1.0", features = ["derive"] }
serde_json = "^1.0"
static_init = "^1.0"
fern = { version = "^0", features = ["colored"] }
chrono = { version = "^0.4", default-features = false, features = [
"std",
"clock",
] }
log = "^0.4"
chrono = { version = "^0.4", default-features = false, features = ["std", "clock"] }
regex = "^1.10.2"
toml = "^0"
dirs = "^6"
ureq = { version = "3", features = ["json"] }
dirs = "^5.0.0"
ureq = { version = "*", features = ["json"] }
retry = "^2.0.0"
iced = { version = "^0.12.0", features = ["advanced", "image"] }
rfd = "^0.14"
csv = "^1.3"
# GUI dependencies
iced = { version = "=0.14.0", features = ["advanced"] }
image = "0.25"
rfd = "^0.17.1"
dark-light = "2"
fern = { version = "^0", features = ["colored"] }
[target.'cfg(not(target_os = "windows"))'.dependencies]
flate2 = { version = "^1", optional = true }
tar = { version = "^0.4", optional = true }
# CLI dependencies
clap = { version = "4.6.1", features = ["derive"] }
tokio = { version = "1.52.3", features = ["full"] }
# Platform-specific dependencies
flate2 = "^1"
tar = "^0.4"
[target.'cfg(target_os = "windows")'.dependencies]
win32console = "^0.1.5"
[workspace.lints.rust]
deprecated_safe = "warn"
[profile.release]
opt-level = "s"
lto = true
strip = "symbols"
[workspace.lints.clippy]
[build-dependencies]
embed-resource = "2.4.2"
[lints.rust]
# "forbid" may cause conflicts with libs (static and dynamic)
unsafe_code = "deny"
[lints.clippy]
undocumented_unsafe_blocks = "forbid"
exit = "deny"
panic_in_result_fn = "warn"
unwrap_used = "warn"
infinite_loop = "warn"
mem_forget = "warn"
string_to_string = "deny"
format_push_string = "warn"
large_include_file = "warn"
shadow_unrelated = "warn"
struct_field_names = "allow" # annoying
module_name_repetitions = "allow" # annoying
disallowed_types = "deny"
disallowed_methods = "deny"
pedantic = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }

View file

@ -1,53 +1,37 @@
# Universal Android Debloater Next Generation
> [!warning]
> **DISCLAIMER**: Use at your own risk. We're not responsible for anything that could happen to your devices.
[![DeepSource](https://app.deepsource.com/gh/Universal-Debloater-Alliance/universal-android-debloater-next-generation.svg/?label=active+issues&show_trend=true&token=LcP1kzmhgcIk06HCJz8LUf7i)](https://app.deepsource.com/gh/Universal-Debloater-Alliance/universal-android-debloater-next-generation/)
[![DeepSource](https://app.deepsource.com/gh/Universal-Debloater-Alliance/universal-android-debloater-next-generation.svg/?label=resolved+issues&show_trend=true&token=LcP1kzmhgcIk06HCJz8LUf7i)](https://app.deepsource.com/gh/Universal-Debloater-Alliance/universal-android-debloater-next-generation/)
[![DeepSource](https://app.deepsource.com/gh/Universal-Debloater-Alliance/universal-android-debloater-next-generation.svg/?label=code+coverage&show_trend=true&token=LcP1kzmhgcIk06HCJz8LUf7i)](https://app.deepsource.com/gh/Universal-Debloater-Alliance/universal-android-debloater-next-generation/)
<div align=center>
<img width=75% alt="screenshot of apps view" src=./resources/screenshots/v1.0.2.png>
</div>
This is a detached fork of the [UAD project](https://github.com/0x192/universal-android-debloater). This aims to improve privacy and efficiency (energy, speed, memory) by removing unnecessary and obscure system apps.
This can also improve security by reducing the [attack surface](https://en.wikipedia.org/wiki/Attack_surface). Read [the wiki](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki) for more details.
**DISCLAIMER**: Use at your own risk. We're not responsible for anything that
could happen to your phone.
<img src="/resources/screenshots/v1.0.2.png" width="850" alt="uad_screenshot">
**Check out the issues, and [feel free to contribute!](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/How-to-contribute)**
**For real-time communication, consider joining our Discord server:**
[![](https://dcbadge.vercel.app/api/server/YHujHzA57a)](https://discord.gg/YHujHzA57a)
**In case you prefer using Matrix (using a Matrix bridge to Discord):**
[<img src="https://matrix.org/images/matrix-logo.svg">](https://matrix.to/#/#uad-ng:matrix.org)
## Summary
This is a detached fork of the [UAD project](https://github.com/0x192/universal-android-debloater), which aims to improve privacy and battery performance by removing unnecessary and obscure system apps.
This can also contribute to improving security by reducing (but not eliminating) [the attack surface](https://en.wikipedia.org/wiki/Attack_surface). Read the [wiki](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki) for more details on getting started. Whilst UAD-ng can remove system apps, it cannot detect or remove potentially malicious system services or drivers baked into the firmware of your device by various vendors; some vendor-specific apps are only UI front-ends to vendor-provided system services, and as such disabling/uninstalling those apps will not stop a service from running. Additional information can be found in package descriptions inside the Universal Android Debloater Next Generation application.
## Documentation
Everything about UAD-ng (and related stuff) can be found on the Wiki, such as:
- [Getting started](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Getting-started)
- Features of this app
- [Usage guide](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Usage)
- Suggested Android app replacements
- How to get the cutting-edge version by [building the source-code](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/Building-from-source)
- Weird things OEMs do
- [Suggested apps for analyzing APKs](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki/How-to-contribute#useful-apps)
## Privacy
UAD-ng does not collect or transmit any user data. The only external connections are `GET` requests to GitHub for fetching the [package list](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/blob/main/resources/assets/uad_lists.json) ([src/core/uad_lists.rs](src/core/uad_lists.rs)) and checking for updates ([src/core/update.rs](src/core/update.rs)).
## Contact
**For real-time communication and support, consider joining our Discord guild:**
[<img width=64em alt="Discord symbol" src=./resources/images/icon_clyde_blurple.svg>](https://discord.gg/CzwbMCPEZa)
**If you prefer using Matrix, we have a bridge to Discord:**
[<img width=64em src=https://matrix.org/images/matrix-favicon.svg>](https://matrix.to/#/#uad-ng:matrix.org)
## Friends
Several projects integrate with or depend on UAD-ng's data and tools:
- **[Canta](https://github.com/samolego/Canta)** — A mobile Android debloater that uses Shizuku for rootless privilege escalation. It integrates with UAD-ng's Universal Debloat List to provide safe package recommendations without requiring a PC.
- **Projects by [Muntashir Akon](https://github.com/MuntashirAkon):**
- **[AppManager](https://github.com/MuntashirAkon/AppManager)** — An advanced Android app manager with powerful debloating features.
- **[android-debloat-list](https://github.com/MuntashirAkon/android-debloat-list)** — A comprehensive, community-driven list of Android packages to debloat, based on UAD-ng's list.
For documentation regarding how to use UAD-ng, the FAQ, building from source and how to decompile/extract APKs, see [our Wiki](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/wiki).
## Special thanks
- [@0x192](https://github.com/0x192) who created the original UAD project.
- [@mawilms](https://github.com/mawilms) for his LotRO plugin manager ([Lembas](https://github.com/mawilms/lembas)) which helped a lot to understand how to use the [Iced](https://github.com/iced-rs/iced) GUI library.
- [@mawilms](https://github.com/mawilms) for his LotRO plugin manager ([Lembas](https://github.com/mawilms/lembas)) which helped a lot to understand how to use the [Iced](https://github.com/hecrj/iced) GUI library.
- [@casperstorm](https://github.com/casperstorm) for the UI/UX inspiration.

View file

@ -1,38 +0,0 @@
# Release management
## Semantic versioning
We're making use of [semantic versioning](https://semver.org/). We use semantic versioning for two things:
1. GitHub Milestones
1. UAD-ng releases
Speaking of milestones: it could be that we have a bug-fix release (e.g. 1.0.3), but a contributor submits a PR that adds a new feature. What do we do? Merge after we released 1.0.3? Change the name of the milestone to for example 1.1.0? Or another approach?
In that case, we should closely review the PR and 'compare' it with what semantic versioning has to say about the submitted feature. If the changes are significant enough, we're renaming the milestone to (for example) 1.1.0.
## Checklist before releasing a new version
- [ ] Make sure the Milestone is completed and if not, check what needs to be done to complete it.
- [ ] Make sure all merged PRs regarding the application follow the Conventional Commit Messages style. This makes sure that when generating a changelog, the changes look consistent, which in turn improves readability.
- [ ] Make sure all merged PRs have the correct labels assigned, as the changelog is generated based on labels.
- [ ] Create a release preparation PR that bumps the UAD-ng version in `Cargo.toml` and `Cargo.lock`.
When all the above has been checked, you can push a tag to `main` to trigger the GitHub Action that creates a release:
- Create the tag: `git tag -s v1.2.3 -am '1.2.3'`
- Push the tag: `git push origin v1.2.3`
Change the version number to whatever version we're releasing.
## Development process
1. Update dependencies right after a new release, so that we start a new milestone with updated dependencies
1. On-going development of bug-fixes and new features etc, along with fixing potential bugs, potentially due to the updated dependencies
1. Release
## Faulty releases
If we publish a faulty release, for example containing a critical bug, this is how we should deal with it:
We issue a hotfix and keep the faulty release but we'll add warnings to the faulty release in the changelog.

View file

@ -1,11 +1,9 @@
const META: &str = "resources/assets/manifest.rc";
use std::{env, error::Error};
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo::rerun-if-changed={META}");
if std::env::var("CARGO_CFG_TARGET_FAMILY")? == "windows" {
embed_resource::compile(META, embed_resource::NONE)
.manifest_optional()
.unwrap();
fn main() -> Result<(), Box<dyn Error>> {
if env::var("CARGO_CFG_TARGET_FAMILY")? == "windows" {
embed_resource::compile("resources/assets/manifest.rc", embed_resource::NONE);
}
Ok(())
}

View file

@ -1,7 +0,0 @@
disallowed-types = [
{ path = "iced::widget::Text", reason = "Use [`crate::gui::widgets::text`] instead. For further details, see #523 and #858" },
]
disallowed-methods= [
{ path = "iced::widget::text", reason = "Use [`crate::gui::widgets::text`] instead. For further details, see #523 and #858" },
]

View file

@ -1,52 +0,0 @@
[package]
name = "uad-cli"
version.workspace = true
authors.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
readme.workspace = true
keywords.workspace = true
categories = ["command-line-utilities"]
edition.workspace = true
[[bin]]
name = "uad"
path = "src/main.rs"
[dependencies]
uad-core = { path = "../uad-core" }
clap.workspace = true
clap_complete = "4.4"
tokio.workspace = true
serde.workspace = true
serde_json.workspace = true
log.workspace = true
chrono.workspace = true
toml.workspace = true
dirs.workspace = true
ureq.workspace = true
retry.workspace = true
csv.workspace = true
rustyline = "14.0"
[lints.rust]
deprecated_safe = "warn"
[lints.clippy]
undocumented_unsafe_blocks = "deny"
exit = "deny"
panic_in_result_fn = "warn"
infinite_loop = "warn"
mem_forget = "warn"
implicit_clone = "warn"
format_push_string = "warn"
large_include_file = "warn"
shadow_unrelated = "warn"
struct_field_names = "allow" # annoying
disallowed_types = "deny"
disallowed_methods = "deny"
allow_attributes_without_reason = "warn"
pedantic = { level = "warn", priority = -1 }

View file

@ -1,44 +0,0 @@
#!/usr/bin/env bash
# Example usage script for UAD CLI
# Check if uad-cli is available
if ! command -v uad &> /dev/null; then
echo "uad command not found. Please build and install uad-cli first."
exit 1
fi
echo "=== UAD CLI Usage Examples ==="
echo
echo "1. List connected devices:"
uad devices
echo
echo "2. List all enabled packages:"
uad list --state enabled | head -20
echo "... (showing first 20)"
echo
echo "3. Search for Google packages:"
uad list --search google | head -10
echo "... (showing first 10)"
echo
echo "4. Show info about a package (example):"
echo "uad info com.google.android.gms"
echo
echo "5. Dry-run uninstall (safe to test):"
echo "uad uninstall com.example.package --dry-run"
echo
echo "6. Start interactive mode:"
echo "uad repl"
echo
echo "=== Generate shell completions ==="
echo "For bash: uad completions bash > ~/.local/share/bash-completion/completions/uad"
echo "For zsh: uad completions zsh > ~/.local/share/zsh/site-functions/_uad"
echo "For fish: uad completions fish > ~/.config/fish/completions/uad.fish"

View file

@ -1,470 +0,0 @@
use clap::CommandFactory;
use clap_complete::{Shell, generate};
use std::collections::{HashMap, HashSet};
use std::io::Write;
use uad_core::adb::{ACommand, PmListPacksFlag};
use uad_core::sync::{
CorePackage, Phone, User, apply_pkg_state_commands, get_devices_list, get_package_state,
run_adb_shell_action,
};
use uad_core::uad_lists::{Package, PackageState, Removal, UadList, load_debloat_lists};
use uad_core::utils::{matches_search, truncate_description};
use crate::device::{NO_DEVICES_FOUND, get_target_device, get_user};
use crate::filters::{ListFilter, RemovalFilter, StateFilter};
use crate::{Cli, print_or_exit, println_or_exit};
/// List all connected Android devices
pub fn list_devices() -> Result<(), Box<dyn std::error::Error>> {
println_or_exit!("Scanning for connected devices...");
let devices = get_devices_list();
if devices.is_empty() {
return Err(NO_DEVICES_FOUND.into());
}
println_or_exit!("\nFound {} device(s):\n", devices.len());
for device in &devices {
println_or_exit!(" Model: {}", device.model);
println_or_exit!(" Serial: {}", device.adb_id);
println_or_exit!(" Android SDK: {}", device.android_sdk);
if !device.user_list.is_empty() {
println_or_exit!(" Users: {} user(s)", device.user_list.len());
for user in &device.user_list {
let protected = if user.protected { " (protected)" } else { "" };
println_or_exit!(" - User ID: {}{}", user.id, protected);
}
}
println_or_exit!();
}
Ok(())
}
/// Context for package filtering and display
pub struct PackageListContext {
pub state_filter: Option<StateFilter>,
pub removal_filter: Option<RemovalFilter>,
pub list_filter: Option<ListFilter>,
pub search: Option<String>,
}
impl PackageListContext {
/// Check if package passes all filters
pub fn filter_package(
&self,
pkg_name: &str,
pkg_info: Option<&Package>,
pkg_state: PackageState,
) -> bool {
// Removal filter
if let Some(removal) = self.removal_filter {
if !removal.matches(pkg_info) {
return false;
}
}
// State filter
if let Some(state) = self.state_filter {
if !state.matches(pkg_state) {
return false;
}
}
// List filter
if let Some(list) = self.list_filter {
if !list.matches(pkg_info) {
return false;
}
}
// Search filter
if let Some(ref search_term) = self.search {
let description = pkg_info.map(|p| p.description.as_str());
if !matches_search(pkg_name, search_term, description) {
return false;
}
}
true
}
/// Determine what information to show based on active filters
pub fn display_config(&self) -> DisplayConfig {
DisplayConfig {
show_state: self.state_filter.is_none_or(|f| !f.is_specific()),
show_removal: self.removal_filter.is_none_or(|f| !f.is_specific()),
}
}
}
pub struct DisplayConfig {
pub show_state: bool,
pub show_removal: bool,
}
/// List packages on a device with filtering
pub fn list_packages(
device: Option<String>,
state_filter: Option<StateFilter>,
removal_filter: Option<RemovalFilter>,
list_filter: Option<ListFilter>,
search: Option<String>,
user_id: Option<u16>,
) -> Result<(), Box<dyn std::error::Error>> {
let target_device = get_target_device(device)?;
let uad_lists = load_debloat_lists(false).unwrap_or_else(|lists| lists);
println_or_exit!(
"Listing packages on: {} ({})\n",
target_device.model,
target_device.adb_id
);
let context = PackageListContext {
state_filter,
removal_filter,
list_filter,
search,
};
let pm_flag = state_filter.and_then(StateFilter::to_pm_flag);
let system_packages = ACommand::new()
.shell(&target_device.adb_id)
.pm()
.list_packages_sys(pm_flag, user_id)?;
let displayed_count = display_package_list(
&system_packages,
&uad_lists,
&target_device.adb_id,
user_id,
&context,
)?;
if displayed_count == 0 {
println_or_exit!(" No packages found matching the specified filters.");
} else {
println_or_exit!("\nTotal: {} package(s)", displayed_count);
}
Ok(())
}
/// Display a list of packages with their info
pub fn display_package_list(
packages: &[String],
uad_lists: &HashMap<String, Package>,
device_serial: &str,
user_id: Option<u16>,
context: &PackageListContext,
) -> Result<usize, Box<dyn std::error::Error>> {
let config = context.display_config();
let mut displayed_count = 0;
let enabled_packages: HashSet<String> = ACommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(Some(PmListPacksFlag::OnlyEnabled), user_id)
.unwrap_or_default()
.into_iter()
.collect();
let disabled_packages: HashSet<String> = ACommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(Some(PmListPacksFlag::OnlyDisabled), user_id)
.unwrap_or_default()
.into_iter()
.collect();
for pkg_name in packages {
let pkg_info = uad_lists.get(pkg_name);
let pkg_state = if enabled_packages.contains(pkg_name) {
PackageState::Enabled
} else if disabled_packages.contains(pkg_name) {
PackageState::Disabled
} else {
PackageState::Uninstalled
};
if !context.filter_package(pkg_name, pkg_info, pkg_state) {
continue;
}
display_package_entry(pkg_name, pkg_info, pkg_state, &config);
displayed_count += 1;
}
Ok(displayed_count)
}
/// Display a single package entry
pub fn display_package_entry(
pkg_name: &str,
pkg_info: Option<&Package>,
pkg_state: PackageState,
config: &DisplayConfig,
) {
print_or_exit!("[");
if let Some(info) = pkg_info {
if config.show_removal {
print_or_exit!("{}", info.removal);
if config.show_state {
print_or_exit!(" - ");
}
}
if config.show_state {
print_or_exit!("{}", pkg_state);
}
print_or_exit!("] {}", pkg_name);
if !info.description.is_empty() {
print_or_exit!(" - {}", truncate_description(&info.description, 80));
}
} else {
if config.show_removal {
print_or_exit!("Unlisted");
if config.show_state {
print_or_exit!(" - ");
}
}
if config.show_state {
print_or_exit!("{}", pkg_state);
}
print_or_exit!("] {}", pkg_name);
}
println_or_exit!();
}
/// Change the state of one or more packages
pub fn change_package_state(
packages: &[String],
device: Option<String>,
user_id: Option<u16>,
dry_run: bool,
target_state: PackageState,
action_name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
if packages.is_empty() {
return Err("No packages specified".into());
}
let target_device = get_target_device(device)?;
let user = get_user(&target_device, user_id)?;
let uad_lists = load_debloat_lists(false).unwrap_or_else(|lists| lists);
println!(
"{} {} package(s) on: {} ({})\n",
action_name,
packages.len(),
target_device.model,
target_device.adb_id
);
if dry_run {
println!("DRY RUN - No changes will be made\n");
}
for pkg_name in packages {
process_package_state_change(
pkg_name,
&target_device,
user,
target_state,
dry_run,
&uad_lists,
)?;
println!();
}
if dry_run {
println!("Dry run completed. No changes were made.");
} else {
println!("Operation completed successfully.");
}
Ok(())
}
/// Process state change for a single package
fn process_package_state_change(
pkg_name: &str,
device: &Phone,
user: User,
target_state: PackageState,
dry_run: bool,
uad_lists: &HashMap<String, Package>,
) -> Result<(), Box<dyn std::error::Error>> {
let current_state = get_package_state(&device.adb_id, pkg_name, Some(user.id))
.ok_or("Package not found on device")?;
println!(" {} ({})", pkg_name, current_state);
if current_state == target_state {
println!(" → Already in target state, skipping");
return Ok(());
}
let pkg_info = uad_lists.get(pkg_name);
if let Some(info) = pkg_info {
if info.removal == Removal::Unsafe {
println!(" ⚠ WARNING: This package is marked as UNSAFE to remove!");
}
}
let core_pkg = CorePackage {
name: pkg_name.to_string(),
description: pkg_info.map(|p| p.description.clone()).unwrap_or_default(),
removal: pkg_info.map(|p| p.removal).unwrap_or(Removal::Unlisted),
state: current_state,
list: pkg_info.map(|p| p.list).unwrap_or(UadList::Unlisted),
};
let commands = apply_pkg_state_commands(&core_pkg, target_state, user, device);
if dry_run {
for cmd in &commands {
println!(" Would run: {}", cmd);
}
} else {
execute_with_fallback(
pkg_name,
target_state,
&core_pkg,
user,
device,
&commands,
" ",
)?;
}
Ok(())
}
/// Execute commands and verify package state with fallback
pub fn execute_with_fallback(
package: &str,
target_state: PackageState,
core_pkg: &CorePackage,
user: User,
device: &Phone,
commands: &[String],
indent: &str,
) -> Result<(), Box<dyn std::error::Error>> {
// Capture the before-state of packages on other users for cross-user detection
let before_cross_user_states =
uad_core::sync::capture_cross_user_states(package, &device.adb_id, user.id, device);
// Execute commands
for cmd in commands {
match run_adb_shell_action(&device.adb_id, cmd.as_str()) {
Ok(_) => println!("{}{}", indent, cmd),
Err(e) => {
return Err(format!("{indent}✗ Failed to execute `{cmd}`: {e:?}").into());
}
}
}
// Verify package state and attempt fallback if needed
let actual_state = match get_package_state(&device.adb_id, package, Some(user.id)) {
Some(state) => state,
None if target_state == PackageState::Uninstalled => PackageState::Uninstalled,
None => {
return Err(format!(
"Package '{package}' was not found on device for user {}",
user.id
)
.into());
}
};
if actual_state != target_state {
println!(
"{}⚠ Package state verification failed: expected {:?}, got {:?}",
indent, target_state, actual_state
);
// Attempt fallback
if let Ok(fallback_action) =
uad_core::sync::attempt_fallback(core_pkg, target_state, actual_state, user, device)
{
println!("{}↻ Fallback: {}", indent, fallback_action);
} else {
println!("{}✗ No fallback available", indent);
}
}
// Check for cross-user behavior if operation succeeded
if actual_state == target_state {
if let Some(notification) = uad_core::sync::detect_cross_user_behavior(
package,
device.adb_id.as_str(),
user.id,
target_state,
actual_state,
device,
&before_cross_user_states,
) {
println!("{} {}", indent, notification);
}
}
Ok(())
}
/// Show detailed information about a package
pub fn show_package_info(
package: &str,
device: Option<String>,
user_id: Option<u16>,
) -> Result<(), Box<dyn std::error::Error>> {
println!("Package: {}\n", package);
let uad_lists = load_debloat_lists(false).unwrap_or_else(|lists| lists);
if let Some(pkg_info) = uad_lists.get(package) {
println!("UAD Information:");
println!(" List: {}", pkg_info.list);
println!(" Removal: {}", pkg_info.removal);
println!(" Description: {}", pkg_info.description);
println!();
} else {
println!(" Not found in UAD lists (unlisted package)\n");
}
if let Some(device_id) = device {
let target_device = get_target_device(Some(device_id))?;
let user = get_user(&target_device, user_id)?;
println!("Device: {} ({})", target_device.model, target_device.adb_id);
println!("User: {}", user.id);
let state = get_package_state(&target_device.adb_id, package, Some(user.id))
.ok_or("Package not found on device")?;
println!(" State: {}", state);
}
Ok(())
}
/// Update UAD package lists from remote repository
pub fn update_lists() -> Result<(), Box<dyn std::error::Error>> {
println!("Updating UAD package lists from remote repository...");
match load_debloat_lists(true) {
Ok(_lists) => {
println!("✓ Successfully updated package lists");
Ok(())
}
Err(_lists) => Err("Failed to update lists from remote, using cached version".into()),
}
}
/// Generate shell completion script
pub fn generate_completions(shell: Shell) {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
generate(shell, &mut cmd, name, &mut std::io::stdout());
}

View file

@ -1,47 +0,0 @@
use uad_core::sync::{Phone, User, get_devices_list};
pub const NO_DEVICES_FOUND: &str =
"No devices found. Make sure ADB is installed and devices are connected.";
/// Get target device, either by serial or first available
pub fn get_target_device(device: Option<String>) -> Result<Phone, Box<dyn std::error::Error>> {
let devices = get_devices_list();
if devices.is_empty() {
return Err(NO_DEVICES_FOUND.into());
}
let target_device = if let Some(device_id) = device {
devices
.iter()
.find(|d| d.adb_id == device_id)
.ok_or("Device not found")?
.clone()
} else {
if devices.len() > 1 {
eprintln!(
"Warning: Multiple devices found, using first one: {}",
devices[0].adb_id
);
}
devices[0].clone()
};
Ok(target_device)
}
/// Get user from device, creating a basic one if not found
pub fn get_user(device: &Phone, user_id: Option<u16>) -> Result<User, Box<dyn std::error::Error>> {
let uid = user_id.unwrap_or(0);
if let Some(user) = device.user_list.iter().find(|u| u.id == uid) {
Ok(*user)
} else {
// Create a basic user if not found in list
Ok(User {
id: uid,
index: 0,
protected: false,
})
}
}

View file

@ -1,98 +0,0 @@
use clap::ValueEnum;
use uad_core::adb::PmListPacksFlag;
use uad_core::uad_lists::{Package, PackageState, Removal, UadList};
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum StateFilter {
/// Show all packages regardless of state
All,
/// Show only enabled packages
Enabled,
/// Show only disabled packages
Disabled,
/// Show only uninstalled packages
Uninstalled,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum RemovalFilter {
All,
Recommended,
Advanced,
Expert,
Unsafe,
Unlisted,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ListFilter {
All,
Aosp,
Carrier,
Google,
Misc,
Oem,
Pending,
Unlisted,
}
impl StateFilter {
pub fn to_pm_flag(self) -> Option<PmListPacksFlag> {
match self {
Self::Enabled => Some(PmListPacksFlag::OnlyEnabled),
Self::Disabled => Some(PmListPacksFlag::OnlyDisabled),
Self::Uninstalled | Self::All => Some(PmListPacksFlag::IncludeUninstalled),
}
}
pub fn matches(self, pkg_state: PackageState) -> bool {
match self {
Self::All => true,
Self::Enabled => pkg_state == PackageState::Enabled,
Self::Disabled => pkg_state == PackageState::Disabled,
Self::Uninstalled => pkg_state == PackageState::Uninstalled,
}
}
pub fn is_specific(self) -> bool {
matches!(self, Self::Enabled | Self::Disabled | Self::Uninstalled)
}
}
impl RemovalFilter {
pub fn matches(self, pkg_info: Option<&Package>) -> bool {
match pkg_info {
Some(info) => match self {
Self::All => true,
Self::Recommended => info.removal == Removal::Recommended,
Self::Advanced => info.removal == Removal::Advanced,
Self::Expert => info.removal == Removal::Expert,
Self::Unsafe => info.removal == Removal::Unsafe,
Self::Unlisted => info.removal == Removal::Unlisted,
},
None => matches!(self, Self::All | Self::Unlisted),
}
}
pub fn is_specific(self) -> bool {
!matches!(self, Self::All)
}
}
impl ListFilter {
pub fn matches(self, pkg_info: Option<&Package>) -> bool {
match pkg_info {
Some(info) => match self {
Self::All => true,
Self::Aosp => info.list == UadList::Aosp,
Self::Carrier => info.list == UadList::Carrier,
Self::Google => info.list == UadList::Google,
Self::Misc => info.list == UadList::Misc,
Self::Oem => info.list == UadList::Oem,
Self::Pending => info.list == UadList::Pending,
Self::Unlisted => info.list == UadList::Unlisted,
},
None => matches!(self, Self::All | Self::Unlisted),
}
}
}

View file

@ -1,251 +0,0 @@
#![allow(
clippy::needless_continue,
clippy::collapsible_if,
clippy::uninlined_format_args,
clippy::map_unwrap_or,
clippy::unnecessary_wraps,
reason = "Suppress non-critical pedantic/style lints to keep build green"
)]
use clap::{Parser, Subcommand};
use clap_complete::Shell;
use std::process::ExitCode;
use uad_core::uad_lists::PackageState;
mod commands;
mod device;
mod filters;
mod output;
mod repl;
use filters::{ListFilter, RemovalFilter, StateFilter};
#[derive(Parser)]
#[command(name = "uad")]
#[command(about = "Universal Android Debloater - Command Line Interface", long_about = None)]
#[command(version)]
#[command(propagate_version = true)]
pub struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// List connected Android devices
Devices,
/// List packages on a device
#[command(name = "list", visible_alias = "ls")]
List {
/// Device serial number (optional, uses first device if not specified)
#[arg(short, long)]
device: Option<String>,
/// Filter by package state
#[arg(short, long, value_enum)]
state: Option<StateFilter>,
/// Filter by removal category
#[arg(short, long, value_enum)]
removal: Option<RemovalFilter>,
/// Filter by UAD list
#[arg(short, long, value_enum)]
list: Option<ListFilter>,
/// Search pattern (matches package name or description)
#[arg(short = 'q', long)]
search: Option<String>,
/// User ID (defaults to 0)
#[arg(short, long)]
user: Option<u16>,
},
/// Uninstall packages (default removal action)
#[command(visible_alias = "rm")]
Uninstall {
/// Package names to uninstall
packages: Vec<String>,
/// Device serial number (optional, uses first device if not specified)
#[arg(short, long)]
device: Option<String>,
/// User ID (defaults to 0)
#[arg(short, long)]
user: Option<u16>,
/// Dry run - show what would be done without actually doing it
#[arg(long)]
dry_run: bool,
},
/// Restore (reinstall) packages
#[command(visible_alias = "restore")]
Enable {
/// Package names to restore/enable
packages: Vec<String>,
/// Device serial number (optional, uses first device if not specified)
#[arg(short, long)]
device: Option<String>,
/// User ID (defaults to 0)
#[arg(short, long)]
user: Option<u16>,
/// Dry run - show what would be done without actually doing it
#[arg(long)]
dry_run: bool,
},
/// Disable packages (keeps data but prevents execution)
Disable {
/// Package names to disable
packages: Vec<String>,
/// Device serial number (optional, uses first device if not specified)
#[arg(short, long)]
device: Option<String>,
/// User ID (defaults to 0)
#[arg(short, long)]
user: Option<u16>,
/// Dry run - show what would be done without actually doing it
#[arg(long)]
dry_run: bool,
},
/// Show detailed information about a package
Info {
/// Package name
package: String,
/// Device serial number (optional, uses first device if not specified)
#[arg(short, long)]
device: Option<String>,
/// User ID (defaults to 0)
#[arg(short, long)]
user: Option<u16>,
},
/// Update UAD package lists from remote repository
Update,
/// Generate shell completion script
Completions {
/// Shell to generate completions for
#[arg(value_enum)]
shell: Shell,
},
/// Start interactive REPL mode
#[command(visible_alias = "shell")]
Repl {
/// Device serial number (optional, uses first device if not specified)
#[arg(short, long)]
device: Option<String>,
/// User ID (defaults to 0)
#[arg(short, long)]
user: Option<u16>,
},
}
#[tokio::main]
async fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("Error: {err}");
ExitCode::FAILURE
}
}
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
match cli.command {
Commands::Devices => {
commands::list_devices()?;
}
Commands::List {
device,
state,
removal,
list,
search,
user,
} => {
commands::list_packages(device, state, removal, list, search, user)?;
}
Commands::Uninstall {
packages,
device,
user,
dry_run,
} => {
commands::change_package_state(
&packages,
device,
user,
dry_run,
PackageState::Uninstalled,
"Uninstalling",
)?;
}
Commands::Enable {
packages,
device,
user,
dry_run,
} => {
commands::change_package_state(
&packages,
device,
user,
dry_run,
PackageState::Enabled,
"Enabling",
)?;
}
Commands::Disable {
packages,
device,
user,
dry_run,
} => {
commands::change_package_state(
&packages,
device,
user,
dry_run,
PackageState::Disabled,
"Disabling",
)?;
}
Commands::Info {
package,
device,
user,
} => {
commands::show_package_info(&package, device, user)?;
}
Commands::Update => {
commands::update_lists()?;
}
Commands::Completions { shell } => {
commands::generate_completions(shell);
}
Commands::Repl { device, user } => {
repl::repl_mode(device, user)?;
}
}
Ok(())
}

View file

@ -1,18 +0,0 @@
/// Helper macro to handle broken pipe errors gracefully
/// When piping to commands like `head`, we want to exit cleanly when the pipe closes
#[macro_export]
macro_rules! println_or_exit {
() => {
let _ = writeln!(std::io::stdout());
};
($($arg:tt)*) => {
let _ = writeln!(std::io::stdout(), $($arg)*);
};
}
#[macro_export]
macro_rules! print_or_exit {
($($arg:tt)*) => {
let _ = write!(std::io::stdout(), $($arg)*);
};
}

View file

@ -1,374 +0,0 @@
use rustyline::DefaultEditor;
use rustyline::error::ReadlineError;
use std::collections::HashMap;
use std::io::Write;
use uad_core::adb::ACommand;
use uad_core::sync::{CorePackage, Phone, User, apply_pkg_state_commands, get_package_state};
use uad_core::uad_lists::{Package, PackageState, Removal, UadList, load_debloat_lists};
use crate::commands::{PackageListContext, display_package_list, execute_with_fallback};
use crate::device::{get_target_device, get_user};
use crate::filters::StateFilter;
use crate::println_or_exit;
enum ReplAction {
Continue,
Exit,
}
/// Start interactive REPL mode
pub fn repl_mode(
device: Option<String>,
user_id: Option<u16>,
) -> Result<(), Box<dyn std::error::Error>> {
println!("Universal Android Debloater - Interactive Mode");
println!("Type 'help' for available commands, 'exit' or 'quit' to leave\n");
let target_device = get_target_device(device)?;
let user = get_user(&target_device, user_id)?;
println!(
"Connected to: {} ({})",
target_device.model, target_device.adb_id
);
println!("User: {}\n", user.id);
let uad_lists = load_debloat_lists(false).unwrap_or_else(|lists| lists);
let mut rl = DefaultEditor::new()?;
// Try to load history
let history_file = dirs::cache_dir().map(|d| d.join("uad").join("cli_history.txt"));
if let Some(ref path) = history_file {
let _ = rl.load_history(path);
}
loop {
let readline = rl.readline("uad> ");
match readline {
Ok(line) => {
match handle_repl_line(&line, &mut rl, &target_device, user, user_id, &uad_lists) {
Ok(ReplAction::Continue) => {}
Ok(ReplAction::Exit) => break,
Err(e) => {
eprintln!("Error: {}", e);
}
}
}
Err(ReadlineError::Interrupted) => {
println!("Interrupted (Ctrl-C). Type 'exit' to quit.");
continue;
}
Err(ReadlineError::Eof) => {
println!("Goodbye!");
break;
}
Err(err) => {
eprintln!("Error: {:?}", err);
break;
}
}
}
// Save history
if let Some(ref path) = history_file {
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = rl.save_history(path);
}
Ok(())
}
/// Handle a single line of REPL input
fn handle_repl_line(
line: &str,
rl: &mut DefaultEditor,
device: &Phone,
user: User,
user_id: Option<u16>,
uad_lists: &HashMap<String, Package>,
) -> Result<ReplAction, Box<dyn std::error::Error>> {
let line = line.trim();
if line.is_empty() {
return Ok(ReplAction::Continue);
}
let _ = rl.add_history_entry(line);
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.is_empty() {
return Ok(ReplAction::Continue);
}
match parts[0] {
"help" => print_repl_help(),
"exit" | "quit" => {
println!("Goodbye!");
return Ok(ReplAction::Exit);
}
"list" | "ls" => {
handle_list_command(&parts[1..], device, user_id, uad_lists)?;
}
"info" => {
handle_info_command(&parts[1..], device, user.id, uad_lists)?;
}
"uninstall" | "rm" => {
handle_state_change_command(
&parts[1..],
device,
user,
PackageState::Uninstalled,
"Uninstalling",
uad_lists,
)?;
}
"enable" | "restore" => {
handle_state_change_command(
&parts[1..],
device,
user,
PackageState::Enabled,
"Enabling",
uad_lists,
)?;
}
"disable" => {
handle_state_change_command(
&parts[1..],
device,
user,
PackageState::Disabled,
"Disabling",
uad_lists,
)?;
}
"device" => {
println!(
"Device: {} ({}), Android SDK: {}, User: {}",
device.model, device.adb_id, device.android_sdk, user.id
);
}
"clear" => {
print!("\x1B[2J\x1B[1;1H");
}
_ => {
eprintln!(
"Unknown command: '{}'. Type 'help' for available commands.",
parts[0]
);
}
}
Ok(ReplAction::Continue)
}
/// Parse REPL arguments into filters
struct ReplListArgs {
state_filter: Option<StateFilter>,
search_term: Option<String>,
}
impl ReplListArgs {
fn parse(args: &[&str]) -> Result<Self, String> {
let mut state_filter = None;
let mut search_term = None;
let mut i = 0;
while i < args.len() {
match args[i] {
"--state" | "-s" => {
if i + 1 >= args.len() {
return Err("--state requires a value".to_string());
}
state_filter = match args[i + 1].to_lowercase().as_str() {
"enabled" => Some(StateFilter::Enabled),
"disabled" => Some(StateFilter::Disabled),
"uninstalled" => Some(StateFilter::Uninstalled),
"all" => Some(StateFilter::All),
_ => return Err(format!("Invalid state: {}", args[i + 1])),
};
i += 2;
}
"--search" | "-q" => {
if i + 1 >= args.len() {
return Err("--search requires a value".to_string());
}
search_term = Some(args[i + 1].to_string());
i += 2;
}
_ => {
return Err(format!("Unknown option: {}", args[i]));
}
}
}
Ok(Self {
state_filter,
search_term,
})
}
}
/// Handle list command in REPL
fn handle_list_command(
args: &[&str],
device: &Phone,
user_id: Option<u16>,
uad_lists: &HashMap<String, Package>,
) -> Result<(), Box<dyn std::error::Error>> {
let parsed = ReplListArgs::parse(args)?;
let pm_flag = parsed.state_filter.and_then(StateFilter::to_pm_flag);
let system_packages = ACommand::new()
.shell(&device.adb_id)
.pm()
.list_packages_sys(pm_flag, user_id)?;
let context = PackageListContext {
state_filter: parsed.state_filter,
removal_filter: None,
list_filter: None,
search: parsed.search_term,
};
let displayed_count = display_package_list(
&system_packages,
uad_lists,
&device.adb_id,
user_id,
&context,
)?;
if displayed_count == 0 {
println_or_exit!(" No packages found.");
} else {
println_or_exit!("\nTotal: {} package(s)", displayed_count);
}
Ok(())
}
/// Handle info command in REPL
fn handle_info_command(
args: &[&str],
device: &Phone,
user_id: u16,
uad_lists: &HashMap<String, Package>,
) -> Result<(), Box<dyn std::error::Error>> {
if args.is_empty() {
eprintln!("Usage: info <package_name>");
return Ok(());
}
let package = args[0];
println!("Package: {}", package);
if let Some(pkg_info) = uad_lists.get(package) {
println!(" List: {}", pkg_info.list);
println!(" Removal: {}", pkg_info.removal);
println!(" Description: {}", pkg_info.description);
} else {
println!(" Not found in UAD lists (unlisted package)");
}
let state = get_package_state(&device.adb_id, package, Some(user_id))
.ok_or("Package not found on device")?;
println!(" State: {}", state);
Ok(())
}
/// Handle state change command in REPL
fn handle_state_change_command(
args: &[&str],
device: &Phone,
user: User,
target_state: PackageState,
action_name: &str,
uad_lists: &HashMap<String, Package>,
) -> Result<(), Box<dyn std::error::Error>> {
if args.is_empty() {
eprintln!(
"Usage: {} <package_name> [package_name...]",
action_name.to_lowercase()
);
return Ok(());
}
for pkg_name in args {
process_package_change(pkg_name, device, user, target_state, action_name, uad_lists)?;
}
Ok(())
}
/// Process state change for a single package in REPL
fn process_package_change(
pkg_name: &str,
device: &Phone,
user: User,
target_state: PackageState,
action_name: &str,
uad_lists: &HashMap<String, Package>,
) -> Result<(), Box<dyn std::error::Error>> {
let current_state = get_package_state(&device.adb_id, pkg_name, Some(user.id))
.ok_or("Package not found on device")?;
println!("{} {} (current: {})", action_name, pkg_name, current_state);
if current_state == target_state {
println!(" → Already in target state, skipping");
return Ok(());
}
let pkg_info = uad_lists.get(pkg_name);
if let Some(info) = pkg_info {
if info.removal == Removal::Unsafe {
println!(" ⚠ WARNING: This package is marked as UNSAFE to remove!");
}
}
let core_pkg = CorePackage {
name: pkg_name.to_string(),
description: pkg_info.map(|p| p.description.clone()).unwrap_or_default(),
removal: pkg_info.map(|p| p.removal).unwrap_or(Removal::Unlisted),
state: current_state,
list: pkg_info.map(|p| p.list).unwrap_or(UadList::Unlisted),
};
let commands = apply_pkg_state_commands(&core_pkg, target_state, user, device);
execute_with_fallback(
pkg_name,
target_state,
&core_pkg,
user,
device,
&commands,
" ",
)
}
/// Print REPL help message
fn print_repl_help() {
println!("Available commands:");
println!(" list [--state <state>] [--search <term>]");
println!(" List packages with optional filters");
println!(" info <package_name>");
println!(" Show information about a package");
println!(" uninstall <package_name> [package_name...]");
println!(" Uninstall one or more packages");
println!(" enable <package_name> [package_name...]");
println!(" Enable/restore one or more packages");
println!(" disable <package_name> [package_name...]");
println!(" Disable one or more packages");
println!(" device");
println!(" Show current device information");
println!(" clear");
println!(" Clear the screen");
println!(" help");
println!(" Show this help message");
println!(" exit, quit");
println!(" Exit the interactive mode");
}

View file

@ -1,52 +0,0 @@
[package]
name = "uad-core"
version.workspace = true
authors.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
readme.workspace = true
keywords.workspace = true
categories = ["command-line-utilities"]
edition.workspace = true
[features]
default = []
self-update = ["dep:flate2", "dep:tar"]
[dependencies]
serde.workspace = true
serde_json.workspace = true
log.workspace = true
chrono.workspace = true
toml.workspace = true
dirs.workspace = true
ureq.workspace = true
retry.workspace = true
csv.workspace = true
flate2 = { workspace = true, optional = true }
tar = { workspace = true, optional = true }
[target.'cfg(target_os = "windows")'.dependencies]
win32console.workspace = true
[lints.rust]
deprecated_safe = "warn"
[lints.clippy]
undocumented_unsafe_blocks = "forbid"
exit = "deny"
panic_in_result_fn = "warn"
infinite_loop = "warn"
mem_forget = "warn"
implicit_clone = "warn"
format_push_string = "warn"
large_include_file = "warn"
shadow_unrelated = "warn"
struct_field_names = "allow" # annoying
disallowed_types = "deny"
disallowed_methods = "deny"
allow_attributes_without_reason = "warn"
pedantic = { level = "warn", priority = -1 }

View file

@ -1,503 +0,0 @@
#![deny(clippy::unwrap_used)]
//! This module is intended to group everything that's "intrinsic" of ADB.
//!
//! Following the design philosophy of most of Rust `std`,
//! `*Command` are intended to be "thin wrappers" (low-overhead abstractions)
//! around the ADB CLI or `adb_client`
//! ([in the future](https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/issues/700) ),
//! which implies:
//! - no "magic"
//! - no custom commands
//! - no chaining ("piping") of existing commands
//!
//! This guarantees a 1-to-1 mapping between methods and cmds,
//! thereby reducing surprises such as:
//! - Non-atomic operations: consider what happens if a pack changes state
//! in the middle of listing enabled and disabled packs!
//! - Non-standard semantics: what would happen if a new ADB version
//! supports a feature we already defined,
//! but has _slightly_ different behavior?
//!
//! Despite being "low-level", we can still "have cake and eat it too";
//! After all, what's the point of an abstraction if it doesn't come with goodies?:
//! We can reserve some artistic license, such as:
//! - pre-parsing or validanting output, to provide types with invariants
//! - strongly-typed rather than "stringly-typed" APIs
//! - nicer IDE support
//! - compile-time prevention of malformed cmds
//! - implicit enforcement of a narrow set of operations
//!
//! About that last point, if there's ever a need for an ADB feature
//! which these APIs don't expose,
//! please, **PLEASE** refrain from falling-back to any `Command`-like API.
//! Rather, please extend these APIs in a consistent way.
//!
//! Thank you! ❤️
//!
//! For comprehensive info about ADB,
//! [see this](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/master/docs/)
use std::rc::Rc;
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
use crate::utils::is_all_w_c;
use log::{error, info, warn};
/// Convert ADB output bytes to a trimmed UTF-8 string.
/// Uses lossy conversion to prevent panics on non-UTF8 output from certain OEMs.
#[must_use]
pub fn to_trimmed_utf8(v: &[u8]) -> String {
String::from_utf8_lossy(v).trim_end().to_string()
}
#[cfg(debug_assertions)]
#[must_use]
fn is_version_triple(s: &str) -> bool {
let mut components = s.split('.');
for _ in 0..3 {
if !components
.next()
.is_some_and(|comp| comp.as_bytes().iter().all(u8::is_ascii_digit))
{
return false;
}
}
if components.next().is_some() {
return false;
}
true
}
/// Builder object for an Android Debug Bridge CLI command,
/// using the type-state and new-type patterns.
///
/// This is not intended to model the entire ADB API.
/// It only models the subset that concerns UADNG.
///
/// [More info here](https://developer.android.com/tools/adb)
#[derive(Debug)]
pub struct ACommand(std::process::Command);
impl ACommand {
/// `adb` command builder
#[must_use]
pub fn new() -> Self {
Self(std::process::Command::new("adb"))
}
/// `shell` sub-command builder.
///
/// If `device_serial` is empty, it lets ADB choose the default device.
#[must_use]
pub fn shell<S: AsRef<str>>(mut self, device_serial: S) -> ShellCommand {
let serial = device_serial.as_ref();
if !serial.is_empty() {
self.0.args(["-s", serial]);
}
self.0.arg("shell");
ShellCommand(self)
}
/// Header-less list of attached devices (as serials) and their statuses:
/// - USB
/// - TCP/IP: WIFI, Ethernet, etc...
/// - Local emulators
///
/// Status can be (but not limited to):
/// - "unauthorized"
/// - "device"
pub fn devices(mut self) -> Result<Vec<(String, String)>, String> {
self.0.arg("devices");
Ok(self
.run()?
.lines()
.skip(1) // header
.map(|dev_stat| {
let tab_idx = dev_stat
// OS-specific?
.find('\t')
// True on Linux,
// no matter if ADB is piped or connected to terminal
.expect("There must be 1 tab after serial");
(
// serial
dev_stat[..tab_idx].to_string(),
// status
dev_stat[(tab_idx + 1)..].to_string(),
)
})
.collect())
}
/// `version` sub-command
///
/// ## Format
/// This is just a sample,
/// we don't know which guarantees are stable (yet):
/// ```txt
/// Android Debug Bridge version 1.0.41
/// Version 34.0.5-debian
/// Installed as /usr/lib/android-sdk/platform-tools/adb
/// Running on Linux 6.12.12-amd64 (x86_64)
/// ```
///
/// The expected format should be like:
/// ```txt
/// Android Debug Bridge version <num>.<num>.<num>
/// Version <num>.<num>.<num>-<no spaces>
/// Installed as <ANDROID_SDK_HOME>/platform-tools/adb[.exe]
/// Running on <OS/kernel version> (<CPU arch>)
/// ```
#[expect(clippy::panic_in_result_fn, reason = "Assertions are fine")]
pub fn version(mut self) -> Result<String, String> {
self.0.arg("version");
let out = self.run()?;
#[cfg(debug_assertions)]
{
const ADBV: &str = "Android Debug Bridge version ";
const V: &str = "Version ";
let mut lns = out.lines();
assert!(
lns.next()
.is_some_and(|ln| ln.starts_with(ADBV) && is_version_triple(&ln[ADBV.len()..]))
);
assert!(lns.next().is_some_and(|ln| ln.starts_with(V)
&& is_version_triple(&ln[V.len()..ln.find('-').unwrap_or(ln.len())])));
// missing test for valid path
assert!(lns.next().is_some_and(|ln| ln.starts_with("Installed as ")
&& (ln.ends_with("adb") || ln.ends_with("adb.exe"))));
// missing test for x86/ARM (both 64b)
assert!(lns.next().is_some_and(|ln| ln.starts_with("Running on ")));
if lns.next().is_some() {
unreachable!("Expected < 5 lines")
}
}
Ok(out)
}
/// General executor
fn run(self) -> Result<String, String> {
let mut cmd = self.0;
#[cfg(target_os = "windows")]
let cmd = cmd.creation_flags(0x0800_0000); // do not open a cmd window
info!(
"Ran command: adb {}",
cmd.get_args()
.map(|s| s.to_str().unwrap_or_else(|| unreachable!()))
.collect::<Vec<_>>()
.join(" ")
);
match cmd.output() {
Err(e) => {
error!("ADB: {e}");
Err("Cannot run ADB, likely not found".to_string())
}
Ok(o) => {
let stdout = to_trimmed_utf8(&o.stdout);
if o.status.success() {
Ok(stdout)
} else {
let stderr = to_trimmed_utf8(&o.stderr);
// ADB does really weird things:
// Some errors are not redirected to `stderr`
let err = if stdout.is_empty() { stderr } else { stdout };
Err(err)
}
}
}
}
}
impl Default for ACommand {
fn default() -> Self {
Self::new()
}
}
/// Builder object for a command that runs on the device's default `sh` implementation.
/// Typically MKSH, but could be Ash.
///
/// [More info](https://chromium.googlesource.com/aosp/platform/system/core/+/refs/heads/upstream/shell_and_utilities).
#[derive(Debug)]
pub struct ShellCommand(ACommand);
impl ShellCommand {
/// `pm` command builder
pub fn pm(mut self) -> PmCommand {
self.0.0.arg("pm");
PmCommand(self)
}
/// Query a device property value, by its key.
/// These can be of any type:
/// - `boolean`
/// - `int`
/// - chars
/// - etc...
///
/// So to avoid lossy conversions, we return strs
pub fn getprop(mut self, key: &str) -> Result<String, String> {
self.0.0.args(["getprop", key]);
self.0.run()
}
/// Reboots device
pub fn reboot(mut self) -> Result<String, String> {
self.0.0.arg("reboot");
self.0.run()
}
/// Execute an arbitrary shell action string on the device's default shell.
/// The action string is passed as a single argument to `adb shell` and
/// interpreted by the remote shell (which splits on spaces).
pub fn raw(mut self, action: &str) -> Result<String, String> {
self.0.0.arg(action);
self.0.run()
}
}
#[must_use]
pub const fn is_pkg_component(s: &[u8]) -> bool {
if s.is_empty() {
return false;
}
s[0].is_ascii_alphabetic()
&& if s.len() > 1 {
is_all_w_c(s.split_at(1).1)
} else {
true
}
}
/// String with the invariant of being a valid package-name.
/// See [`PackageId::new`] for validation details.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PackageId(Rc<str>);
impl PackageId {
/// Creates a package-ID if it's `"android"` or valid according to:
/// - <https://developer.android.com/guide/topics/manifest/manifest-element.html#package>
/// - <https://developer.android.com/build/configure-app-module#set-application-id>
#[must_use]
pub fn new(p_id: &str) -> Option<Self> {
if p_id == "android" {
return Some(Self(p_id.into()));
}
let mut components = p_id.split('.');
for _ in 0..2 {
if !components
.next()
.is_some_and(|comp| is_pkg_component(comp.as_bytes()))
{
return None;
}
}
if components.all(|comp| is_pkg_component(comp.as_bytes())) {
Some(Self(p_id.into()))
} else {
None
}
}
}
/// `pm list packages` flag/state/type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PmListPacksFlag {
/// `-u`, not to be confused with `-a`
IncludeUninstalled,
/// `-e`
OnlyEnabled,
/// `-d`
OnlyDisabled,
}
impl PmListPacksFlag {
// is there a trait for this?
fn to_str(self) -> &'static str {
match self {
Self::IncludeUninstalled => "-u",
Self::OnlyEnabled => "-e",
Self::OnlyDisabled => "-d",
}
}
}
#[expect(clippy::to_string_trait_impl, reason = "This is not user-facing")]
impl ToString for PmListPacksFlag {
fn to_string(&self) -> String {
self.to_str().to_string()
}
}
const PACK_PREFIX: &str = "package:";
pub const PM_CLEAR_PACK: &str = "pm clear";
/// Builder object for an Android Package Manager command.
/// <https://developer.android.com/tools/adb#pm>
#[derive(Debug)]
#[must_use]
pub struct PmCommand(ShellCommand);
impl PmCommand {
/// `list packages -s` sub-command, [`PACK_PREFIX`] stripped from each element.
///
/// `Ok` variant:
/// - isn't 100% guaranteed to contain valid pack-IDs
/// but you can assume it does (except in `unsafe {}` blocks)
/// - isn't sorted
/// - duplicates never _seem_ to happen, but don't assume uniqueness
pub fn list_packages_sys(
mut self,
f: Option<PmListPacksFlag>,
user_id: Option<u16>,
) -> Result<Vec<String>, String> {
let cmd = &mut self.0.0.0;
cmd.args(["list", "packages", "-s"]);
if let Some(s) = f {
cmd.arg(s.to_str());
}
if let Some(u) = user_id {
cmd.arg("--user");
cmd.arg(u.to_string());
}
self.0.0.run().map(|pack_ls| {
pack_ls
.lines()
.filter_map(|p_ln| {
debug_assert!(p_ln.starts_with(PACK_PREFIX));
let p = &p_ln[PACK_PREFIX.len()..];
if PackageId::new(p).is_some() {
Some(String::from(p))
} else {
warn!("skipping nonstandard package name: {p:?}");
None
}
})
.collect()
})
}
/// `list users` sub-command, deserialized/parsed.
///
/// - <https://source.android.com/docs/devices/admin/multi-user-testing>
/// - <https://stackoverflow.com/questions/37495126/android-get-list-of-users-and-profile-name>
pub fn list_users(mut self) -> Result<Box<[UserInfo]>, String> {
self.0.0.0.args(["list", "users"]);
Ok(self
.0
.0
.run()?
.lines()
.skip(1) // omit header
.map(|ln| {
// this could be optimized by making more API-stability assumptions
let ln = ln.trim_ascii_start();
let ln = ln.strip_prefix("UserInfo").unwrap_or(ln).trim_ascii_start();
let ln = ln.strip_prefix('{').unwrap_or(ln).trim_ascii();
//let run;
let ln = if let Some(l) = ln.strip_suffix("running") {
//run = true;
l.trim_ascii_end()
} else {
//run = false;
ln
};
let ln = ln.strip_suffix('}').unwrap_or(ln).trim_ascii_end();
// https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/android/content/pm/UserInfo.java
// The format looks stable today, but google may change it in future Android versions
// (and very old Androids might differ). Keep parsing defensive.
// Expected shape: "UserInfo{<id>:<name>:<flags>}[ running]"
let mut comps = ln.split(':');
let id = comps
.next()
.expect("There must be at least 1 ':'-separated component")
.parse()
.expect("string assumed to be UID numeral");
//let name = comps
// .next()
// .expect("There must be at least 2 ':'-separated components. 2nd is user-name");
//let flags = u32::from_str_radix(
// comps.next().expect(
// "There must be at least 3 ':'-separated components. 3rd is user bit-flags",
// ),
// 16,
//)
//.expect("string assumed to be hexadecimal bit-flags");
UserInfo {
id,
//name: name.into(),
//flags,
//running: run,
}
})
.collect())
}
}
/// Mirror of AOSP `UserInfo` Java Class, with an extra field
#[derive(Debug, Clone)]
pub struct UserInfo {
id: u16,
//name: Box<str>,
//flags: u32,
//running: bool,
}
impl UserInfo {
#[must_use]
pub const fn get_id(&self) -> u16 {
self.id
}
/*
/// Check if the user was logged-in at the time `pm list users` was invoked
#[must_use]
#[allow(dead_code, reason = "Currently unused by UI; kept for future features")]
pub const fn was_running(&self) -> bool {
self.running
}
*/
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_pack_ids() {
for p_id in [
"",
" ",
".",
"nodots",
"com..example",
"net.hello.",
"org.0example",
"org._foobar",
"the.🎂.is.a.lie",
"EXCLAMATION!!!!",
] {
assert_eq!(PackageId::new(p_id), None);
}
}
#[test]
fn valid_pack_ids() {
for p_id in [
"A.a",
"x.X",
"org.example",
"net.hello",
"uwu.owo",
"Am0Gu5.Zuz",
"net.net.net.net.net.net.net.net.net.net.net",
"com.github.w1nst0n",
"this_.String_.is_.not_.real_",
] {
assert_ne!(PackageId::new(p_id), None);
}
}
}

View file

@ -1,150 +0,0 @@
use crate::CACHE_DIR;
use crate::CONFIG_DIR;
use crate::sync::User;
use crate::utils::DisplayablePath;
use log::error;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::sync::LazyLock;
const DEFAULT_THEME: &str = "Auto (follow system theme)";
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
pub struct Config {
pub general: GeneralSettings,
#[serde(skip_serializing_if = "Vec::is_empty", default = "Vec::new")]
pub devices: Vec<DeviceSettings>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GeneralSettings {
pub theme: String,
pub expert_mode: bool,
pub backup_folder: PathBuf,
}
#[derive(Default, Debug, Clone)]
pub struct BackupSettings {
pub backups: Vec<DisplayablePath>,
pub selected: Option<DisplayablePath>,
pub users: Vec<User>,
pub selected_user: Option<User>,
pub backup_state: String,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct DeviceSettings {
/// Unique serial identifier
pub device_id: String,
pub disable_mode: bool, // should be `enum RemovalMode`
pub multi_user_mode: bool,
#[serde(skip)]
pub backup: BackupSettings,
}
impl Default for GeneralSettings {
fn default() -> Self {
Self {
theme: DEFAULT_THEME.to_string(),
expert_mode: false,
backup_folder: CACHE_DIR.join("backups"),
}
}
}
static CONFIG_FILE: LazyLock<PathBuf> = LazyLock::new(|| CONFIG_DIR.join("config.toml"));
impl Config {
pub fn save_device_settings(
&mut self,
device_settings: DeviceSettings,
general: GeneralSettings,
) {
if let Some(device) = self
.devices
.iter_mut()
.find(|x| x.device_id == device_settings.device_id)
{
*device = device_settings;
} else {
self.devices.push(device_settings);
}
self.general = general;
let toml = toml::to_string(&self).unwrap();
fs::write(&*CONFIG_FILE, toml).expect("Could not write config file to disk!");
}
#[must_use]
pub fn load_configuration_file() -> Self {
match fs::read_to_string(&*CONFIG_FILE) {
Ok(s) => match toml::from_str(&s) {
Ok(config) => return config,
Err(e) => error!("Invalid config file: `{e}`"),
},
Err(e) => error!("Failed to read config file: `{e}`"),
}
error!("Restoring default config file");
let toml = toml::to_string(&Self::default()).unwrap();
fs::write(&*CONFIG_FILE, toml).expect("Could not write config file to disk!");
Self::default()
}
}
#[cfg(test)]
mod tests {
//! Unit tests
use super::*;
use std::path::Path;
// create a clean default config file for testing
fn create_default_config_file() {
let toml = toml::to_string(&Config::default()).unwrap();
fs::write(&*CONFIG_FILE, toml).expect("Could not write config file to disk!");
}
#[test]
fn test_create_default_config_file() {
create_default_config_file();
assert!(CONFIG_FILE.exists());
}
#[test]
fn test_load_configuration_file() {
create_default_config_file();
let config = Config::load_configuration_file();
// non-deterministic
//assert_eq!(config.devices.len(), 0);
assert_eq!(config.general.theme, DEFAULT_THEME);
assert!(!config.general.expert_mode);
assert_eq!(config.general.backup_folder, CACHE_DIR.join("backups"));
}
// non-deterministic
/*
#[test]
fn test_save_changes() {
let mut settings = Settings::default();
let device_id = "test_device".to_string();
settings.device.device_id = device_id.clone();
Config::save_changes(&settings, &device_id);
let config = Config::load_configuration_file();
assert_eq!(config.devices[0].device_id, device_id);
}
*/
#[test]
fn test_default_config() {
let config = Config::default();
assert_eq!(config.devices.len(), 0);
assert_eq!(config.general.theme, DEFAULT_THEME);
assert!(!config.general.expert_mode);
assert_eq!(config.general.backup_folder, CACHE_DIR.join("backups"));
}
#[test]
fn test_config_file_path() {
assert_eq!(&*CONFIG_FILE, Path::new(&*CONFIG_DIR.join("config.toml")));
}
}

View file

@ -1,23 +0,0 @@
#![allow(
clippy::missing_panics_doc,
clippy::missing_errors_doc,
clippy::collapsible_if,
clippy::uninlined_format_args,
clippy::result_unit_err,
reason = "Doc+style pedantic lints are out-of-scope for this pass"
)]
pub mod adb;
pub mod config;
pub mod save;
pub mod sync;
pub mod uad_lists;
pub mod update;
pub mod utils;
use std::path::PathBuf;
use std::sync::LazyLock;
pub static CONFIG_DIR: LazyLock<PathBuf> =
LazyLock::new(|| utils::setup_uad_dir(&dirs::config_dir().expect("Can't detect config dir")));
pub static CACHE_DIR: LazyLock<PathBuf> =
LazyLock::new(|| utils::setup_uad_dir(&dirs::cache_dir().expect("Can't detect cache dir")));

View file

@ -1,663 +0,0 @@
use crate::{
adb::{ACommand as AdbCommand, PM_CLEAR_PACK, PackageId},
uad_lists::PackageState,
};
use log::{error, info};
use retry::{OperationResult, delay::Fixed, retry};
use serde::{Deserialize, Serialize};
/// An Android device, typically a phone
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Phone {
/// Non-market name
pub model: String, // could be `Copy`
/// Android API level version
pub android_sdk: u8,
/// In theory, `len < u16::MAX` _should_ always be `true`.
/// In practice, `len <= u8::MAX`.
pub user_list: Vec<User>,
/// Unique serial identifier
pub adb_id: String, // could be `Copy`
}
impl Default for Phone {
fn default() -> Self {
Self {
model: "fetching devices...".to_string(),
android_sdk: 0,
user_list: vec![],
adb_id: String::default(),
}
}
}
impl std::fmt::Display for Phone {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.model)
}
}
/// `UserInfo` but relevant to UAD
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub struct User {
pub id: u16,
pub index: usize,
pub protected: bool,
}
impl std::fmt::Display for User {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "user {}", self.id)
}
}
/// An enum to contain different variants for errors yielded by ADB.
#[derive(Debug, Clone)]
pub enum AdbError {
Generic(String),
}
/// Run an arbitrary shell action via the typed ADB wrapper.
/// This replaces the deprecated `adb_shell_command`.
///
/// If `serial` is empty, it lets ADB choose the default device.
pub fn run_adb_shell_action<S: AsRef<str>>(
device_serial: S,
action: &str,
) -> Result<String, AdbError> {
let serial = device_serial.as_ref();
match AdbCommand::new().shell(serial).raw(action) {
Ok(o) => {
if ["Error", "Failure"].iter().any(|&e| o.contains(e)) {
let friendly_msg = make_friendly_error_message(&o, action);
return Err(AdbError::Generic(friendly_msg));
}
info!("{action} -> {o}");
Ok(o)
}
Err(err) => {
if !err.contains("[not installed for") {
let friendly_msg = make_friendly_error_message(&err, action);
return Err(AdbError::Generic(friendly_msg));
}
Err(AdbError::Generic(err))
}
}
}
/// Convert common OEM-specific ADB error messages into user-friendly explanations.
fn make_friendly_error_message(error_output: &str, action: &str) -> String {
// Common Samsung errors
if error_output.contains("DELETE_FAILED_USER_RESTRICTED") {
return format!(
"Cannot uninstall: This package is restricted by the device manufacturer (Samsung Knox or similar).\n\
Error: {error_output}\n\
Tip: Try disabling the package instead, or check device settings for Knox/security restrictions."
);
}
if error_output.contains("NOT_INSTALLED_FOR_USER") {
return format!(
"Package is not installed for the current user.\n\
Error: {error_output}\n\
Tip: The package may be installed for a different user profile or work profile."
);
}
// Empty package name error
if error_output.contains("Shell cannot change component state for null") {
return format!(
"Invalid package: Empty package name detected.\n\
Error: {error_output}\n\
Tip: Please refresh the package list and try again."
);
}
// Generic permission errors
if error_output.contains("Permission denied")
|| error_output.contains("INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE")
{
return format!(
"Permission denied: Insufficient privileges to perform this action.\n\
Error: {error_output}\n\
Tip: This may require root access or the package is protected by the system."
);
}
// Work profile / managed device errors
if error_output.contains("DELETE_FAILED_DEVICE_POLICY_MANAGER") {
return format!(
"Cannot modify: Package is managed by device policy (MDM/EMM).\n\
Error: {error_output}\n\
Tip: Contact your IT administrator if this is a work device."
);
}
// Generic failure with context
format!("{action} -> {error_output}")
}
/// If `None`, returns an empty String, not " --user 0"
#[must_use]
pub fn user_flag(user_id: Option<User>) -> String {
user_id
.map(|user| format!(" --user {}", user.id))
.unwrap_or_default()
}
// Minimum information for processing adb commands
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct CorePackage {
pub name: String,
pub description: String,
#[serde(default)]
pub removal: crate::uad_lists::Removal,
#[serde(default)]
pub state: PackageState,
#[serde(default)]
pub list: crate::uad_lists::UadList,
}
#[must_use]
pub fn apply_pkg_state_commands(
package: &CorePackage,
wanted_state: PackageState,
selected_user: User,
phone: &Phone,
) -> Vec<String> {
// https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki/ADB-reference
// ALWAYS PUT THE COMMAND THAT CHANGES THE PACKAGE STATE FIRST!
let commands = match wanted_state {
PackageState::Enabled => match package.state {
PackageState::Disabled => vec!["pm enable"],
PackageState::Uninstalled => match phone.android_sdk {
i if i >= 23 => vec!["cmd package install-existing"],
21 | 22 => vec!["pm unhide"],
19 | 20 => vec!["pm unblock", PM_CLEAR_PACK],
_ => unreachable!("already prevented by the GUI"),
},
_ => vec![],
},
PackageState::Disabled => match package.state {
PackageState::Uninstalled | PackageState::Enabled => {
if supports_disabling(phone) {
vec!["pm disable-user", "am force-stop", PM_CLEAR_PACK]
} else {
vec![]
}
}
_ => vec![],
},
PackageState::Uninstalled => match package.state {
PackageState::Enabled | PackageState::Disabled => match phone.android_sdk {
sdk if sdk >= 23 => vec!["pm uninstall"], // > Marshmallow (6.0)
21 | 22 => vec!["pm hide", PM_CLEAR_PACK], // Lollipop (5.x)
_ => vec!["pm block", PM_CLEAR_PACK], // Disable mode is unavailable on older devices because the specific ADB commands need root
},
_ => vec![],
},
PackageState::All => vec![],
}; // this should be a `tinyvec`, as `len <= 4`
let user = supports_multi_user(phone).then_some(selected_user);
request_builder(&commands, &package.name, user)
}
/// Build a command request to be sent via ADB to a device.
/// `commands` accepts one or more ADB shell commands
/// which act on a common `package` and `user`.
#[must_use]
pub fn request_builder(commands: &[&str], package: &str, user: Option<User>) -> Vec<String> {
// Defense-in-depth: `package` is interpolated verbatim into a device-shell
// action, so refuse any invalid name/ID. Every current caller already
// reconciles the name against the live device package list before reaching
// here, so this rejects nothing legitimate — it just keeps the no-injection
// guarantee local to the sink instead of relying on each caller to sanitise.
// Fail closed: emit no command for a malformed name rather than an injectable
// device-shell string.
if PackageId::new(package).is_none() {
error!("request_builder: refusing invalid package name: {package:?}");
return Vec::new();
}
let maybe_user_flag = user_flag(user);
commands
.iter()
.map(|c| format!("{c}{maybe_user_flag} {package}"))
.collect()
}
/// Get the model by querying the `ro.product.model` property.
///
/// If `serial` is empty, it lets ADB choose the default device.
#[must_use]
pub fn get_device_model(serial: &str) -> String {
AdbCommand::new()
.shell(serial)
.getprop("ro.product.model")
.unwrap_or_else(|err| {
eprintln!("ERROR: {err}");
error!("{err}");
if err.contains("adb: no devices/emulators found") {
"no devices/emulators found".to_string()
} else {
err
}
})
}
/// Get the brand by querying the `ro.product.brand` property.
///
/// If `serial` is empty, it lets ADB choose the default device.
#[must_use]
pub fn get_device_brand(serial: &str) -> String {
AdbCommand::new()
.shell(serial)
.getprop("ro.product.brand")
// `trim` is just-in-case
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
/// Get Android SDK version by querying the
// `ro.build.version.sdk` property or defaulting to 0.
///
/// If `device_serial` is empty, it lets ADB choose the default device.
#[must_use]
pub fn get_android_sdk(device_serial: &str) -> u8 {
AdbCommand::new()
.shell(device_serial)
.getprop("ro.build.version.sdk")
.map_or(0, |sdk| {
sdk.parse().expect("SDK version numeral must be valid")
})
}
/// Capture the current state of a package across all non-protected users.
/// This is used to detect cross-user behavior by comparing before and after states.
///
/// Only includes users where the package exists (Some state). Users where the package
/// doesn't exist (None) are not tracked.
#[must_use]
pub fn capture_cross_user_states(
package_name: &str,
device_serial: &str,
target_user_id: u16,
phone: &Phone,
) -> Vec<(u16, PackageState)> {
phone
.user_list
.iter()
.filter(|u| !u.protected && u.id != target_user_id)
.filter_map(|u| {
verify_package_state(package_name, device_serial, Some(u.id)).map(|state| (u.id, state))
})
.collect()
}
/// Detect cross-user behavior and return appropriate notification message.
/// This handles unexpected cross-user behavior:
/// - Case A: Uninstall → Restore (package appears on other users)
/// - Case B: Uninstall → Uninstall (package disappears from other users that previously had it)
/// - Case C: Restore → Restore (package appears on other users)
#[must_use]
pub fn detect_cross_user_behavior(
package_name: &str,
device_serial: &str,
target_user_id: u16,
wanted_state: PackageState,
actual_state: PackageState,
phone: &Phone,
before_states: &[(u16, PackageState)],
) -> Option<String> {
// Only check if operation was successful on target user
if actual_state != wanted_state {
return None;
}
// Only check if we have multiple users
if phone.user_list.len() < 2 {
return None;
}
let after_states =
check_cross_user_package_existence(package_name, device_serial, target_user_id, phone);
match wanted_state {
PackageState::Uninstalled => {
if after_states.is_empty() {
// Case B: Uninstall → Uninstall (check if all users lost package)
let affected_users: Vec<_> = before_states
.iter()
.filter(|(uid, before_state)| {
// Only flag if the package was installed/enabled/disabled before
*before_state != PackageState::Uninstalled
// And is NOT in after_states (doesn't exist in usable state anymore)
&& !after_states.iter().any(|(after_uid, _)| after_uid == uid)
})
.map(|(uid, _)| uid)
.collect();
if affected_users.is_empty() {
None
} else {
let user_list = affected_users
.iter()
.map(|uid| format!("user {uid}"))
.collect::<Vec<_>>()
.join(", ");
Some(format!(
"Detected cross-user uninstall: package was also uninstalled from {user_list} after uninstalling from user {target_user_id}"
))
}
} else {
// Case A: Uninstall → Restore (package appears on other users)
let user_list = after_states
.iter()
.map(|(uid, state)| format!("user {uid} ({state:?})"))
.collect::<Vec<_>>()
.join(", ");
Some(format!(
"Detected cross-user restoration: package exists on {user_list} after uninstalling from user {target_user_id}"
))
}
}
PackageState::Enabled | PackageState::Disabled => {
// Case C: Restore → Restore (package appears on other users)
// Check if a user didn't have the package before (not tracked or package didn't exist).
// Detects packages that appear on users where they didn't exist previously (OEM cross-user restoration).
let was_package_absent_before = |uid: &u16| {
before_states
.iter()
.find(|(before_uid, _)| before_uid == uid)
.is_none_or(|(_, before_state)| *before_state == PackageState::Uninstalled)
};
let newly_appeared: Vec<_> = after_states
.iter()
.filter(|(uid, _after_state)| was_package_absent_before(uid))
.collect();
if newly_appeared.is_empty() {
None
} else {
let user_list = newly_appeared
.iter()
.map(|(uid, state)| format!("user {uid} ({state:?})"))
.collect::<Vec<_>>()
.join(", ");
Some(format!(
"Detected cross-user restoration: package exists on {user_list} after {} from user {target_user_id}",
if wanted_state == PackageState::Enabled {
"enabling"
} else {
"disabling"
}
))
}
}
PackageState::All => None,
}
}
#[must_use]
pub const fn supports_disabling(dev: &Phone) -> bool {
// >= Marshmallow (6.0)
dev.android_sdk >= 23
}
/// Check if it might support multi-user mode,
/// by simply comparing SDK version.
/// `true` isn't reliable, you can only trust `false`.
///
/// See:
/// - <https://source.android.com/docs/devices/admin/multi-user#applying_the_overlay>
/// - <https://developer.android.com/reference/android/os/UserManager#supportsMultipleUsers()>
#[must_use]
pub const fn supports_multi_user(dev: &Phone) -> bool {
// >= Lollipop (5.0)
dev.android_sdk >= 21
}
/// Check if a `user_id` is protected on a device by trying
/// to list associated packages.
///
/// If `device_serial` is empty, it lets ADB choose the default device.
pub fn is_protected_user<S: AsRef<str>>(user_id: u16, device_serial: S) -> bool {
AdbCommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(None, Some(user_id))
.is_err()
}
#[must_use]
pub fn list_users_idx_prot(device_serial: &str) -> Vec<User> {
AdbCommand::new()
.shell(device_serial)
.pm()
.list_users()
.map(|out| {
out.into_iter()
.enumerate()
.map(|(i, user)| {
let id = user.get_id();
User {
id,
index: i,
protected: is_protected_user(id, device_serial),
}
})
.collect()
})
.unwrap_or_default()
}
/// This matches serials (`getprop ro.serialno`)
/// that are authorized by the user.
#[must_use]
pub fn get_devices_list() -> Vec<Phone> {
retry(
Fixed::from_millis(500).take(if cfg!(debug_assertions) { 3 } else { 10 }),
|| match AdbCommand::new().devices() {
Ok(devices) => {
let mut device_list: Vec<Phone> = vec![];
if devices.iter().all(|(_, stat)| stat != "device") {
return OperationResult::Retry(vec![]);
}
for device in devices {
let serial = &device.0;
device_list.push(Phone {
model: format!("{} {}", get_device_brand(serial), get_device_model(serial)),
android_sdk: get_android_sdk(serial),
user_list: list_users_idx_prot(serial),
adb_id: serial.clone(),
});
}
OperationResult::Ok(device_list)
}
Err(err) => {
error!("get_devices_list() -> {err}");
let test: Vec<Phone> = vec![];
OperationResult::Retry(test)
}
},
)
.unwrap_or_default()
}
#[must_use]
pub fn initial_load() -> bool {
match AdbCommand::new().devices() {
Ok(_devices) => true,
Err(_err) => false,
}
}
/// Get the current state of a package on a device
#[must_use]
pub fn get_package_state(
device_serial: &str,
package_name: &str,
user_id: Option<u16>,
) -> Option<PackageState> {
use crate::adb::{ACommand as AdbCommand, PmListPacksFlag};
// Check if package is enabled
if let Ok(enabled_packages) = AdbCommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(Some(PmListPacksFlag::OnlyEnabled), user_id)
&& enabled_packages.contains(&package_name.to_string())
{
return Some(PackageState::Enabled);
}
// Check if package is disabled
if let Ok(disabled_packages) = AdbCommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(Some(PmListPacksFlag::OnlyDisabled), user_id)
&& disabled_packages.contains(&package_name.to_string())
{
return Some(PackageState::Disabled);
}
// Check if package exists at all (including uninstalled)
if let Ok(all_packages) = AdbCommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(Some(PmListPacksFlag::IncludeUninstalled), user_id)
&& all_packages.contains(&package_name.to_string())
{
return Some(PackageState::Uninstalled);
}
// Package not found at all - it doesn't exist on this device/user
None
}
/// Verify the current state of a package on a device.
/// Returns the package state, or `None` if the package doesn't exist.
#[must_use]
pub fn verify_package_state(
package_name: &str,
device_serial: &str,
user_id: Option<u16>,
) -> Option<PackageState> {
get_package_state(device_serial, package_name, user_id)
}
/// Check if a package exists on any other users besides the target user.
/// This helps detect OEM-specific cross-user restoration behavior.
///
/// Only includes users where the package exists in a non-uninstalled state
/// (i.e., Enabled or Disabled).
#[must_use]
pub fn check_cross_user_package_existence(
package_name: &str,
device_serial: &str,
target_user_id: u16,
phone: &Phone,
) -> Vec<(u16, PackageState)> {
let mut other_user_states = Vec::new();
for user in &phone.user_list {
if user.id != target_user_id
&& !user.protected
&& let Some(state) = verify_package_state(package_name, device_serial, Some(user.id))
&& state != PackageState::Uninstalled
{
other_user_states.push((user.id, state));
}
}
other_user_states
}
/// Creates a `CorePackage` with the specified state, preserving other fields from the original.
fn package_with_state(package: &CorePackage, state: PackageState) -> CorePackage {
CorePackage {
state,
..package.clone()
}
}
/// Executes the first available command and returns the result.
fn execute_first_command(commands: &[String], phone: &Phone) -> Result<(), String> {
if commands.is_empty() {
return Err("No command available".to_string());
}
AdbCommand::new()
.shell(&phone.adb_id)
.raw(&commands[0])
.map(|_| ())
.map_err(|err| err.clone())
}
/// Attempt fallback action when package state verification fails
pub fn attempt_fallback(
package: &CorePackage,
wanted_state: PackageState,
actual_state: PackageState,
user: User,
phone: &Phone,
) -> Result<String, String> {
match (wanted_state, actual_state) {
// Case 1: Tried to uninstall but package was reinstalled -> disable it
(PackageState::Uninstalled, PackageState::Enabled) => {
let pkg = package_with_state(package, PackageState::Enabled);
let commands = apply_pkg_state_commands(&pkg, PackageState::Disabled, user, phone);
execute_first_command(&commands, phone)
.map(|()| "disabled package instead of uninstalling".to_string())
.map_err(|e| format!("Failed to disable package: {e}"))
}
// Case 2: Tried to disable but package re-enabled itself -> try uninstall
(PackageState::Disabled, PackageState::Enabled) => {
let pkg = package_with_state(package, PackageState::Enabled);
let commands = apply_pkg_state_commands(&pkg, PackageState::Uninstalled, user, phone);
execute_first_command(&commands, phone)
.map_err(|e| format!("Failed to uninstall: {e}"))?;
// Verify the package was actually uninstalled
match verify_package_state(&package.name, &phone.adb_id, Some(user.id)) {
Some(PackageState::Uninstalled) | None => {
Ok("uninstalled package instead of disabling".to_string())
}
_ => Err("Package still exists after uninstall attempt".to_string()),
}
}
// Case 3: Tried to enable but package was disabled -> try uninstall then reinstall
(PackageState::Enabled, PackageState::Disabled) => {
let pkg = package_with_state(package, PackageState::Disabled);
let uninstall_cmds =
apply_pkg_state_commands(&pkg, PackageState::Uninstalled, user, phone);
execute_first_command(&uninstall_cmds, phone)
.map_err(|e| format!("Failed to uninstall for reinstall: {e}"))?;
// Now try to reinstall/enable
let pkg_uninstalled = package_with_state(package, PackageState::Uninstalled);
let enable_cmds =
apply_pkg_state_commands(&pkg_uninstalled, PackageState::Enabled, user, phone);
if enable_cmds.is_empty() {
return Ok("uninstalled package but couldn't reinstall".to_string());
}
execute_first_command(&enable_cmds, phone)
.map(|()| "uninstalled and reinstalled package to enable it".to_string())
.map_err(|e| format!("Failed to reinstall package: {e}"))
}
// Other cases - no fallback available
_ => Err(format!(
"No fallback available for wanted state {wanted_state:?} and actual state {actual_state:?}"
)),
}
}

View file

@ -1,299 +0,0 @@
#![warn(clippy::unwrap_used)]
use crate::{
adb::{ACommand as AdbCommand, PmListPacksFlag},
sync::{CorePackage, User},
uad_lists::{PackageHashMap, PackageState, Removal, UadList},
};
use chrono::{DateTime, offset::Utc};
use csv::Writer;
use log::error;
use std::{
collections::HashSet,
fmt, fs,
path::{Path, PathBuf},
};
/// Canonical shortened name of the application
pub const NAME: &str = "UAD-ng";
/// Full name of the application
pub const FULL_NAME: &str = "Universal Android Debloater Next Generation";
pub const EXPORT_FILE_NAME: &str = "selection_export.txt";
/// Returns `true` if `c` matches the regex `\w`
#[inline]
#[must_use]
pub const fn is_w(c: u8) -> bool {
// https://github.com/rust-lang/rust/issues/93279
// https://github.com/rust-lang/rust/issues/83623
(c == b'_') | c.is_ascii_alphanumeric()
}
/// Returns `true` if `s` matches the regex `^\w+$`
#[must_use]
pub const fn is_all_w_c(s: &[u8]) -> bool {
let mut i = 0;
while i < s.len() {
if !is_w(s[i]) {
return false;
}
i += 1;
}
true
}
// Takes a time-stamp parameter,
// for purity and testability.
//
// The TZ is generic, because testing requires UTC,
// while users get the local-aware version.
#[expect(
clippy::needless_pass_by_value,
reason = "Timestamps should be fresh, no need to borrow"
)]
#[must_use]
pub fn generate_backup_name<T>(t: DateTime<T>) -> String
where
T: chrono::TimeZone,
T::Offset: std::fmt::Display,
{
t.format("uninstalled_packages_%Y%m%d.csv").to_string()
}
#[derive(Debug, Clone, Copy)]
pub enum Error {
DialogClosed,
}
#[must_use]
pub fn fetch_packages(
uad_lists: &PackageHashMap,
device_serial: &str,
user_id: Option<u16>,
) -> Vec<CorePackage> {
let all_sys_packs = AdbCommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(Some(PmListPacksFlag::IncludeUninstalled), user_id)
.unwrap_or_default();
let enabled_sys_packs: HashSet<String> = AdbCommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(Some(PmListPacksFlag::OnlyEnabled), user_id)
.unwrap_or_default()
.into_iter()
.collect();
let disabled_sys_packs: HashSet<String> = AdbCommand::new()
.shell(device_serial)
.pm()
.list_packages_sys(Some(PmListPacksFlag::OnlyDisabled), user_id)
.unwrap_or_default()
.into_iter()
.collect();
let mut description;
let mut removal;
let mut state;
let mut list;
let mut user_package: Vec<CorePackage> = Vec::new();
for pack_name in all_sys_packs {
let p_name = &pack_name;
description = String::from("[No description]: CONTRIBUTION WELCOMED");
removal = Removal::Unlisted;
state = PackageState::Uninstalled;
list = UadList::Unlisted;
if let Some(package) = uad_lists.get(p_name) {
if !package.description.is_empty() {
description = package.description.clone();
}
removal = package.removal;
list = package.list;
}
if enabled_sys_packs.contains(p_name) {
state = PackageState::Enabled;
} else if disabled_sys_packs.contains(p_name) {
state = PackageState::Disabled;
}
let package = CorePackage {
name: p_name.clone(),
description,
removal,
state,
list,
};
user_package.push(package);
}
user_package.sort_by_key(|package| package.name.to_lowercase());
user_package
}
#[must_use]
pub fn setup_uad_dir(dir: &Path) -> PathBuf {
let dir = dir.join("uad");
if let Err(e) = fs::create_dir_all(&dir) {
error!("Can't create directory: {}", dir.display());
panic!("{e}");
}
dir
}
/// Open a directory or file with the system's default file manager.
pub fn open_url(dir: PathBuf) {
const OPENER: &str = match std::env::consts::OS.as_bytes() {
b"windows" => "explorer",
b"macos" => "open",
// "linux"
_ => "xdg-open",
};
match std::process::Command::new(OPENER).arg(dir).output() {
Ok(o) => {
if !o.status.success() {
// Use lossy conversion for stderr - some systems (like Windows)
// may output non-UTF8 characters in error messages
let stderr = String::from_utf8_lossy(&o.stderr);
let stderr_trimmed = stderr.trim_end();
if stderr_trimmed.is_empty() {
error!("Can't open URL: command failed with no error message");
} else {
error!("Can't open the following URL: {stderr_trimmed}");
}
}
}
Err(e) => error!("Failed to run command to open the file explorer: {e}"),
}
}
#[rustfmt::skip]
#[must_use]
pub fn last_modified_date(file: PathBuf) -> DateTime<Utc> {
fs::metadata(file).map_or_else(|_| Utc::now(), |metadata| match metadata.modified() {
Ok(time) => time.into(),
Err(_) => Utc::now(),
})
}
#[must_use]
pub fn format_diff_time_from_now(date: DateTime<Utc>) -> String {
let now: DateTime<Utc> = Utc::now();
let last_update = now - date;
if last_update.num_days() == 0 {
if last_update.num_hours() == 0 {
last_update.num_minutes().to_string() + " min(s) ago"
} else {
last_update.num_hours().to_string() + " hour(s) ago"
}
} else {
last_update.num_days().to_string() + " day(s) ago"
}
}
/// Export selected package names.
/// File will be saved in same directory where UAD-ng is located.
pub fn export_selection(package_names: &[String]) -> Result<bool, String> {
let selected = package_names.join("\n");
match fs::write(EXPORT_FILE_NAME, selected) {
Ok(()) => Ok(true),
Err(err) => Err(err.to_string()),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DisplayablePath {
pub path: PathBuf,
}
impl fmt::Display for DisplayablePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let stem = self.path.file_stem().map_or_else(
|| {
error!("[PATH STEM]: No file stem found");
"[File steam not found]".to_string()
},
|p| {
if let Ok(stem) = p.to_os_string().into_string() {
stem
} else {
error!("[PATH ENCODING]: {}", self.path.display());
"[PATH ENCODING ERROR]".to_string()
}
},
);
write!(f, "{stem}")
}
}
/// Export uninstalled packages in a csv file.
/// Exported information will contain package name and description.
pub fn export_packages(user: User, phone_packages: &[Vec<CorePackage>]) -> Result<bool, String> {
let backup_file = generate_backup_name(chrono::Local::now());
let file = fs::File::create(backup_file).map_err(|err| err.to_string())?;
let mut wtr = Writer::from_writer(file);
wtr.write_record(["Package Name", "Description"])
.map_err(|err| err.to_string())?;
let uninstalled_packages: Vec<&CorePackage> = phone_packages[user.index]
.iter()
.filter(|p| p.state == PackageState::Uninstalled)
.collect();
for package in uninstalled_packages {
wtr.write_record([&package.name, &package.description.replace('\n', " ")])
.map_err(|err| err.to_string())?;
}
wtr.flush().map_err(|err| err.to_string())?;
Ok(true)
}
/// Truncate description to fit within max length, taking only the first line
#[must_use]
pub fn truncate_description(desc: &str, max_len: usize) -> String {
let first_line = desc.split('\n').next().unwrap_or("").trim_end();
if first_line.len() <= max_len {
first_line.to_string()
} else {
format!("{}...", &first_line[..max_len.saturating_sub(3)])
}
}
/// Check if package matches search term (checks name and description)
#[must_use]
pub fn matches_search(pkg_name: &str, search_term: &str, pkg_description: Option<&str>) -> bool {
let search_lower = search_term.to_lowercase();
if pkg_name.to_lowercase().contains(&search_lower) {
return true;
}
if let Some(description) = pkg_description {
if description.to_lowercase().contains(&search_lower) {
return true;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn backup_name() {
assert_eq!(
generate_backup_name(chrono::Utc.timestamp_millis_opt(0).unwrap()),
"uninstalled_packages_19700101.csv".to_string()
);
}
}

View file

@ -1,62 +0,0 @@
[package]
name = "uad-gui"
version.workspace = true
authors.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
readme.workspace = true
keywords.workspace = true
categories = ["gui"]
edition.workspace = true
[[bin]]
name = "uad-ng"
path = "src/main.rs"
[features]
default = ["wgpu", "self-update", "img"]
wgpu = [] # Iced/wgpu is default
self-update = ["flate2", "tar"]
no-self-update = []
img = ["image", "iced/image"]
[dependencies]
uad-core = { path = "../uad-core", features = ["self-update"] }
iced.workspace = true
image = { workspace = true, optional = true }
rfd.workspace = true
dark-light.workspace = true
fern.workspace = true
chrono.workspace = true
dirs.workspace = true
log.workspace = true
flate2 = { workspace = true, optional = true }
tar = { workspace = true, optional = true }
[target.'cfg(target_os = "windows")'.dependencies]
win32console.workspace = true
[build-dependencies]
embed-resource = "3"
[lints.rust]
deprecated_safe = "warn"
[lints.clippy]
undocumented_unsafe_blocks = "forbid"
exit = "deny"
panic_in_result_fn = "warn"
infinite_loop = "warn"
mem_forget = "warn"
implicit_clone = "warn"
format_push_string = "warn"
large_include_file = "warn"
shadow_unrelated = "warn"
struct_field_names = "allow" # annoying
disallowed_types = "deny"
disallowed_methods = "deny"
allow_attributes_without_reason = "warn"
pedantic = { level = "warn", priority = -1 }

View file

@ -1,23 +0,0 @@
use crate::style;
use crate::theme::Theme;
use iced::Element;
use iced::widget::button::Button;
/// Wrapper function for `iced::widget::button` with padding and style applied
pub fn button_primary<'a, Message>(
content: impl Into<Element<'a, Message, Theme>>,
) -> Button<'a, Message, Theme> {
iced::widget::button(content)
.padding([5, 10])
.style(style::Button::Primary)
}
/// Opens a file picker dialog to select a folder
pub async fn open_folder() -> Result<std::path::PathBuf, uad_core::utils::Error> {
rfd::AsyncFileDialog::new()
.set_title("Choose a backup location")
.pick_folder()
.await
.ok_or(uad_core::utils::Error::DialogClosed)
.map(|f| f.path().to_path_buf())
}

View file

@ -1,11 +0,0 @@
#![allow(
clippy::missing_errors_doc,
reason = "Short-circuit doc lint to keep CI green"
)]
pub mod gui;
pub mod helpers;
pub mod style;
pub mod theme;
pub mod views;
pub mod widgets;

View file

@ -1,776 +0,0 @@
#![allow(
non_snake_case,
clippy::trivially_copy_pass_by_ref,
clippy::wildcard_imports,
reason = "Iced style modules use PascalCase and &Theme; wildcard for local convenience"
)]
use crate::theme::{ColorPalette, Theme};
use iced::widget::{
button, checkbox, container, overlay, pick_list, radio, scrollable, text, text_editor,
text_input,
};
use iced::{Background, Border, Color, Shadow};
// Implement theming catalogs for our custom `Theme` so generic widgets
// like `Button<'_, Message, Theme, Renderer>` compile under iced 0.13.
impl button::Catalog for Theme {
type Class<'a> = button::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as button::Catalog>::Class<'a> {
Box::new(|t: &Theme, s: button::Status| Button::Primary(t, s))
}
fn style(
&self,
class: &<Self as button::Catalog>::Class<'_>,
status: button::Status,
) -> button::Style {
(class)(self, status)
}
}
impl checkbox::Catalog for Theme {
type Class<'a> = checkbox::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as checkbox::Catalog>::Class<'a> {
Box::new(|t: &Theme, s: checkbox::Status| CheckBox::SettingsEnabled(t, s))
}
fn style(
&self,
class: &<Self as checkbox::Catalog>::Class<'_>,
status: checkbox::Status,
) -> checkbox::Style {
(class)(self, status)
}
}
impl container::Catalog for Theme {
type Class<'a> = container::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as container::Catalog>::Class<'a> {
Box::new(|t: &Theme| Container::Background(t))
}
fn style(&self, class: &<Self as container::Catalog>::Class<'_>) -> container::Style {
(class)(self)
}
}
impl scrollable::Catalog for Theme {
type Class<'a> = scrollable::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as scrollable::Catalog>::Class<'a> {
Box::new(|t: &Theme, s: scrollable::Status| Scrollable::Description(t, s))
}
fn style(
&self,
class: &<Self as scrollable::Catalog>::Class<'_>,
status: scrollable::Status,
) -> scrollable::Style {
(class)(self, status)
}
}
impl text::Catalog for Theme {
type Class<'a> = text::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as text::Catalog>::Class<'a> {
Box::new(|t: &Theme| Text::Default(t))
}
fn style(&self, class: &<Self as text::Catalog>::Class<'_>) -> text::Style {
(class)(self)
}
}
// Additional catalogs required by Iced 0.13 generic theming
impl text_input::Catalog for Theme {
type Class<'a> = text_input::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as text_input::Catalog>::Class<'a> {
Box::new(|t: &Theme, s: text_input::Status| {
let p = t.palette();
let active = text_input::Style {
background: Background::Color(p.base.foreground),
border: Border {
color: p.base.foreground,
width: 0.0,
radius: 5.0.into(),
},
icon: Color {
a: 0.5,
..p.normal.primary
},
placeholder: p.normal.surface,
value: p.bright.primary,
selection: p.normal.primary,
};
let focused = text_input::Style {
background: Background::Color(p.base.foreground),
border: Border {
color: Color {
a: 0.5,
..p.normal.primary
},
width: 1.0,
radius: 2.0.into(),
},
icon: Color {
a: 0.5,
..p.normal.primary
},
placeholder: p.normal.surface,
value: p.bright.primary,
selection: p.normal.primary,
};
let disabled = text_input::Style {
background: Background::Color(p.base.background),
border: Border {
color: Color {
a: 0.5,
..p.base.foreground
},
width: 1.0,
radius: 2.0.into(),
},
icon: Color {
a: 0.5,
..p.base.foreground
},
placeholder: p.normal.surface,
value: p.bright.primary,
selection: p.normal.primary,
};
match s {
text_input::Status::Active => active,
text_input::Status::Focused { .. } | text_input::Status::Hovered => focused,
text_input::Status::Disabled => disabled,
}
})
}
fn style(
&self,
class: &<Self as text_input::Catalog>::Class<'_>,
status: text_input::Status,
) -> text_input::Style {
(class)(self, status)
}
}
impl pick_list::Catalog for Theme {
type Class<'a> = pick_list::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as pick_list::Catalog>::Class<'a> {
Box::new(|t: &Theme, s: pick_list::Status| {
let p = t.palette();
let border_color = match s {
pick_list::Status::Hovered => p.normal.primary,
_ => Color {
a: 0.5,
..p.normal.primary
},
};
pick_list::Style {
text_color: p.bright.surface,
placeholder_color: p.bright.surface,
handle_color: p.bright.surface,
background: Background::Color(p.base.background),
border: Border {
color: border_color,
width: 1.0,
radius: 2.0.into(),
},
}
})
}
fn style(
&self,
class: &<Self as pick_list::Catalog>::Class<'_>,
status: pick_list::Status,
) -> pick_list::Style {
(class)(self, status)
}
}
impl overlay::menu::Catalog for Theme {
type Class<'a> = overlay::menu::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as overlay::menu::Catalog>::Class<'a> {
Box::new(|t: &Theme| {
let p = t.palette();
overlay::menu::Style {
text_color: p.bright.surface,
background: p.base.background.into(),
border: Border {
color: p.base.background,
width: 1.0,
radius: 2.0.into(),
},
selected_text_color: p.bright.surface,
selected_background: p.normal.primary.into(),
shadow: Shadow::default(),
}
})
}
fn style(&self, class: &<Self as overlay::menu::Catalog>::Class<'_>) -> overlay::menu::Style {
(class)(self)
}
}
impl radio::Catalog for Theme {
type Class<'a> = radio::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as radio::Catalog>::Class<'a> {
Box::new(|t: &Theme, s: radio::Status| {
let p = t.palette();
let active = radio::Style {
background: Color::TRANSPARENT.into(),
dot_color: p.bright.primary,
border_width: 1.0,
border_color: p.bright.primary,
text_color: None,
};
match s {
radio::Status::Active { .. } => active,
radio::Status::Hovered { .. } => radio::Style {
border_width: 2.0,
..active
},
}
})
}
fn style(
&self,
class: &<Self as radio::Catalog>::Class<'_>,
status: radio::Status,
) -> radio::Style {
(class)(self, status)
}
}
impl text_editor::Catalog for Theme {
type Class<'a> = text_editor::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as text_editor::Catalog>::Class<'a> {
Box::new(|t: &Theme, _s: text_editor::Status| {
let p = t.palette();
text_editor::Style {
background: Background::Color(p.base.foreground),
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 0.0.into(),
},
placeholder: p.normal.surface,
value: p.bright.surface,
selection: Color {
a: 0.3,
..p.normal.primary
},
}
})
}
fn style(
&self,
class: &<Self as text_editor::Catalog>::Class<'_>,
status: text_editor::Status,
) -> text_editor::Style {
(class)(self, status)
}
}
// Rule styling for custom Theme (needed by vertical_rule)
impl iced::widget::rule::Catalog for Theme {
type Class<'a> = iced::widget::rule::StyleFn<'a, Theme>;
fn default<'a>() -> <Self as iced::widget::rule::Catalog>::Class<'a> {
Box::new(|t: &Theme| {
let p = t.palette();
iced::widget::rule::Style {
color: p.bright.surface,
radius: 2.0.into(),
fill_mode: iced::widget::rule::FillMode::Full,
snap: true,
}
})
}
fn style(
&self,
class: &<Self as iced::widget::rule::Catalog>::Class<'_>,
) -> iced::widget::rule::Style {
(class)(self)
}
}
pub mod Container {
use super::*;
#[allow(dead_code, reason = "Used by other themes or future styles")]
#[must_use]
pub fn Invisible(_: &Theme) -> container::Style {
container::Style::default()
}
#[must_use]
pub fn Frame(theme: &Theme) -> container::Style {
let p = theme.palette();
container::Style {
background: Some(Background::Color(p.base.foreground)),
text_color: Some(p.bright.surface),
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
snap: true,
}
}
#[must_use]
pub fn BorderedFrame(theme: &Theme) -> container::Style {
let p = theme.palette();
container::Style {
background: Some(Background::Color(p.base.foreground)),
text_color: Some(p.bright.surface),
border: Border {
color: p.normal.error,
width: 1.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
snap: true,
}
}
#[allow(dead_code, reason = "Currently unused in some views")]
#[must_use]
pub fn Tooltip(theme: &Theme) -> container::Style {
let p = theme.palette();
container::Style {
background: Some(Background::Color(p.base.foreground)),
text_color: Some(p.bright.surface),
border: Border {
color: p.normal.primary,
width: 1.0,
radius: 8.0.into(),
},
shadow: Shadow::default(),
snap: true,
}
}
#[must_use]
pub fn Background(theme: &Theme) -> container::Style {
let p = theme.palette();
container::Style {
background: Some(Background::Color(p.base.background)),
text_color: Some(p.bright.surface),
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
snap: true,
}
}
}
pub mod Button {
use super::*;
#[allow(
dead_code,
reason = "Helper used by multiple styles; may be inlined by compiler"
)]
fn base(border_color: Color) -> button::Style {
button::Style {
background: None,
text_color: Color::WHITE,
border: Border {
color: border_color,
width: 1.0,
radius: 2.0.into(),
},
shadow: Shadow::default(),
snap: true,
}
}
#[must_use]
pub fn Primary(theme: &Theme, status: button::Status) -> button::Style {
let p = theme.palette();
let mut style = style_active_hover_disabled(p.bright.primary, p.bright.primary, status);
if matches!(status, button::Status::Active | button::Status::Pressed) {
style.background = Some(Background::Color(p.base.foreground));
}
style
}
#[allow(
dead_code,
reason = "Alias kept for semantic clarity in some call-sites"
)]
#[must_use]
pub fn SelfUpdate(theme: &Theme, status: button::Status) -> button::Style {
Primary(theme, status)
}
#[must_use]
pub fn RestorePackage(theme: &Theme, status: button::Status) -> button::Style {
let p = theme.palette();
let mut style = style_active_hover_disabled(p.bright.secondary, p.bright.secondary, status);
if matches!(status, button::Status::Active | button::Status::Pressed) {
style.background = Some(Background::Color(p.base.foreground));
}
if matches!(status, button::Status::Disabled) {
style.background = Some(Background::Color(Color {
a: 0.05,
..p.normal.primary
}));
style.text_color = p.bright.primary;
}
style
}
#[must_use]
pub fn UninstallPackage(theme: &Theme, status: button::Status) -> button::Style {
let p = theme.palette();
let mut style = style_active_hover_disabled(p.bright.error, p.bright.error, status);
if matches!(status, button::Status::Active | button::Status::Pressed) {
style.background = Some(Background::Color(p.base.foreground));
}
style
}
#[allow(
dead_code,
reason = "Style exposed for disabled state buttons in some contexts"
)]
#[must_use]
pub fn Unavailable(theme: &Theme, status: button::Status) -> button::Style {
UninstallPackage(theme, status)
}
#[must_use]
pub fn NormalPackage(theme: &Theme, status: button::Status) -> button::Style {
let p = theme.palette();
match status {
button::Status::Hovered => button::Style {
background: Some(Background::Color(Color {
a: 0.25,
..p.normal.primary
})),
text_color: p.bright.surface,
border: Border {
color: p.base.background,
width: 0.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
snap: true,
},
_ => button::Style {
background: Some(Background::Color(p.base.foreground)),
text_color: p.bright.surface,
border: Border {
color: p.base.background,
width: 0.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
snap: true,
},
}
}
#[must_use]
pub fn SelectedPackage(theme: &Theme, _status: button::Status) -> button::Style {
let p = theme.palette();
button::Style {
background: Some(Background::Color(Color {
a: 0.25,
..p.normal.primary
})),
text_color: p.bright.primary,
border: Border {
color: p.normal.primary,
width: 0.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
snap: true,
}
}
#[allow(dead_code, reason = "Used in views where buttons must be invisible")]
#[must_use]
pub fn Hidden(_: &Theme, _: button::Status) -> button::Style {
button::Style {
background: Some(Background::Color(Color::TRANSPARENT)),
text_color: Color::TRANSPARENT,
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
snap: true,
}
}
fn style_active_hover_disabled(
main: Color,
text: Color,
status: button::Status,
) -> button::Style {
match status {
button::Status::Active | button::Status::Pressed => button::Style {
background: Some(Background::Color(main)),
text_color: text,
border: Border {
color: Color { a: 0.5, ..main },
width: 1.0,
radius: 2.0.into(),
},
shadow: Shadow::default(),
snap: true,
},
button::Status::Hovered => button::Style {
background: Some(Background::Color(Color { a: 0.25, ..main })),
text_color: text,
border: Border {
color: Color { a: 0.5, ..main },
width: 1.0,
radius: 2.0.into(),
},
shadow: Shadow::default(),
snap: true,
},
button::Status::Disabled => button::Style {
background: Some(Background::Color(Color { a: 0.05, ..main })),
text_color: Color { a: 0.5, ..text },
border: Border {
color: Color { a: 0.5, ..main },
width: 1.0,
radius: 2.0.into(),
},
shadow: Shadow::default(),
snap: true,
},
}
}
}
pub mod Scrollable {
use super::*;
#[allow(dead_code, reason = "Kept for future custom rails variations")]
fn rails(scroller_color: Color) -> (scrollable::Rail, scrollable::Rail) {
let rail = scrollable::Rail {
background: Some(Background::Color(Color::TRANSPARENT)),
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
scroller: scrollable::Scroller {
background: Background::Color(scroller_color),
border: Border {
color: Color::TRANSPARENT,
width: 1.0,
radius: 5.0.into(),
},
},
};
(rail, rail)
}
fn autoscroll(p: ColorPalette) -> scrollable::AutoScroll {
scrollable::AutoScroll {
background: Background::Color(Color {
a: 0.05,
..p.base.background
}),
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
icon: p.bright.surface,
}
}
#[must_use]
pub fn Description(theme: &Theme, _status: scrollable::Status) -> scrollable::Style {
let p = theme.palette();
let (v, h) = rails(p.normal.surface);
scrollable::Style {
container: container::Style::default(),
vertical_rail: v,
horizontal_rail: h,
gap: Some(Background::Color(Color::TRANSPARENT)),
auto_scroll: autoscroll(p),
}
}
#[must_use]
pub fn Packages(theme: &Theme, _status: scrollable::Status) -> scrollable::Style {
let p = theme.palette();
let (v, h) = rails(p.base.foreground);
scrollable::Style {
container: container::Style::default(),
vertical_rail: v,
horizontal_rail: h,
gap: Some(Background::Color(Color::TRANSPARENT)),
auto_scroll: autoscroll(p),
}
}
}
pub mod CheckBox {
use super::*;
#[must_use]
pub fn PackageEnabled(theme: &Theme, _status: checkbox::Status) -> checkbox::Style {
let p = theme.palette();
checkbox::Style {
background: Background::Color(p.base.background),
icon_color: p.bright.primary,
border: Border {
color: p.base.background,
width: 1.0,
radius: 5.0.into(),
},
text_color: Some(p.bright.surface),
}
}
#[must_use]
pub fn PackageDisabled(theme: &Theme, _status: checkbox::Status) -> checkbox::Style {
let p = theme.palette();
checkbox::Style {
background: Background::Color(Color {
a: 0.55,
..p.base.background
}),
icon_color: p.bright.primary,
border: Border {
color: p.normal.primary,
width: 1.0,
radius: 5.0.into(),
},
text_color: Some(p.normal.primary),
}
}
#[must_use]
pub fn SettingsEnabled(theme: &Theme, _status: checkbox::Status) -> checkbox::Style {
let p = theme.palette();
checkbox::Style {
background: Background::Color(p.base.background),
icon_color: p.bright.primary,
border: Border {
color: p.bright.primary,
width: 1.0,
radius: 5.0.into(),
},
text_color: Some(p.bright.surface),
}
}
#[must_use]
pub fn SettingsDisabled(theme: &Theme, _status: checkbox::Status) -> checkbox::Style {
let p = theme.palette();
checkbox::Style {
background: Background::Color(p.base.foreground),
icon_color: p.bright.primary,
border: Border {
color: p.normal.primary,
width: 1.0,
radius: 5.0.into(),
},
text_color: Some(p.bright.surface),
}
}
}
pub mod Text {
use super::*;
#[must_use]
pub fn Default(theme: &Theme) -> text::Style {
let _ = theme;
text::Style::default()
}
#[must_use]
pub fn Ok(theme: &Theme) -> text::Style {
let p = theme.palette();
text::Style {
color: Some(p.bright.secondary),
}
}
#[must_use]
pub fn Danger(theme: &Theme) -> text::Style {
let p = theme.palette();
text::Style {
color: Some(p.bright.error),
}
}
#[must_use]
pub fn Commentary(theme: &Theme) -> text::Style {
let p = theme.palette();
text::Style {
color: Some(p.normal.surface),
}
}
#[allow(
dead_code,
reason = "Convenience factory used by dynamic text coloring"
)]
pub fn Color(c: Color) -> impl Fn(&Theme) -> text::Style {
move |_t: &Theme| text::Style { color: Some(c) }
}
}
// Unit tests
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_palette() {
let palette = Theme::Dark.palette();
assert_ne!(palette.base.background, palette.base.foreground);
assert_ne!(palette.normal.primary, Color::BLACK);
assert_ne!(palette.normal.surface, Color::BLACK);
assert_ne!(palette.bright.primary, Color::BLACK);
// if `LIGHT` then this can be `BLACK`
// https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/pull/730#issuecomment-2525405134
//assert_ne!(palette.bright.surface, Color::BLACK);
assert_ne!(palette.normal.error, Color::BLACK);
assert_ne!(palette.bright.error, Color::BLACK);
}
}

View file

@ -1,174 +0,0 @@
use crate::helpers::button_primary;
use crate::theme::Theme;
use crate::{gui::UpdateState, style, widgets::text};
use iced::widget::{Space, column, container, row};
use iced::{Alignment, Element, Length, Renderer};
use log::error;
use std::path::PathBuf;
use uad_core::CACHE_DIR;
use uad_core::adb;
use uad_core::uad_lists::LIST_FNAME;
use uad_core::utils::{FULL_NAME, NAME, last_modified_date, open_url};
#[cfg(feature = "self-update")]
use uad_core::update::SelfUpdateStatus;
#[derive(Default, Debug, Clone)]
pub struct About {}
#[derive(Debug, Clone)]
pub enum Message {
UrlPressed(PathBuf),
UpdateUadLists,
DoSelfUpdate,
}
impl About {
#[allow(
clippy::unused_self,
reason = "Trait-like shape required by GUI architecture"
)]
pub fn update(&mut self, msg: Message) {
if let Message::UrlPressed(url) = msg {
open_url(url);
}
// other events are handled by UadGui update()
}
#[allow(
clippy::unused_self,
reason = "Trait-like shape required by GUI architecture"
)]
pub fn view(&self, update_state: &UpdateState) -> Element<'_, Message, Theme, Renderer> {
let about_text = text(format!(
"{FULL_NAME} ({NAME}) is a free and open-source community project \naiming at simplifying the removal of pre-installed apps on any Android device."
));
let descr_container = container(about_text)
.width(Length::Fill)
.padding(25)
.style(style::Container::Frame);
let date = last_modified_date(CACHE_DIR.join(LIST_FNAME));
let uad_list_text =
text(format!("{NAME} package list: v{}", date.format("%Y%m%d"))).width(250);
let last_update_text = text(update_state.uad_list.to_string());
let uad_lists_btn = button_primary("Update").on_press(Message::UpdateUadLists);
#[cfg(feature = "self-update")]
let self_update_row = {
let self_update_btn = button_primary("Update").on_press(Message::DoSelfUpdate);
let uad_version_text =
text(format!("{NAME} version: v{}", env!("CARGO_PKG_VERSION"))).width(250);
let self_update_text = update_state
.self_update
.latest_release
.as_ref()
.map_or_else(
|| {
if update_state.self_update.status == SelfUpdateStatus::Done {
"(No update available)".to_string()
} else {
update_state.self_update.status.to_string()
}
},
|r| {
if update_state.self_update.status == SelfUpdateStatus::Updating {
update_state.self_update.status.to_string()
} else {
format!("({} available)", r.tag_name)
}
},
);
let last_self_update_text = text(self_update_text).style(style::Text::Default);
row![uad_version_text, self_update_btn, last_self_update_text,]
.align_y(Alignment::Center)
.spacing(10)
.width(550)
};
let uad_list_row = row![uad_list_text, uad_lists_btn, last_update_text,]
.align_y(Alignment::Center)
.spacing(10)
.width(550);
/*
There's no need to fetch this info every time the view is updated,
we could cache it in a `static` `LazyLock`.
But what if the system updates ADB while the app is running?
the numbers will be out of sync!
However, the server will still be the "old" version
until it's killed
*/
let adb_version_text = text(match adb::ACommand::new().version() {
Ok(s) => s
.lines()
.nth(0)
.unwrap_or_else(|| unreachable!())
// This allocation is good.
// If it was a ref, the app would hold the entire string
// instead of the relevant slice.
.to_string(),
Err(e) => {
error!("{e}");
"Couldn't fetch ADB version. Is it installed?".into()
// satisfy `match` by inferring the type of the `Ok` arm
}
})
.width(250);
let adb_version_row = row![adb_version_text].align_y(Alignment::Center).width(550);
#[cfg(feature = "self-update")]
let update_column = column![uad_list_row, self_update_row, adb_version_row];
#[cfg(not(feature = "self-update"))]
let update_column = column![uad_list_row, adb_version_row];
let update_column = update_column.align_x(Alignment::Center).spacing(10);
let update_container = container(update_column)
.width(Length::Fill)
.center_x(Length::Fill)
.padding(10)
.style(style::Container::Frame);
let website_btn =
button_primary("GitHub page").on_press(Message::UrlPressed(PathBuf::from(
"https://github.com/Universal-Debloater-Alliance/universal-android-debloater",
)));
let issue_btn = button_primary("Have an issue?")
.on_press(Message::UrlPressed(PathBuf::from(
"https://github.com/Universal-Debloater-Alliance/universal-android-debloater/issues",
)));
let log_btn = button_primary("Locate the logfiles")
.on_press(Message::UrlPressed(CACHE_DIR.to_path_buf()));
let wiki_btn = button_primary("Wiki").on_press(Message::UrlPressed(PathBuf::from(
"https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki",
)));
let row = row![website_btn, wiki_btn, issue_btn, log_btn,].spacing(20);
let content = column![
Space::new().width(Length::Fill).height(Length::Shrink),
descr_container,
update_container,
row,
]
.width(Length::Fill)
.spacing(20)
.align_x(Alignment::Center);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.padding(10)
.into()
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,694 +0,0 @@
use crate::helpers::{button_primary, open_folder};
use crate::theme::Theme;
use crate::theme::string_to_theme;
use crate::{
style,
views::list::{List as AppsView, PackageInfo},
widgets::modal::Modal,
widgets::navigation_menu::ICONS,
widgets::package_row::PackageRow,
widgets::text,
};
use chrono;
use iced::widget::{Space, button, checkbox, column, container, pick_list, radio, row, scrollable};
use iced::{Alignment, Element, Length, Renderer, Task, alignment};
use log::{debug, error, info};
use std::path::PathBuf;
use uad_core::{
config::{BackupSettings, Config, DeviceSettings, GeneralSettings},
save::{backup_phone, list_available_backup_user, list_available_backups, restore_backup},
sync::{
AdbError, CorePackage, Phone, User, get_android_sdk, run_adb_shell_action,
supports_disabling, supports_multi_user,
},
utils::{DisplayablePath, Error, NAME, export_packages, generate_backup_name, open_url},
};
#[derive(Debug, Clone)]
pub enum PopUpModal {
ExportUninstalled,
}
#[derive(Debug, Clone)]
pub struct Settings {
pub general: GeneralSettings,
pub device: DeviceSettings,
is_loading: bool,
modal: Option<PopUpModal>,
}
impl Default for Settings {
fn default() -> Self {
Self {
general: Config::load_configuration_file().general,
device: DeviceSettings::default(),
is_loading: false,
modal: None,
}
}
}
#[derive(Debug, Clone)]
pub enum Message {
LoadDeviceSettings,
ExpertMode(bool),
DisableMode(bool),
MultiUserMode(bool),
ApplyTheme(Theme),
UrlPressed(PathBuf),
BackupSelected(DisplayablePath),
BackupDevice,
RestoreDevice,
RestoringDevice(Result<PackageInfo, AdbError>),
DeviceBackedUp(Result<bool, String>),
ChooseBackUpFolder,
FolderChosen(Result<PathBuf, Error>),
ExportPackages,
PackagesExported(Result<bool, String>),
ModalHide,
}
impl Settings {
pub fn update(
&mut self,
phone: &Phone,
packages: &[Vec<PackageRow>],
nb_running_async_adb_commands: &mut u32,
msg: Message,
selected_user: Option<User>,
) -> Task<Message> {
match msg {
Message::ModalHide => self.handle_modal_hide(),
Message::ExpertMode(toggled) => self.handle_expert_mode(phone, toggled),
Message::DisableMode(toggled) => self.handle_disable_mode(phone, toggled),
Message::MultiUserMode(toggled) => self.handle_multi_user_mode(phone, toggled),
Message::ApplyTheme(theme) => self.handle_apply_theme(phone, theme),
Message::UrlPressed(url) => Self::handle_url_pressed(url),
Message::LoadDeviceSettings => self.handle_load_device_settings(phone),
Message::BackupSelected(d_path) => self.handle_backup_selected(d_path),
Message::BackupDevice => self.handle_backup_device(phone, packages),
Message::DeviceBackedUp(result) => self.handle_device_backed_up(phone, result),
Message::RestoreDevice => {
self.handle_restore_device(phone, packages, nb_running_async_adb_commands)
}
Message::RestoringDevice(_) => Task::none(),
Message::FolderChosen(result) => self.handle_folder_chosen(phone, result),
Message::ChooseBackUpFolder => self.handle_choose_backup_folder(),
Message::ExportPackages => Self::handle_export_packages(selected_user, packages),
Message::PackagesExported(result) => self.handle_packages_exported(result),
}
}
fn handle_modal_hide(&mut self) -> Task<Message> {
self.modal = None;
Task::none()
}
fn handle_expert_mode(&mut self, _phone: &Phone, toggled: bool) -> Task<Message> {
self.general.expert_mode = toggled;
debug!("Config change: {self:?}");
let mut config = Config::load_configuration_file();
config.save_device_settings(self.device.clone(), self.general.clone());
Task::none()
}
fn handle_disable_mode(&mut self, phone: &Phone, toggled: bool) -> Task<Message> {
if supports_disabling(phone) {
self.device.disable_mode = toggled;
debug!("Config change: {self:?}");
let mut config = Config::load_configuration_file();
config.save_device_settings(self.device.clone(), self.general.clone());
}
Task::none()
}
fn handle_multi_user_mode(&mut self, _phone: &Phone, toggled: bool) -> Task<Message> {
self.device.multi_user_mode = toggled;
debug!("Config change: {self:?}");
let mut config = Config::load_configuration_file();
config.save_device_settings(self.device.clone(), self.general.clone());
Task::none()
}
fn handle_apply_theme(&mut self, _phone: &Phone, theme: Theme) -> Task<Message> {
self.general.theme = theme.to_string();
debug!("Config change: {self:?}");
let mut config = Config::load_configuration_file();
config.save_device_settings(self.device.clone(), self.general.clone());
Task::none()
}
fn handle_url_pressed(url: PathBuf) -> Task<Message> {
open_url(url);
Task::none()
}
fn handle_load_device_settings(&mut self, phone: &Phone) -> Task<Message> {
self.load_device_settings(phone);
Task::none()
}
fn load_device_settings(&mut self, phone: &Phone) {
let backups = list_available_backups(&self.general.backup_folder.join(&phone.adb_id));
let backup = BackupSettings {
backups: backups.clone(),
selected: backups.first().cloned(),
users: phone.user_list.clone(),
selected_user: phone.user_list.first().copied(),
backup_state: String::default(),
};
match Config::load_configuration_file()
.devices
.iter()
.find(|d| d.device_id == phone.adb_id)
{
Some(device) => {
self.device.clone_from(device);
self.device.backup = backup;
}
None => {
self.device = DeviceSettings {
device_id: phone.adb_id.clone(),
// see FAQ, and GH-issue #1426
disable_mode: supports_disabling(phone),
multi_user_mode: supports_multi_user(phone),
backup,
};
}
}
}
fn handle_backup_selected(&mut self, d_path: DisplayablePath) -> Task<Message> {
self.device.backup.selected = Some(d_path.clone());
self.device.backup.users = list_available_backup_user(d_path);
Task::none()
}
fn handle_backup_device(
&mut self,
phone: &Phone,
packages: &[Vec<PackageRow>],
) -> Task<Message> {
let core_packages: Vec<Vec<_>> = packages
.iter()
.map(|user_packages| user_packages.iter().map(CorePackage::from).collect())
.collect();
// Avoid capturing &self and &phone in the future; clone owned data first.
let user_list = phone.user_list.clone();
let device_id = self.device.device_id.clone();
let packages_owned = core_packages;
Task::perform(
async move { backup_phone(user_list, device_id, &packages_owned) },
Message::DeviceBackedUp,
)
}
fn handle_device_backed_up(
&mut self,
phone: &Phone,
result: Result<bool, String>,
) -> Task<Message> {
match result {
Ok(_) => {
info!("[BACKUP] Backup successfully created");
self.device.backup.backups =
list_available_backups(&self.general.backup_folder.join(phone.adb_id.clone()));
self.device.backup.selected = self.device.backup.backups.first().cloned();
}
Err(err) => {
error!("[BACKUP FAILED] Backup creation failed: {err:?}");
}
}
Task::none()
}
fn handle_restore_device(
&mut self,
phone: &Phone,
packages: &[Vec<PackageRow>],
nb_running_async_adb_commands: &mut u32,
) -> Task<Message> {
let core_packages: Vec<Vec<_>> = packages
.iter()
.map(|user_packages| user_packages.iter().map(CorePackage::from).collect())
.collect();
match restore_backup(phone, &core_packages, &self.device) {
Ok(restore_result) => {
let mut commands = vec![];
*nb_running_async_adb_commands = 0;
for p in &restore_result.packages {
let p_info = PackageInfo {
i_user: p.i_user,
index: p.index,
removal: "RESTORE".to_string(),
before_cross_user_states: vec![],
};
for command in p.commands.clone() {
*nb_running_async_adb_commands += 1;
let p_info_clone = p_info.clone();
let phone_id = phone.adb_id.clone();
commands.push(Task::perform(
async move {
run_adb_shell_action(phone_id, command.as_str())
.map(|_| p_info_clone)
},
Message::RestoringDevice,
));
}
}
if restore_result.skipped_count > 0 {
self.device.backup.backup_state = format!(
"Restore completed with {} packages skipped (not found on device)",
restore_result.skipped_count
);
} else if restore_result.packages.is_empty() {
if get_android_sdk(&phone.adb_id) == 0 {
self.device.backup.backup_state = "Device is not connected".to_string();
} else {
self.device.backup.backup_state =
"Device state is already restored".to_string();
}
} else {
self.device.backup.backup_state = "Restore completed successfully".to_string();
}
info!(
"[RESTORE] Restoring backup {}",
self.device.backup.selected.as_ref().unwrap()
);
Task::batch(commands)
}
Err(e) => {
self.device.backup.backup_state.clone_from(&e);
error!("{} - {}", self.device.backup.selected.as_ref().unwrap(), e);
Task::none()
}
}
}
fn handle_folder_chosen(
&mut self,
phone: &Phone,
result: Result<PathBuf, Error>,
) -> Task<Message> {
self.is_loading = false;
if let Ok(path) = result {
self.general.backup_folder = path;
let mut config = Config::load_configuration_file();
config.save_device_settings(self.device.clone(), self.general.clone());
self.load_device_settings(phone);
}
Task::none()
}
fn handle_choose_backup_folder(&mut self) -> Task<Message> {
if self.is_loading {
Task::none()
} else {
self.is_loading = true;
Task::perform(open_folder(), Message::FolderChosen)
}
}
fn handle_export_packages(
selected_user: Option<User>,
packages: &[Vec<PackageRow>],
) -> Task<Message> {
let core_packages: Vec<Vec<_>> = packages
.iter()
.map(|user_packages| user_packages.iter().map(CorePackage::from).collect())
.collect();
Task::perform(
async move { export_packages(selected_user.unwrap_or_default(), &core_packages) },
Message::PackagesExported,
)
}
fn handle_packages_exported(&mut self, result: Result<bool, String>) -> Task<Message> {
match result {
Ok(_) => self.modal = Some(PopUpModal::ExportUninstalled),
Err(err) => error!("Failed to export list of uninstalled packages: {err:?}"),
}
Task::none()
}
pub fn view(
&self,
phone: &Phone,
apps_view: &AppsView,
) -> Element<'_, Message, Theme, Renderer> {
let content = if phone.adb_id.is_empty() {
self.build_no_device_content()
} else {
self.build_device_content(phone, apps_view)
};
if let Some(PopUpModal::ExportUninstalled) = self.modal {
return Self::render_export_modal(content);
}
container(scrollable(content))
.padding(10)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn build_no_device_content(&self) -> Element<'_, Message, Theme, Renderer> {
column![
text("Theme").size(26),
self.theme_container(),
text("General").size(26),
self.general_container(),
text("Current device").size(26),
Self::no_device_container(),
text("Backup / Restore").size(26),
Self::no_device_container(),
]
.width(Length::Fill)
.spacing(20)
.into()
}
fn build_device_content(
&self,
phone: &Phone,
apps_view: &AppsView,
) -> Element<'_, Message, Theme, Renderer> {
column![
text("Theme").size(26),
self.theme_container(),
text("General").size(26),
self.general_container(),
text("Current device").size(26),
Self::warning_container(phone),
self.device_specific_container(phone),
text("Backup / Restore").size(26),
self.backup_restore_container(phone, apps_view),
]
.width(Length::Fill)
.spacing(20)
.into()
}
fn theme_container(&self) -> Element<'_, Message, Theme, Renderer> {
let radio_btn_theme = Theme::ALL
.iter()
.fold(row![].spacing(10), |column, option| {
column.push(
radio(
format!("{}", option.clone()),
*option,
Some(string_to_theme(&self.general.theme)),
Message::ApplyTheme,
)
.size(24),
)
});
container(radio_btn_theme)
.padding(10)
.width(Length::Fill)
.height(Length::Shrink)
.style(style::Container::Frame)
.into()
}
fn general_container(&self) -> Element<'_, Message, Theme, Renderer> {
let expert_mode_checkbox = checkbox(self.general.expert_mode)
.label("Allow to uninstall packages marked as \"unsafe\" (I KNOW WHAT I AM DOING)")
.on_toggle(Message::ExpertMode)
.size(20)
.style(style::CheckBox::SettingsEnabled);
let expert_mode_descr =
text("Most unsafe packages are known to bootloop the device if removed.")
.style(style::Text::Commentary);
let choose_backup_descr = text("Note: If you have previous backups, you will need to transfer them manually to newly changed backup folder to be able to use Restore functionality")
.style(style::Text::Commentary);
let choose_backup_btn = button(text("\u{E930}").font(ICONS))
.padding([5, 10])
.on_press(Message::ChooseBackUpFolder)
.style(style::Button::Primary);
let choose_backup_row = row![
choose_backup_btn,
"Choose backup folder",
Space::new().width(Length::Fill).height(Length::Shrink),
"Current folder: ",
text(self.general.backup_folder.to_string_lossy())
]
.spacing(10)
.align_y(Alignment::Center);
container(
column![
expert_mode_checkbox,
expert_mode_descr,
choose_backup_row,
choose_backup_descr,
]
.spacing(10),
)
.padding(10)
.width(Length::Fill)
.height(Length::Shrink)
.style(style::Container::Frame)
.into()
}
fn warning_container(phone: &Phone) -> Element<'static, Message, Theme, Renderer> {
container(
row![
text("The following settings only affect the currently selected device:")
.style(style::Text::Danger),
text(phone.model.clone()),
Space::new().width(Length::Fill).height(Length::Shrink),
text(phone.adb_id.clone()).style(style::Text::Commentary)
]
.spacing(7),
)
.padding(10)
.width(Length::Fill)
.style(style::Container::BorderedFrame)
.into()
}
fn device_specific_container(&self, phone: &Phone) -> Element<'_, Message, Theme, Renderer> {
let multi_user_mode_descr = row![
text("This will not affect the following protected work profile users: ")
.style(style::Text::Commentary),
text(
phone
.user_list
.iter()
.filter(|&u| u.protected)
.map(|u| u.id.to_string())
.collect::<Vec<String>>()
.join(", ")
)
.style(style::Text::Danger)
];
let multi_user_mode_checkbox = checkbox(self.device.multi_user_mode)
.label("Affect all the users of the device (not only the selected user)")
.on_toggle(Message::MultiUserMode)
.size(20)
.style(style::CheckBox::SettingsEnabled);
let disable_checkbox_style = if supports_disabling(phone) {
style::CheckBox::SettingsEnabled
} else {
style::CheckBox::SettingsDisabled
};
let disable_mode_descr =
text("In many cases, it's better to disable a package instead of uninstalling it")
.style(style::Text::Commentary);
let unavailable_btn = button(text("Unavailable").size(14))
.on_press(Message::UrlPressed(PathBuf::from(
"https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki/FAQ#\
why-is-the-disable-mode-setting-not-available-for-my-device",
)))
.height(22)
.style(style::Button::Unavailable);
let disable_mode_checkbox = checkbox(self.device.disable_mode)
.label("Clear and disable packages instead of uninstalling them")
.on_toggle(Message::DisableMode)
.size(20)
.style(disable_checkbox_style);
let disable_setting_row = if supports_disabling(phone) {
row![
disable_mode_checkbox,
Space::new().width(Length::Fill).height(Length::Shrink),
]
.width(Length::Fill)
} else {
row![
disable_mode_checkbox,
Space::new().width(Length::Fill).height(Length::Shrink),
unavailable_btn,
]
.width(Length::Fill)
};
container(
column![
multi_user_mode_checkbox,
multi_user_mode_descr,
disable_setting_row,
disable_mode_descr,
]
.spacing(10),
)
.padding(10)
.width(Length::Fill)
.height(Length::Shrink)
.style(style::Container::Frame)
.into()
}
fn backup_restore_container(
&self,
phone: &Phone,
apps_view: &AppsView,
) -> Element<'_, Message, Theme, Renderer> {
let backup_pick_list = pick_list(
self.device.backup.backups.clone(),
self.device.backup.selected.clone(),
Message::BackupSelected,
)
.padding(6);
let backup_btn = button_primary(text("Backup").align_x(alignment::Horizontal::Center))
.on_press(Message::BackupDevice)
.width(77);
let restore_btn = |enabled| {
if enabled {
button(text("Restore").align_x(alignment::Horizontal::Center))
.padding([5, 10])
.on_press(Message::RestoreDevice)
.width(77)
} else {
button(
text("No backup")
.align_x(alignment::Horizontal::Center)
.align_y(alignment::Vertical::Center),
)
.padding([5, 10])
.width(77)
}
};
let locate_backup_btn = if self.device.backup.backups.is_empty() {
button_primary("Open backup directory")
} else {
button_primary("Open backup directory").on_press(Message::UrlPressed(
self.general.backup_folder.join(phone.adb_id.clone()),
))
};
let export_btn = button_primary("Export").on_press(Message::ExportPackages);
let backup_row = row![
backup_btn,
"Backup the current state of the phone",
Space::new().width(Length::Fill).height(Length::Shrink),
locate_backup_btn,
]
.spacing(10)
.align_y(Alignment::Center);
let restore_row = if self.device.backup.backups.is_empty() {
row![]
} else {
row![
restore_btn(true),
"Restore the state of the device",
Space::new().width(Length::Fill).height(Length::Shrink),
text(self.device.backup.backup_state.clone()).style(style::Text::Danger),
backup_pick_list,
]
.spacing(10)
.align_y(Alignment::Center)
};
let export_row = row![
export_btn,
"Export uninstalled packages with their description",
Space::new().width(Length::Fill).height(Length::Shrink),
text(format!(
"Selected: user {}",
apps_view.selected_user.unwrap_or_default().id
)),
]
.spacing(10)
.align_y(Alignment::Center);
container(column![backup_row, restore_row, export_row].spacing(10))
.padding(10)
.width(Length::Fill)
.height(Length::Shrink)
.style(style::Container::Frame)
.into()
}
fn no_device_container() -> Element<'static, Message, Theme, Renderer> {
container(text("No device detected").style(style::Text::Danger))
.padding(10)
.width(Length::Fill)
.style(style::Container::BorderedFrame)
.into()
}
fn render_export_modal<'a>(
content: Element<'a, Message, Theme, Renderer>,
) -> Element<'a, Message, Theme, Renderer> {
let title = container(row![text("Success").size(24)].align_y(Alignment::Center))
.width(Length::Fill)
.style(style::Container::Frame)
.padding([10, 0])
.center_y(Length::Shrink)
.center_x(Length::Shrink);
let text_box = row![
text(format!(
"Exported uninstalled packages into file.\nFile is exported in same directory where {NAME} is located."
))
.width(Length::Fill),
]
.padding(20);
let file_row =
row![text(generate_backup_name(chrono::Local::now())).style(style::Text::Commentary)]
.padding(20);
let modal_btn_row = row![
Space::new().width(Length::Fill).height(Length::Shrink),
button(text("Close").width(Length::Shrink))
.width(Length::Shrink)
.on_press(Message::ModalHide),
Space::new().width(Length::Fill).height(Length::Shrink),
];
let ctn = container(column![title, text_box, file_row, modal_btn_row])
.height(Length::Shrink)
.width(500)
.padding(10)
.style(style::Container::Frame);
let padded_content: Element<'a, Message, Theme, Renderer> =
container(content).padding(10).into();
Modal::new(padded_content, ctn)
.on_blur(Message::ModalHide)
.into()
}
}

View file

@ -1,13 +0,0 @@
#![allow(
clippy::disallowed_types,
reason = "this is the replacement that enforces advanced shaping for disallowed [`iced::widget::Text`]"
)]
use crate::theme::Theme;
use iced::advanced::text::IntoFragment;
use iced::widget;
// Creates a new Text widget with advanced shaping.
pub fn text<'a>(text: impl IntoFragment<'a>) -> widget::Text<'a, Theme> {
widget::Text::new(text).shaping(iced::widget::text::Shaping::Advanced)
}

48
flake.lock generated
View file

@ -1,25 +1,55 @@
{
"nodes": {
"nixpkgs": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1776949667,
"narHash": "sha256-GMSVw35Q+294GlrTUKlx087E31z7KurReQ1YHSKp5iw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "01fbdeef22b76df85ea168fbfe1bfd9e63681b30",
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 0,
"narHash": "sha256-YN/Ciidm+A0fmJPWlHBGvVkcarYWSC+s3NTPk/P+q3c=",
"path": "/nix/store/amxd2p02wx78nyaa4bkb0hjvgwhz1dq7-source",
"type": "path"
},
"original": {
"id": "nixpkgs",
"type": "indirect"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",

View file

@ -1,69 +1,37 @@
{
description = "devshell for uad-ng";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
inputs.flake-utils.url = "github:numtide/flake-utils";
outputs =
{ nixpkgs, ... }:
let
forSystems =
f:
nixpkgs.lib.genAttrs nixpkgs.lib.systems.flakeExposed (
system: f (import nixpkgs { inherit system; })
);
in
{
formatter = forSystems (pkgs: pkgs.nixfmt-tree);
devShells = forSystems (
pkgs:
let
inherit (pkgs) lib stdenv;
runtimeLibs = [
pkgs.fontconfig
pkgs.freetype
]
++ lib.optionals stdenv.isLinux (
with pkgs;
[
libglvnd
libX11
libXcursor
libXi
libXrandr
libxkbcommon
wayland
]
);
in
outputs = { self, nixpkgs, flake-utils }:
flake-utils.lib.eachDefaultSystem
(system:
let pkgs = nixpkgs.legacyPackages.${system}; in
{
default = pkgs.mkShell (
{
nativeBuildInputs = with pkgs; [
clang
pkg-config
];
buildInputs =
with pkgs;
[
rustc
cargo
rustfmt
rust-analyzer
clippy
android-tools
]
++ runtimeLibs;
devShells.default = pkgs.mkShell {
packages = with pkgs;
[
rustc
cargo
clang
pkg-config
mold
android-tools
];
RUST_SRC_PATH = "${pkgs.rustPlatform.rustLibSrc}/lib/rustlib/src/rust";
LIBCLANG_PATH = "${pkgs.llvmPackages.libclang.lib}/lib";
}
// lib.optionalAttrs stdenv.isLinux { LD_LIBRARY_PATH = lib.makeLibraryPath runtimeLibs; }
// lib.optionalAttrs stdenv.isDarwin {
DYLD_FALLBACK_LIBRARY_PATH = lib.makeLibraryPath runtimeLibs;
}
);
LD_LIBRARY_PATH = "${nixpkgs.lib.makeLibraryPath [
pkgs.fontconfig
pkgs.freetype
pkgs.libglvnd
pkgs.xorg.libX11
pkgs.xorg.libXcursor
pkgs.xorg.libXi
pkgs.xorg.libXrandr
pkgs.libxkbcommon
pkgs.wayland
]}";
LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib";
};
}
);
};
}

File diff suppressed because it is too large Load diff

View file

@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="Discord-Logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 126.644 96"><defs><style>.cls-1{fill:#5865f2;}</style></defs><path id="Discord-Symbol-Blurple" class="cls-1" d="M81.15,0c-1.2376,2.1973-2.3489,4.4704-3.3591,6.794-9.5975-1.4396-19.3718-1.4396-28.9945,0-.985-2.3236-2.1216-4.5967-3.3591-6.794-9.0166,1.5407-17.8059,4.2431-26.1405,8.0568C2.779,32.5304-1.6914,56.3725.5312,79.8863c9.6732,7.1476,20.5083,12.603,32.0505,16.0884,2.6014-3.4854,4.8998-7.1981,6.8698-11.0623-3.738-1.3891-7.3497-3.1318-10.8098-5.1523.9092-.6567,1.7932-1.3386,2.6519-1.9953,20.281,9.547,43.7696,9.547,64.0758,0,.8587.7072,1.7427,1.3891,2.6519,1.9953-3.4601,2.0457-7.0718,3.7632-10.835,5.1776,1.97,3.8642,4.2683,7.5769,6.8698,11.0623,11.5419-3.4854,22.3769-8.9156,32.0509-16.0631,2.626-27.2771-4.496-50.9172-18.817-71.8548C98.9811,4.2684,90.1918,1.5659,81.1752.0505l-.0252-.0505ZM42.2802,65.4144c-6.2383,0-11.4159-5.6575-11.4159-12.6535s4.9755-12.6788,11.3907-12.6788,11.5169,5.708,11.4159,12.6788c-.101,6.9708-5.026,12.6535-11.3907,12.6535ZM84.3576,65.4144c-6.2637,0-11.3907-5.6575-11.3907-12.6535s4.9755-12.6788,11.3907-12.6788,11.4917,5.708,11.3906,12.6788c-.101,6.9708-5.026,12.6535-11.3906,12.6535Z"/></svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

101
src/core/config.rs Normal file
View file

@ -0,0 +1,101 @@
use crate::core::utils::DisplayablePath;
use crate::core::{
sync::{get_android_sdk, User},
theme::Theme,
};
use crate::gui::views::settings::Settings;
use crate::CACHE_DIR;
use crate::CONFIG_DIR;
use serde::{Deserialize, Serialize};
use static_init::dynamic;
use std::fs;
use std::path::PathBuf;
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
pub struct Config {
pub general: GeneralSettings,
#[serde(skip_serializing_if = "Vec::is_empty", default = "Vec::new")]
pub devices: Vec<DeviceSettings>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GeneralSettings {
pub theme: String,
pub expert_mode: bool,
pub backup_folder: PathBuf,
}
#[derive(Default, Debug, Clone)]
pub struct BackupSettings {
pub backups: Vec<DisplayablePath>,
pub selected: Option<DisplayablePath>,
pub users: Vec<User>,
pub selected_user: Option<User>,
pub backup_state: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DeviceSettings {
pub device_id: String,
pub disable_mode: bool,
pub multi_user_mode: bool,
#[serde(skip)]
pub backup: BackupSettings,
}
impl Default for GeneralSettings {
fn default() -> Self {
Self {
theme: Theme::default().to_string(),
expert_mode: false,
backup_folder: CACHE_DIR.join("backups"),
}
}
}
impl Default for DeviceSettings {
fn default() -> Self {
Self {
device_id: String::default(),
multi_user_mode: get_android_sdk() > 21,
disable_mode: false,
backup: BackupSettings::default(),
}
}
}
#[dynamic]
static CONFIG_FILE: PathBuf = CONFIG_DIR.join("config.toml");
impl Config {
pub fn save_changes(settings: &Settings, device_id: &String) {
let mut config = Self::load_configuration_file();
if let Some(device) = config
.devices
.iter_mut()
.find(|x| x.device_id == *device_id)
{
*device = settings.device.clone();
} else {
debug!("config: New device settings saved");
config.devices.push(settings.device.clone());
}
config.general.clone_from(&settings.general);
let toml = toml::to_string(&config).unwrap();
fs::write(&*CONFIG_FILE, toml).expect("Could not write config file to disk!");
}
pub fn load_configuration_file() -> Self {
match fs::read_to_string(&*CONFIG_FILE) {
Ok(s) => match toml::from_str(&s) {
Ok(config) => return config,
Err(e) => error!("Invalid config file: `{}`", e),
},
Err(e) => error!("Failed to read config file: `{}`", e),
}
error!("Restoring default config file");
let toml = toml::to_string(&Self::default()).unwrap();
fs::write(&*CONFIG_FILE, toml).expect("Could not write config file to disk!");
Self::default()
}
}

14
src/core/helpers.rs Normal file
View file

@ -0,0 +1,14 @@
use crate::core::theme::Theme;
use crate::gui::style;
use iced::widget::button;
use iced::widget::button::Button;
use iced::{Element, Renderer};
/// Wrapper function for `iced::widget::button` with padding and style applied
pub fn button_primary<'a, Message>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Button<'a, Message, Theme, Renderer> {
button(content)
.padding([5, 10])
.style(style::Button::Primary)
}

8
src/core/mod.rs Normal file
View file

@ -0,0 +1,8 @@
pub mod config;
pub mod helpers;
pub mod save;
pub mod sync;
pub mod theme;
pub mod uad_lists;
pub mod update;
pub mod utils;

View file

@ -1,12 +1,15 @@
use crate::config::{Config, DeviceSettings};
use crate::sync::{CorePackage, Phone, User, apply_pkg_state_commands};
use crate::utils::DisplayablePath;
use log::{error, info, warn};
use crate::core::config::{Config, DeviceSettings};
use crate::core::sync::{apply_pkg_state_commands, CorePackage, Phone, User};
use crate::core::utils::DisplayablePath;
use crate::gui::widgets::package_row::PackageRow;
use crate::CACHE_DIR;
use serde::{Deserialize, Serialize};
use std::{
fs,
path::{Path, PathBuf},
};
use static_init::dynamic;
use std::fs;
use std::path::{Path, PathBuf};
#[dynamic]
pub static BACKUP_DIR: PathBuf = CACHE_DIR.join("backups");
#[derive(Default, Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct PhoneBackup {
@ -21,10 +24,10 @@ pub struct UserBackup {
}
/// Backup all `Uninstalled` and `Disabled` packages
pub fn backup_phone(
pub async fn backup_phone(
users: Vec<User>,
device_id: String,
phone_packages: &[Vec<CorePackage>],
phone_packages: Vec<Vec<PackageRow>>,
) -> Result<bool, String> {
let mut backup = PhoneBackup {
device_id: device_id.clone(),
@ -37,8 +40,11 @@ pub fn backup_phone(
..UserBackup::default()
};
for p in phone_packages[u.index].iter().cloned() {
user_backup.packages.push(p);
for p in phone_packages[u.index].clone() {
user_backup.packages.push(CorePackage {
name: p.name.clone(),
state: p.state,
});
}
backup.users.push(user_backup);
}
@ -49,9 +55,9 @@ pub fn backup_phone(
let backup_path = &*backup_dir.join(device_id);
if let Err(e) = fs::create_dir_all(backup_path) {
error!("BACKUP: could not create backup dir: {e}");
error!("BACKUP: could not create backup dir: {}", e);
return Err(e.to_string());
}
};
let backup_filename =
format!("{}.json", chrono::Local::now().format("%Y-%m-%d_%H-%M-%S"));
@ -66,6 +72,7 @@ pub fn backup_phone(
}
pub fn list_available_backups(dir: &Path) -> Vec<DisplayablePath> {
#[allow(clippy::option_if_let_else)]
match fs::read_dir(dir) {
Ok(files) => files
.filter_map(Result::ok)
@ -75,21 +82,24 @@ pub fn list_available_backups(dir: &Path) -> Vec<DisplayablePath> {
}
}
#[must_use]
pub fn list_available_backup_user(backup: DisplayablePath) -> Vec<User> {
match fs::read_to_string(backup.path) {
Ok(data) => serde_json::from_str::<PhoneBackup>(&data)
.expect("Unable to parse backup file")
.users
.into_iter()
.map(|u| User {
id: u.id,
index: 0,
protected: false,
})
.collect(),
Ok(data) => {
let phone_backup: PhoneBackup =
serde_json::from_str(&data).expect("Unable to parse backup file");
let mut users = vec![];
for u in phone_backup.users {
users.push(User {
id: u.id,
index: 0,
protected: false,
});
}
users
}
Err(e) => {
error!("[BACKUP]: Selected backup file not found: {e}");
error!("[BACKUP]: Selected backup file not found: {}", e);
vec![]
}
}
@ -97,22 +107,15 @@ pub fn list_available_backup_user(backup: DisplayablePath) -> Vec<User> {
#[derive(Debug)]
pub struct BackupPackage {
pub i_user: usize,
pub index: usize,
pub commands: Vec<String>,
}
#[derive(Debug)]
pub struct RestoreResult {
pub packages: Vec<BackupPackage>,
pub skipped_count: usize,
}
pub fn restore_backup(
selected_device: &Phone,
packages: &[Vec<CorePackage>],
packages: &[Vec<PackageRow>],
settings: &DeviceSettings,
) -> Result<RestoreResult, String> {
) -> Result<Vec<BackupPackage>, String> {
match fs::read_to_string(
settings
.backup
@ -127,31 +130,30 @@ pub fn restore_backup(
serde_json::from_str(&data).expect("Unable to parse backup file");
let mut commands = vec![];
let mut skipped_packages = 0;
for u in phone_backup.users {
let i_user = match selected_device.user_list.iter().find(|x| x.id == u.id) {
let index = match selected_device.user_list.iter().find(|x| x.id == u.id) {
Some(i) => i.index,
None => return Err(format!("user {} doesn't exist", u.id)),
};
for (i, backup_package) in u.packages.iter().enumerate() {
let package: CorePackage = if let Some(p) = packages[i_user]
let package: CorePackage;
match packages[index]
.iter()
.find(|x| x.name == backup_package.name)
{
p.clone()
} else {
skipped_packages += 1;
warn!(
"{} not found for user {} - skipping package during restore",
backup_package.name, u.id
);
continue;
};
Some(p) => package = p.into(),
None => {
return Err(format!(
"{} not found for user {}",
backup_package.name, u.id
))
}
}
let p_commands = apply_pkg_state_commands(
&package,
backup_package.state,
settings
&settings
.backup
.selected_user
.ok_or("field should be Some type")?,
@ -159,29 +161,19 @@ pub fn restore_backup(
);
if !p_commands.is_empty() {
commands.push(BackupPackage {
i_user,
index: i,
commands: p_commands,
});
}
}
}
if skipped_packages > 0 {
info!(
"Restore completed with {skipped_packages} packages skipped (not found on device)"
);
}
if !commands.is_empty() {
commands.push(BackupPackage {
i_user: 0,
index: 0,
commands: vec![],
});
}
Ok(RestoreResult {
packages: commands,
skipped_count: skipped_packages,
})
Ok(commands)
}
Err(e) => Err(e.to_string()),
}

351
src/core/sync.rs Normal file
View file

@ -0,0 +1,351 @@
use crate::core::uad_lists::PackageState;
use crate::core::utils::ANDROID_SERIAL;
use crate::gui::views::list::PackageInfo;
use crate::gui::widgets::package_row::PackageRow;
use regex::Regex;
use retry::{delay::Fixed, retry, OperationResult};
use serde::{Deserialize, Serialize};
use static_init::dynamic;
use std::collections::HashSet;
use std::env;
use std::process::Command;
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
#[dynamic]
static RE: Regex = Regex::new(r"\n(\S+)\s+device").unwrap();
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Phone {
pub model: String,
pub android_sdk: u8,
pub user_list: Vec<User>,
pub adb_id: String,
}
impl Default for Phone {
fn default() -> Self {
Self {
model: "fetching devices...".to_string(),
android_sdk: 0,
user_list: vec![],
adb_id: String::default(),
}
}
}
impl std::fmt::Display for Phone {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.model)
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq, Copy)]
pub struct User {
pub id: u16,
pub index: usize,
pub protected: bool,
}
impl std::fmt::Display for User {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "user {}", self.id)
}
}
pub fn adb_shell_command(shell: bool, args: &str) -> Result<String, String> {
let adb_command = if shell {
vec!["shell", args]
} else {
vec![args]
};
let mut command = Command::new("adb");
command.args(adb_command);
#[cfg(target_os = "windows")]
let command = command.creation_flags(0x08000000); // do not open a cmd window
match command.output() {
Err(e) => {
error!("ADB: {}", e);
Err("ADB was not found".to_string())
}
Ok(o) => {
if o.status.success() {
Ok(String::from_utf8(o.stdout)
.map_err(|e| e.to_string())?
.trim_end()
.to_string())
} else {
let stdout = String::from_utf8(o.stdout)
.map_err(|e| e.to_string())?
.trim_end()
.to_string();
let stderr = String::from_utf8(o.stderr)
.map_err(|e| e.to_string())?
.trim_end()
.to_string();
// ADB does really weird things. Some errors are not redirected to stderr
let err = if stdout.is_empty() { stderr } else { stdout };
Err(err)
}
}
}
}
#[derive(Debug, Clone)]
pub enum CommandType {
PackageManager(PackageInfo),
Shell,
}
/// An enum to contain different variants for errors yielded by ADB.
#[derive(Debug, Clone)]
pub enum AdbError {
Generic(String),
}
pub async fn perform_adb_commands(
action: String,
command_type: CommandType,
) -> Result<CommandType, AdbError> {
let label = match &command_type {
CommandType::PackageManager(p) => &p.removal,
CommandType::Shell => "Shell",
};
match adb_shell_command(true, &action) {
Ok(o) => {
// On old devices, adb commands can return the `0` exit code even if there
// is an error. On Android 4.4, ADB doesn't check if the package exists.
// It does not return any error if you try to `pm block` a non-existent package.
// Some commands are even killed by ADB before finishing and UAD-ng can't catch
// the output.
if ["Error", "Failure"].iter().any(|&e| o.contains(e)) {
return Err(AdbError::Generic(format!("[{label}] {action} -> {o}")));
}
info!("[{label}] {action} -> {o}");
Ok(command_type)
}
Err(err) => {
if !err.contains("[not installed for") {
return Err(AdbError::Generic(format!("[{label}] {action} -> {err}")));
}
Err(AdbError::Generic(err))
}
}
}
pub fn user_flag(user_id: Option<&User>) -> String {
user_id
.map(|user| format!(" --user {}", user.id))
.unwrap_or_default()
}
pub fn list_all_system_packages(user_id: Option<&User>) -> String {
let action = format!("pm list packages -s -u{}", user_flag(user_id));
adb_shell_command(true, &action)
.unwrap_or_default()
.replace("package:", "")
}
pub fn hashset_system_packages(state: PackageState, user_id: Option<&User>) -> HashSet<String> {
let user = user_flag(user_id);
let action = match state {
PackageState::Enabled => format!("pm list packages -s -e{user}"),
PackageState::Disabled => format!("pm list package -s -d{user}"),
_ => String::default(), // You probably don't need to use this function for anything else
};
adb_shell_command(true, &action)
.unwrap_or_default()
.replace("package:", "")
.lines()
.map(String::from)
.collect()
}
// Minimum information for processing adb commands
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct CorePackage {
pub name: String,
pub state: PackageState,
}
impl From<&mut PackageRow> for CorePackage {
fn from(pr: &mut PackageRow) -> Self {
Self {
name: pr.name.clone(),
state: pr.state,
}
}
}
impl From<PackageRow> for CorePackage {
fn from(pr: PackageRow) -> Self {
Self {
name: pr.name.clone(),
state: pr.state,
}
}
}
impl From<&PackageRow> for CorePackage {
fn from(pr: &PackageRow) -> Self {
Self {
name: pr.name.clone(),
state: pr.state,
}
}
}
pub fn apply_pkg_state_commands(
package: &CorePackage,
wanted_state: PackageState,
selected_user: &User,
phone: &Phone,
) -> Vec<String> {
// https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki/ADB-reference
// ALWAYS PUT THE COMMAND THAT CHANGES THE PACKAGE STATE FIRST!
let commands = match wanted_state {
PackageState::Enabled => {
match package.state {
PackageState::Disabled => match phone.android_sdk {
i if i >= 23 => vec!["pm enable"],
_ => vec!["pm enable"],
},
PackageState::Uninstalled => match phone.android_sdk {
i if i >= 23 => vec!["cmd package install-existing"],
21 | 22 => vec!["pm unhide"],
19 | 20 => vec!["pm unblock", "pm clear"],
_ => vec![], // Impossible action already prevented by the GUI
},
_ => vec![],
}
}
PackageState::Disabled => match package.state {
PackageState::Uninstalled | PackageState::Enabled => match phone.android_sdk {
sdk if sdk >= 23 => vec!["pm disable-user", "am force-stop", "pm clear"],
_ => vec![],
},
_ => vec![],
},
PackageState::Uninstalled => match package.state {
PackageState::Enabled | PackageState::Disabled => match phone.android_sdk {
sdk if sdk >= 23 => vec!["pm uninstall"], // > Android Marshmallow (6.0)
21 | 22 => vec!["pm hide", "pm clear"], // Android Lollipop (5.x)
19 | 20 => vec!["pm block", "pm clear"], // Android KitKat (4.4/4.4W)
_ => vec!["pm block", "pm clear"], // Disable mode is unavailable on older devices because the specific ADB commands need root
},
_ => vec![],
},
PackageState::All => vec![],
};
let user = (phone.android_sdk >= 21).then_some(selected_user);
request_builder(&commands, &package.name, user)
}
/// Build a command request to be sent via ADB to a device.
/// `commands` accepts one or more ADB shell commands
/// which act on a common `package` and `user`.
pub fn request_builder(commands: &[&str], package: &str, user: Option<&User>) -> Vec<String> {
let maybe_user_flag = user_flag(user);
commands
.iter()
.map(|c| format!("{}{} {}", c, maybe_user_flag, package))
.collect()
}
/// Get the current device model by querying the `ro.product.model` property.
pub fn get_phone_model() -> String {
adb_shell_command(true, "getprop ro.product.model").unwrap_or_else(|err| {
println!("ERROR: {err}");
if err.contains("adb: no devices/emulators found") {
"no devices/emulators found".to_string()
} else {
err
}
})
}
/// Get the current device Android SDK version by querying the
// `ro.build.version.sdk` property or defaulting to 0.
pub fn get_android_sdk() -> u8 {
adb_shell_command(true, "getprop ro.build.version.sdk").map_or(0, |sdk| sdk.parse().unwrap())
}
/// Get the current device brand by querying the `ro.product.brand` property.
pub fn get_phone_brand() -> String {
format!(
"{} {}",
adb_shell_command(true, "getprop ro.product.brand")
.map(|s| s.trim().to_string())
.unwrap_or_default(),
get_phone_model()
)
}
/// Check if a `user_id` is protected on a device by trying
/// to list associated packages.
pub fn is_protected_user(user_id: &str) -> bool {
adb_shell_command(true, &format!("pm list packages -s --user {user_id}")).is_err()
}
pub fn get_user_list() -> Vec<User> {
#[dynamic]
static RE: Regex = Regex::new(r"\{([0-9]+)").unwrap();
adb_shell_command(true, "pm list users")
.map(|users| {
RE.find_iter(&users)
.enumerate()
.map(|(i, u)| User {
id: u.as_str()[1..].parse().unwrap(),
index: i,
protected: is_protected_user(&u.as_str()[1..]),
})
.collect()
})
.unwrap_or_default()
}
// getprop ro.serialno
pub async fn get_devices_list() -> Vec<Phone> {
retry(
Fixed::from_millis(500).take(120),
|| match adb_shell_command(false, "devices") {
Ok(devices) => {
let mut device_list: Vec<Phone> = vec![];
if !RE.is_match(&devices) {
return OperationResult::Retry(vec![]);
}
for device in RE.captures_iter(&devices) {
env::set_var(ANDROID_SERIAL, &device[1]);
device_list.push(Phone {
model: get_phone_brand(),
android_sdk: get_android_sdk(),
user_list: get_user_list(),
adb_id: device[1].to_string(),
});
}
OperationResult::Ok(device_list)
}
Err(err) => {
error!("get_device_list() -> {}", err);
let test: Vec<Phone> = vec![];
OperationResult::Retry(test)
}
},
)
.unwrap_or_default()
}
pub async fn initial_load() -> bool {
match adb_shell_command(false, "devices") {
Ok(_devices) => true,
Err(_err) => false,
}
}

View file

@ -1,18 +1,5 @@
use iced::theme::{self, Mode, Palette, Style};
use iced::{Color, color};
use std::sync::LazyLock;
/*
In-memory caching.
This fixes the perf bug
caused by Iced repeatedly calling `palette`.
Coincidentally, this also ensures consistent colors across the GUI,
at the cost of requiring a restart to update the palette.
(this is just a patch, not a fix)
*/
pub static OS_COLOR_SCHEME: LazyLock<dark_light::Mode> =
LazyLock::new(|| dark_light::detect().unwrap_or(dark_light::Mode::Unspecified));
use dark_light;
use iced::{color, Color};
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone)]
/// Color scheme
@ -37,7 +24,7 @@ pub struct BaseColors {
#[derive(Debug, Clone, Copy)]
pub struct NormalColors {
pub primary: Color,
#[allow(dead_code, reason = "Reserved for future palette updates")]
#[allow(dead_code)]
pub secondary: Color,
pub surface: Color,
pub error: Color,
@ -65,8 +52,6 @@ impl Theme {
clippy::unreadable_literal,
reason = "https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/pull/578#discussion_r1759653408"
)]
/// This `fn` _could_ be `const`,
/// but `deref`ing a lazy-`static` is non-`const`.
#[must_use]
pub fn palette(self) -> ColorPalette {
const DARK: ColorPalette = ColorPalette {
@ -127,9 +112,11 @@ impl Theme {
Self::Dark => DARK,
Self::Light => LIGHT,
Self::Lupin => LUPIN,
Self::Auto => match *OS_COLOR_SCHEME {
#[allow(clippy::match_same_arms)]
Self::Auto => match dark_light::detect() {
dark_light::Mode::Light => LIGHT,
dark_light::Mode::Dark | dark_light::Mode::Unspecified => DARK,
dark_light::Mode::Dark => DARK,
dark_light::Mode::Default => DARK,
},
}
}
@ -149,71 +136,3 @@ impl std::fmt::Display for Theme {
)
}
}
/// Converts a string to the GUI's Theme type
#[must_use]
pub fn string_to_theme(theme: &str) -> Theme {
match theme {
"Lupin" => Theme::Lupin,
"Dark" => Theme::Dark,
"Light" => Theme::Light,
_ => Theme::Auto,
}
}
impl theme::Base for Theme {
fn default(preference: Mode) -> Self {
match preference {
Mode::Light => Self::Light,
Mode::Dark => Self::Dark,
Mode::None => match *OS_COLOR_SCHEME {
dark_light::Mode::Light => Self::Light,
dark_light::Mode::Dark | dark_light::Mode::Unspecified => Self::Dark,
},
}
}
fn mode(&self) -> Mode {
let resolved = match self {
Self::Auto => match *OS_COLOR_SCHEME {
dark_light::Mode::Light => Self::Light,
dark_light::Mode::Dark | dark_light::Mode::Unspecified => Self::Dark,
},
other => *other,
};
match resolved {
Self::Light => Mode::Light,
_ => Mode::Dark,
}
}
fn base(&self) -> Style {
let p = Self::palette(*self);
Style {
background_color: p.base.background,
text_color: p.bright.surface,
}
}
fn palette(&self) -> Option<Palette> {
let p = Self::palette(*self);
Some(Palette {
background: p.base.background,
text: p.bright.surface,
primary: p.normal.primary,
success: p.bright.secondary,
warning: p.normal.surface,
danger: p.normal.error,
})
}
fn name(&self) -> &str {
match self {
Self::Dark => "Dark",
Self::Light => "Light",
Self::Lupin => "Lupin",
Self::Auto => "Auto",
}
}
}

View file

@ -1,10 +1,8 @@
use crate::core::utils::{format_diff_time_from_now, last_modified_date};
use crate::CACHE_DIR;
use crate::utils::{format_diff_time_from_now, last_modified_date};
use log::warn;
use retry::{OperationResult, delay::Fixed, retry};
use retry::{delay::Fixed, retry, OperationResult};
use serde::{Deserialize, Serialize};
use serde_json;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
@ -16,7 +14,8 @@ pub const LIST_FNAME: &str = "uad_lists.json";
reason = "https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/discussions/608"
)]
// not `const`, because it's too big
pub static DATA: &str = include_str!("../../../resources/assets/uad_lists.json");
pub static DATA: &str = include_str!("../../resources/assets/uad_lists.json");
// TODO: use `const_format` crate
#[derive(Deserialize, Debug, Clone, PartialEq, Hash, Eq)]
#[serde(rename_all = "camelCase")]
@ -29,7 +28,7 @@ pub struct Package {
pub removal: Removal,
}
#[derive(Default, Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(Default, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UadList {
#[default]
All,
@ -73,31 +72,24 @@ impl UadList {
Self::Pending,
Self::Unlisted,
];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::All => "All lists",
Self::Aosp => "aosp",
Self::Carrier => "carrier",
Self::Google => "google",
Self::Misc => "misc",
Self::Oem => "oem",
Self::Pending => "pending",
Self::Unlisted => "unlisted",
}
}
}
impl std::fmt::Display for UadList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl From<UadList> for Cow<'_, str> {
fn from(list: UadList) -> Self {
Cow::Borrowed(list.as_str())
write!(
f,
"{}",
match self {
Self::All => "All lists",
Self::Aosp => "aosp",
Self::Carrier => "carrier",
Self::Google => "google",
Self::Misc => "misc",
Self::Oem => "oem",
Self::Pending => "pending",
Self::Unlisted => "unlisted",
}
)
}
}
@ -120,7 +112,7 @@ impl std::fmt::Display for PackageState {
f,
"{}",
match self {
Self::All => "All states",
Self::All => "All packages",
Self::Enabled => "Enabled",
Self::Uninstalled => "Uninstalled",
Self::Disabled => "Disabled",
@ -150,7 +142,7 @@ impl Opposite for PackageState {
}
// Bad names. To be changed!
#[derive(Default, Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(Default, Debug, Deserialize, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Removal {
#[default]
Recommended,
@ -177,29 +169,22 @@ impl Removal {
Self::Unsafe,
Self::Unlisted,
];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::All => "All removals",
Self::Recommended => "Recommended",
Self::Advanced => "Advanced",
Self::Expert => "Expert",
Self::Unsafe => "Unsafe",
Self::Unlisted => "Unlisted",
}
}
}
impl std::fmt::Display for Removal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl From<Removal> for Cow<'_, str> {
fn from(list: Removal) -> Self {
Cow::Borrowed(list.as_str())
write!(
f,
"{}",
match self {
Self::All => "All",
Self::Recommended => "Recommended",
Self::Advanced => "Advanced",
Self::Expert => "Expert",
Self::Unsafe => "Unsafe",
Self::Unlisted => "Unlisted",
}
)
}
}
@ -209,32 +194,23 @@ pub fn load_debloat_lists(remote: bool) -> Result<PackageHashMap, PackageHashMap
let mut error = false;
let list: PackageHashMap = if remote {
retry(Fixed::from_millis(1000).take(60), || {
match ureq::get(format!(
"https://raw.githubusercontent.com\
/Universal-Debloater-Alliance\
/universal-android-debloater\
/main\
/resources\
/assets\
/{LIST_FNAME}"
))
match ureq::get(
&format!("https://raw.githubusercontent.com/Universal-Debloater-Alliance/universal-android-debloater/\
main/resources/assets/{LIST_FNAME}"),
)
.call()
{
Ok(mut data) => {
// https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/discussions/608
let text = data
.body_mut()
.with_config()
.limit(1 << (3 + 10 + 10))
.read_to_string()
.expect("remote list is bigger than 8MiB");
Ok(data) => {
// TODO: max resp size is 10MB, list is ~1.3MB;
// TODO: https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/discussions/608
#[warn(clippy::expect_used, reason = "this will panic if GH servers rate-limit the user, or many other reasons.")]
let text = data.into_string().expect("response should be Ok type");
fs::write(cached_uad_lists.clone(), &text).expect("Unable to write file");
let list: PackageHashMap =
serde_json::from_str(&text).expect("Unable to parse");
let list: PackageHashMap = serde_json::from_str(&text).expect("Unable to parse");
OperationResult::Ok(list)
}
Err(e) => {
warn!("Could not load remote debloat list: {e}");
warn!("Could not load remote debloat list: {}", e);
error = true;
OperationResult::Retry(PackageHashMap::new())
}

View file

@ -1,10 +1,10 @@
use crate::core::utils::NAME;
use serde::Deserialize;
#[cfg(feature = "self-update")]
use {
crate::utils::NAME,
log::{debug, error},
retry::{OperationResult, delay::Fibonacci, retry},
retry::{delay::Fibonacci, retry, OperationResult},
std::fs,
std::io,
std::io::copy,
@ -55,14 +55,15 @@ impl std::fmt::Display for SelfUpdateStatus {
/// Download a file from the internet
#[cfg(feature = "self-update")]
#[allow(clippy::unused_async, reason = "`.call` is equivalent to `.await`")]
pub async fn download_file(url: &str, dest_file: PathBuf) -> Result<(), String> {
debug!("downloading file from {url}");
pub async fn download_file<T: ToString + Send>(url: T, dest_file: PathBuf) -> Result<(), String> {
let url = url.to_string();
debug!("downloading file from {}", &url);
match ureq::get(url).call() {
Ok(mut res) => {
match ureq::get(&url).call() {
Ok(res) => {
let mut file = fs::File::create(dest_file).map_err(|e| e.to_string())?;
if let Err(e) = copy(&mut res.body_mut().as_reader(), &mut file) {
if let Err(e) = copy(&mut res.into_reader(), &mut file) {
return Err(e.to_string());
}
}
@ -76,7 +77,7 @@ pub async fn download_file(url: &str, dest_file: PathBuf) -> Result<(), String>
/// then returns both the original file name (new version) and temp path (old version)
#[cfg(feature = "self-update")]
pub async fn download_update_to_temp_file(
bin_name: &str,
bin_name: String,
release: Release,
) -> Result<(PathBuf, PathBuf), ()> {
let current_bin_path = std::env::current_exe().map_err(|_| ())?;
@ -109,8 +110,8 @@ pub async fn download_update_to_temp_file(
let archive_path = current_bin_path.parent().ok_or(())?.join(&asset_name);
if let Err(e) = download_file(&asset.download_url, archive_path.clone()).await {
error!("Couldn't download {NAME} update: {e}");
if let Err(e) = download_file(asset.download_url, archive_path.clone()).await {
error!("Couldn't download {NAME} update: {}", e);
return Err(());
}
@ -132,7 +133,7 @@ pub async fn download_update_to_temp_file(
.cloned()
.ok_or(())?;
if let Err(e) = download_file(&asset.download_url, download_path.clone()).await {
if let Err(e) = download_file(asset.download_url, download_path.clone()).await {
error!("Couldn't download {NAME} update: {}", e);
return Err(());
}
@ -146,17 +147,23 @@ pub async fn download_update_to_temp_file(
let mut permissions = fs::metadata(&download_path).map_err(|_| ())?.permissions();
permissions.set_mode(0o755);
if let Err(e) = fs::set_permissions(&download_path, permissions) {
error!("[SelfUpdate] Couldn't set permission to temp file: {e}");
error!("[SelfUpdate] Couldn't set permission to temp file: {}", e);
return Err(());
}
}
if let Err(e) = rename(&current_bin_path, &tmp_path) {
error!("[SelfUpdate] Couldn't rename from current to temporary binary path: {e}");
error!(
"[SelfUpdate] Couldn't rename from current to temporary binary path: {}",
e
);
return Err(());
}
if let Err(e) = rename(&download_path, &current_bin_path) {
error!("[SelfUpdate] Couldn't rename from downloaded to current binary path: {e}");
error!(
"[SelfUpdate] Couldn't rename from downloaded to current binary path: {}",
e
);
return Err(());
}
@ -175,10 +182,10 @@ pub fn get_latest_release() -> Result<Option<Release>, ()> {
pub fn get_latest_release() -> Result<Option<Release>, ()> {
debug!("Checking for {NAME} update");
if let Ok(mut res) = ureq::get("https://api.github.com/repos/Universal-Debloater-Alliance/universal-android-debloater/releases/latest")
if let Ok(res) = ureq::get("https://api.github.com/repos/Universal-Debloater-Alliance/universal-android-debloater/releases/latest")
.call() {
let release: Release = serde_json::from_value(
res.body_mut().read_json::<serde_json::Value>()
res.into_json::<serde_json::Value>()
.map_err(|_| ())?
.clone(),
)
@ -225,18 +232,13 @@ pub fn extract_binary_from_tar(archive_path: &Path, temp_file: &Path) -> io::Res
/// Hardcoded binary names for each compilation target
/// that gets published to the GitHub Release
#[cfg(feature = "self-update")]
pub const BIN_NAME: &str = {
pub const fn bin_name() -> &'static str {
#[cfg(target_os = "windows")]
{
"uad-ng-windows.exe"
"uad-ng.exe"
}
#[cfg(all(target_os = "macos", any(target_arch = "x86_64", target_arch = "x86")))]
{
"uad-ng-macos-intel"
}
#[cfg(all(target_os = "macos", any(target_arch = "arm", target_arch = "aarch64")))]
#[cfg(target_os = "macos")]
{
"uad-ng-macos"
}
@ -245,7 +247,7 @@ pub const BIN_NAME: &str = {
{
"uad-ng-linux"
}
};
}
/// Rename a file or directory to a new name, retrying if the operation fails because of permissions
///

211
src/core/utils.rs Normal file
View file

@ -0,0 +1,211 @@
use crate::core::sync::{hashset_system_packages, list_all_system_packages, User};
use crate::core::theme::Theme;
use crate::core::uad_lists::{PackageHashMap, PackageState, Removal, UadList};
use crate::gui::widgets::package_row::PackageRow;
use chrono::offset::Utc;
use chrono::{DateTime, Local};
use csv::Writer;
use std::path::PathBuf;
use std::process::Command;
use std::{fmt, fs};
/// Canonical shortened name of the application
pub const NAME: &str = "UAD-ng";
/// Global environment variable to keep
/// track of the current device serial.
///
/// [More info](https://developer.android.com/tools/variables#adb)
pub const ANDROID_SERIAL: &str = "ANDROID_SERIAL";
pub const EXPORT_FILE_NAME: &str = "selection_export.txt";
pub const UNINSTALLED_PACKAGES_FILE_NAME: &str = "uninstalled_packages";
#[derive(Debug, Clone)]
pub enum Error {
DialogClosed,
}
pub fn fetch_packages(uad_lists: &PackageHashMap, user_id: Option<&User>) -> Vec<PackageRow> {
let all_system_packages = list_all_system_packages(user_id); // installed and uninstalled packages
let enabled_system_packages = hashset_system_packages(PackageState::Enabled, user_id);
let disabled_system_packages = hashset_system_packages(PackageState::Disabled, user_id);
let mut description;
let mut uad_list;
let mut state;
let mut removal;
let mut user_package: Vec<PackageRow> = Vec::new();
for p_name in all_system_packages.lines() {
state = PackageState::Uninstalled;
description = "[No description]: CONTRIBUTION WELCOMED";
uad_list = UadList::Unlisted;
removal = Removal::Unlisted;
if let Some(package) = uad_lists.get(p_name) {
if !package.description.is_empty() {
description = &package.description;
}
uad_list = package.list;
removal = package.removal;
}
if enabled_system_packages.contains(p_name) {
state = PackageState::Enabled;
} else if disabled_system_packages.contains(p_name) {
state = PackageState::Disabled;
}
let package_row =
PackageRow::new(p_name, state, description, uad_list, removal, false, false);
user_package.push(package_row);
}
user_package.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
user_package
}
pub fn string_to_theme(theme: &str) -> Theme {
match theme {
"Dark" => Theme::Dark,
"Light" => Theme::Light,
"Lupin" => Theme::Lupin,
// Auto uses `Display`, so it doesn't have a canonical repr
t if t.starts_with("Auto") => Theme::Auto,
_ => Theme::default(),
}
}
pub fn setup_uad_dir(dir: &PathBuf) -> PathBuf {
let dir = dir.join("uad");
if let Err(e) = fs::create_dir_all(&dir) {
error!("Can't create directory: {dir:?}");
panic!("{e}");
};
dir
}
pub fn open_url(dir: PathBuf) {
#[cfg(target_os = "windows")]
let output = Command::new("explorer").args([dir]).output();
#[cfg(target_os = "macos")]
let output = Command::new("open").args([dir]).output();
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
let output = Command::new("xdg-open").args([dir]).output();
match output {
Ok(o) => {
if !o.status.success() {
let stderr = String::from_utf8(o.stderr).unwrap().trim_end().to_string();
error!("Can't open the following URL: {}", stderr);
}
}
Err(e) => error!("Failed to run command to open the file explorer: {}", e),
}
}
#[rustfmt::skip]
#[allow(clippy::option_if_let_else)]
pub fn last_modified_date(file: PathBuf) -> DateTime<Utc> {
fs::metadata(file).map_or_else(|_| Utc::now(), |metadata| match metadata.modified() {
Ok(time) => time.into(),
Err(_) => Utc::now(),
})
}
pub fn format_diff_time_from_now(date: DateTime<Utc>) -> String {
let now: DateTime<Utc> = Utc::now();
let last_update = now - date;
if last_update.num_days() == 0 {
if last_update.num_hours() == 0 {
last_update.num_minutes().to_string() + " min(s) ago"
} else {
last_update.num_hours().to_string() + " hour(s) ago"
}
} else {
last_update.num_days().to_string() + " day(s) ago"
}
}
/// Export selected packages.
/// File will be saved in same directory where UAD-ng is located.
pub async fn export_selection(packages: Vec<PackageRow>) -> Result<bool, String> {
let selected = packages
.iter()
.filter(|p| p.selected)
.map(|p| p.name.clone())
.collect::<Vec<String>>()
.join("\n");
match fs::write(EXPORT_FILE_NAME, selected) {
Ok(()) => Ok(true),
Err(err) => Err(err.to_string()),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DisplayablePath {
pub path: PathBuf,
}
impl fmt::Display for DisplayablePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let stem = self.path.file_stem().map_or_else(
|| {
error!("[PATH STEM]: No file stem found");
"[File steam not found]".to_string()
},
|p| match p.to_os_string().into_string() {
Ok(stem) => stem,
Err(e) => {
error!("[PATH ENCODING]: {:?}", e);
"[PATH ENCODING ERROR]".to_string()
}
},
);
write!(f, "{stem}")
}
}
/// Can be used to choose any folder.
pub async fn open_folder() -> Result<PathBuf, Error> {
let picked_folder = rfd::AsyncFileDialog::new()
.pick_folder()
.await
.ok_or(Error::DialogClosed)?;
Ok(picked_folder.path().to_owned())
}
/// Export uninstalled packages in a csv file.
/// Exported information will contain package name and description.
pub async fn export_packages(
user: User,
phone_packages: Vec<Vec<PackageRow>>,
) -> Result<bool, String> {
let backup_file = format!(
"{}_{}.csv",
UNINSTALLED_PACKAGES_FILE_NAME,
Local::now().format("%Y%m%d")
);
let file = fs::File::create(backup_file).map_err(|err| err.to_string())?;
let mut wtr = Writer::from_writer(file);
wtr.write_record(["Package Name", "Description"])
.map_err(|err| err.to_string())?;
let uninstalled_packages: Vec<&PackageRow> = phone_packages[user.index]
.iter()
.filter(|p| p.state == PackageState::Uninstalled)
.collect();
for package in uninstalled_packages {
wtr.write_record([&package.name, &package.description.replace('\n', " ")])
.map_err(|err| err.to_string())?;
}
wtr.flush().map_err(|err| err.to_string())?;
Ok(true)
}

View file

@ -1,32 +1,32 @@
#[cfg(feature = "img")]
use crate::theme::OS_COLOR_SCHEME;
use crate::theme::Theme;
use crate::theme::string_to_theme;
use crate::views::about::{About as AboutView, Message as AboutMessage};
use crate::views::list::{
List as AppsView, LoadingState as ListLoadingState, Message as AppsMessage,
};
use crate::views::settings::{Message as SettingsMessage, Settings as SettingsView};
use crate::widgets::navigation_menu::nav_menu;
pub mod style;
pub mod views;
pub mod widgets;
use crate::core::sync::{get_devices_list, initial_load, perform_adb_commands, CommandType, Phone};
use crate::core::theme::Theme;
use crate::core::uad_lists::UadListState;
use crate::core::update::{get_latest_release, Release, SelfUpdateState, SelfUpdateStatus};
use crate::core::utils::{string_to_theme, ANDROID_SERIAL, NAME};
use iced::advanced::graphics::image::image_rs::ImageFormat;
use iced::font;
use iced::widget::column;
#[cfg(feature = "img")]
use iced::window::icon;
use iced::{Alignment, Element, Length, Settings, Task, window::Settings as Window};
use iced::{Subscription, event, keyboard};
#[cfg(feature = "img")]
use image::ImageFormat;
use log::{debug, error, info};
use views::about::{About as AboutView, Message as AboutMessage};
use views::list::{List as AppsView, LoadingState as ListLoadingState, Message as AppsMessage};
use views::settings::{Message as SettingsMessage, Settings as SettingsView};
use widgets::navigation_menu::nav_menu;
use iced::widget::column;
use iced::{
window::Settings as Window, Alignment, Application, Command, Element, Length, Renderer,
Settings,
};
use std::env;
#[cfg(feature = "self-update")]
use std::path::PathBuf;
use uad_core::adb;
use uad_core::sync::{Phone, get_devices_list, initial_load};
use uad_core::uad_lists::UadListState;
use uad_core::update::{Release, SelfUpdateState, SelfUpdateStatus, get_latest_release};
use uad_core::utils::{FULL_NAME, NAME};
#[cfg(feature = "self-update")]
use uad_core::update::{BIN_NAME, download_update_to_temp_file, remove_file};
use crate::core::update::{bin_name, download_update_to_temp_file, remove_file};
#[derive(Default, Debug, Clone)]
enum View {
@ -38,11 +38,11 @@ enum View {
#[derive(Default, Clone)]
pub struct UpdateState {
pub self_update: SelfUpdateState,
pub uad_list: UadListState,
self_update: SelfUpdateState,
uad_list: UadListState,
}
#[derive(Default)]
#[derive(Default, Clone)]
pub struct UadGui {
view: View,
apps_view: AppsView,
@ -77,28 +77,22 @@ pub enum Message {
ADBSatisfied(bool),
}
impl UadGui {
#[allow(
clippy::unused_self,
reason = "required by iced's Application trait interface"
)]
fn title(&self) -> String {
self.selected_device.as_ref().map_or_else(
|| FULL_NAME.to_string(),
|device| format!("{FULL_NAME} - {}", device.model),
)
}
impl Application for UadGui {
type Theme = Theme;
type Executor = iced::executor::Default;
type Message = Message;
type Flags = ();
fn new() -> (Self, Task<Message>) {
fn new(_flags: ()) -> (Self, Command<Message>) {
(
Self::default(),
Task::batch([
// Used in crate::widgets::navigation_menu::ICONS. Name is `icomoon`.
font::load(include_bytes!("../../../resources/assets/icons.ttf").as_slice())
Command::batch([
// Used in crate::gui::widgets::navigation_menu::ICONS. Name is `icomoon`.
font::load(include_bytes!("../../resources/assets/icons.ttf").as_slice())
.map(Message::FontLoaded),
Task::perform(async { initial_load() }, Message::ADBSatisfied),
Task::perform(async { get_devices_list() }, Message::LoadDevices),
Task::perform(
Command::perform(initial_load(), Message::ADBSatisfied),
Command::perform(get_devices_list(), Message::LoadDevices),
Command::perform(
async move { get_latest_release() },
Message::GetLatestRelease,
),
@ -106,58 +100,18 @@ impl UadGui {
)
}
#[allow(
clippy::unused_self,
reason = "required by iced's Application trait interface"
)]
fn subscription(&self) -> Subscription<Message> {
if self.selected_device.is_some() {
event::listen_with(Self::keyboard_shortcuts_with_device)
} else {
event::listen_with(Self::keyboard_shortcuts_without_device)
}
fn theme(&self) -> Theme {
string_to_theme(&self.settings_view.general.theme)
}
fn keyboard_shortcuts_with_device(
event: iced::Event,
_status: iced::event::Status,
_window: iced::window::Id,
) -> Option<Message> {
Self::keyboard_shortcuts(event, true)
fn title(&self) -> String {
String::from("Universal Android Debloater Next Generation")
}
fn keyboard_shortcuts_without_device(
event: iced::Event,
_status: iced::event::Status,
_window: iced::window::Id,
) -> Option<Message> {
Self::keyboard_shortcuts(event, false)
}
fn keyboard_shortcuts(event: iced::Event, can_control_device: bool) -> Option<Message> {
match event {
iced::Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Character(c),
modifiers,
..
}) if modifiers.control() && modifiers.shift() => match c.as_str() {
"r" if can_control_device => Some(Message::RebootButtonPressed),
"5" if can_control_device => Some(Message::RefreshButtonPressed),
"a" => Some(Message::AppsPress),
"i" => Some(Message::AboutPressed),
"s" => Some(Message::SettingsPressed),
_ => None,
},
_ => None,
}
}
#[allow(
clippy::too_many_lines,
reason = "Root GUI update orchestrates many flows"
)]
fn update(&mut self, msg: Message) -> Task<Message> {
// TODO: refactor later
#[allow(clippy::too_many_lines)]
fn update(&mut self, msg: Message) -> Command<Message> {
match msg {
#[allow(clippy::option_if_let_else)]
Message::LoadDevices(devices_list) => {
self.selected_device = match &self.selected_device {
Some(s_device) => {
@ -171,7 +125,7 @@ impl UadGui {
};
self.devices_list = devices_list;
#[expect(unused_must_use, reason = "side-effect")]
#[allow(unused_must_use)]
{
self.update(Message::SettingsAction(SettingsMessage::LoadDeviceSettings));
}
@ -180,40 +134,36 @@ impl UadGui {
}
Message::AppsPress => {
self.view = View::List;
Task::none()
Command::none()
}
Message::AboutPressed => {
self.view = View::About;
self.update_state.self_update = SelfUpdateState::default();
Task::perform(
Command::perform(
async move { get_latest_release() },
Message::GetLatestRelease,
)
}
Message::SettingsPressed => {
self.view = View::Settings;
Task::none()
Command::none()
}
Message::RefreshButtonPressed => {
self.apps_view = AppsView::default();
#[expect(unused_must_use, reason = "side-effect")]
#[allow(unused_must_use)]
{
self.update(Message::AppsAction(AppsMessage::ADBSatisfied(
self.adb_satisfied,
)));
}
Task::perform(async { get_devices_list() }, Message::LoadDevices)
Command::perform(get_devices_list(), Message::LoadDevices)
}
Message::RebootButtonPressed => {
self.apps_view = AppsView::default();
let serial = match &self.selected_device {
Some(d) => d.adb_id.clone(),
_ => String::default(),
};
self.selected_device = None;
self.devices_list = vec![];
Task::perform(
async { adb::ACommand::new().shell(serial).reboot() },
Command::perform(
perform_adb_commands("reboot".to_string(), CommandType::Shell),
|_| Message::Nothing,
)
}
@ -232,7 +182,7 @@ impl UadGui {
self.nb_running_async_adb_commands -= 1;
self.view = View::List;
#[expect(unused_must_use, reason = "side-effect")]
#[allow(unused_must_use)]
{
self.apps_view.update(
&mut self.settings_view,
@ -288,22 +238,24 @@ impl UadGui {
{
self.update_state.self_update.status = SelfUpdateStatus::Updating;
self.apps_view.loading_state = ListLoadingState::_UpdatingUad;
Task::perform(
download_update_to_temp_file(BIN_NAME, release.clone()),
let bin_name = bin_name().to_owned();
Command::perform(
download_update_to_temp_file(bin_name, release.clone()),
Message::_NewReleaseDownloaded,
)
} else {
Task::none()
Command::none()
}
#[cfg(not(feature = "self-update"))]
Task::none()
Command::none()
}
AboutMessage::UrlPressed(_) => Task::none(),
AboutMessage::UrlPressed(_) => Command::none(),
}
}
Message::DeviceSelected(s_device) => {
self.selected_device = Some(s_device.clone());
self.view = View::List;
env::set_var(ANDROID_SERIAL, s_device.adb_id);
info!("{:-^65}", "-");
info!(
"ANDROID_SDK: {} | DEVICE: {}",
@ -312,7 +264,7 @@ impl UadGui {
info!("{:-^65}", "-");
self.apps_view.loading_state = ListLoadingState::FindingPhones;
#[expect(unused_must_use, reason = "side-effects")]
#[allow(unused_must_use)]
{
self.update(Message::SettingsAction(SettingsMessage::LoadDeviceSettings));
self.update(Message::AppsAction(AppsMessage::ToggleAllSelected(false)));
@ -347,26 +299,26 @@ impl UadGui {
{
Ok(_) => {
if let Err(e) = remove_file(cleanup_path) {
error!("Could not remove temp update file: {e}");
error!("Could not remove temp update file: {}", e);
}
std::process::exit(0)
}
Err(error) => {
if let Err(e) = remove_file(cleanup_path) {
error!("Could not remove temp update file: {e}");
error!("Could not remove temp update file: {}", e);
}
error!("Failed to update {NAME}: {error}");
error!("Failed to update {NAME}: {}", error);
}
}
} else {
error!("Failed to update {NAME}!");
#[expect(unused_must_use, reason = "side-effect")]
#[allow(unused_must_use)]
{
self.update(Message::AppsAction(AppsMessage::UpdateFailed));
self.update_state.self_update.status = SelfUpdateStatus::Failed;
}
}
Task::none()
Command::none()
}
Message::GetLatestRelease(release) => {
match release {
@ -375,15 +327,15 @@ impl UadGui {
self.update_state.self_update.latest_release = r;
}
Err(()) => self.update_state.self_update.status = SelfUpdateStatus::Failed,
}
Task::none()
};
Command::none()
}
Message::FontLoaded(result) => {
if let Err(error) = result {
error!("Couldn't load font: {error:?}");
}
Task::none()
Command::none()
}
Message::ADBSatisfied(result) => {
self.adb_satisfied = result;
@ -391,11 +343,11 @@ impl UadGui {
self.adb_satisfied,
)))
}
Message::Nothing => Task::none(),
Message::Nothing => Command::none(),
}
}
fn view(&self) -> Element<'_, Message, Theme> {
fn view(&self) -> Element<Self::Message, Self::Theme, Renderer> {
let navigation_container = nav_menu(
&self.devices_list,
self.selected_device.clone(),
@ -421,55 +373,33 @@ impl UadGui {
column![navigation_container, main_container]
.width(Length::Fill)
.align_x(Alignment::Center)
.align_items(Alignment::Center)
.into()
}
fn theme(&self) -> Theme {
string_to_theme(&self.settings_view.general.theme)
}
}
impl UadGui {
pub fn start() -> iced::Result {
#[cfg(feature = "img")]
let logo: &[u8] = match *OS_COLOR_SCHEME {
// remember to keep `Unspecified` in sync with `src/theme`
dark_light::Mode::Dark | dark_light::Mode::Unspecified => {
include_bytes!("../../../resources/assets/logo-dark.png")
}
dark_light::Mode::Light => {
include_bytes!("../../../resources/assets/logo-light.png")
}
let logo: &[u8] = match dark_light::detect() {
dark_light::Mode::Dark => include_bytes!("../../resources/assets/logo-dark.png"),
dark_light::Mode::Light => include_bytes!("../../resources/assets/logo-light.png"),
dark_light::Mode::Default => include_bytes!("../../resources/assets/logo-light.png"),
};
iced::application(UadGui::new, UadGui::update, UadGui::view)
.title(UadGui::title)
.theme(UadGui::theme)
.subscription(UadGui::subscription)
.settings(Settings {
id: Some(String::from(NAME)),
default_text_size: iced::Pixels(16.0),
// HACK: avoid glyph clipping on some systems. Details:
// https://github.com/Universal-Debloater-Alliance/universal-android-debloater-next-generation/pull/1337
#[cfg(target_os = "linux")]
default_font: iced::Font {
family: iced::font::Family::Name("Adwaita Sans"),
..Default::default()
},
..Settings::default()
})
.window(Window {
Self::run(Settings {
id: Some(String::from(NAME)),
window: Window {
size: iced::Size {
width: 950.0,
height: 700.0,
},
resizable: true,
decorations: true,
#[cfg(feature = "img")]
icon: icon::from_file_data(logo, Some(ImageFormat::Png)).ok(),
..iced::window::Settings::default()
})
.run()
},
default_text_size: iced::Pixels(16.0),
..Settings::default()
})
}
}

575
src/gui/style.rs Normal file
View file

@ -0,0 +1,575 @@
use crate::core::theme::Theme;
use iced::overlay::menu;
use iced::widget::{
button, checkbox, container, pick_list, radio, rule, scrollable, text, text_input,
};
use iced::{application, Background, Border, Color, Shadow};
#[derive(Default, Debug, Clone, Copy)]
pub enum Application {
#[default]
Default,
}
impl application::StyleSheet for Theme {
type Style = Application;
fn appearance(&self, _style: &Self::Style) -> application::Appearance {
application::Appearance {
background_color: self.palette().base.background,
text_color: self.palette().bright.surface,
}
}
}
#[derive(Default, Debug, Clone, Copy)]
pub enum Container {
#[default]
Invisible,
Frame,
BorderedFrame,
Tooltip,
Background,
}
impl container::StyleSheet for Theme {
type Style = Container;
fn appearance(&self, style: &Self::Style) -> container::Appearance {
match style {
Container::Invisible => container::Appearance::default(),
Container::Frame => container::Appearance {
background: Some(Background::Color(self.palette().base.foreground)),
text_color: Some(self.palette().bright.surface),
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
..container::Appearance::default()
},
Container::BorderedFrame => container::Appearance {
background: Some(Background::Color(self.palette().base.foreground)),
text_color: Some(self.palette().bright.surface),
border: Border {
color: self.palette().normal.error,
width: 1.0,
radius: 5.0.into(),
},
shadow: Shadow::default(),
},
Container::Tooltip => container::Appearance {
background: Some(Background::Color(self.palette().base.foreground)),
text_color: Some(self.palette().bright.surface),
border: Border {
color: self.palette().normal.primary,
width: 1.0,
radius: 8.0.into(),
},
shadow: Shadow::default(),
},
Container::Background => container::Appearance {
background: Some(Background::Color(self.palette().base.background)),
text_color: Some(self.palette().bright.surface),
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
..container::Appearance::default()
},
}
}
}
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Button {
#[default]
Primary,
Unavailable,
SelfUpdate,
UninstallPackage,
RestorePackage,
NormalPackage,
SelectedPackage,
Hidden,
}
impl button::StyleSheet for Theme {
type Style = Button;
fn active(&self, style: &Self::Style) -> button::Appearance {
let p = self.palette();
let appearance = button::Appearance {
border: Border {
color: self.palette().normal.primary,
width: 1.0,
radius: 2.0.into(),
},
..button::Appearance::default()
};
let active_appearance = |bg: Option<Color>, mc| button::Appearance {
background: Some(Background::Color(bg.unwrap_or(p.base.foreground))),
border: Border {
color: Color { a: 0.5, ..mc },
width: 1.0,
radius: 2.0.into(),
},
text_color: mc,
..appearance
};
match style {
Button::Primary | Button::SelfUpdate => active_appearance(None, p.bright.primary),
Button::RestorePackage => active_appearance(None, p.bright.secondary),
Button::NormalPackage => button::Appearance {
background: Some(Background::Color(p.base.foreground)),
text_color: p.bright.surface,
border: Border {
color: p.base.background,
width: 0.0,
radius: 5.0.into(),
},
..appearance
},
Button::SelectedPackage => button::Appearance {
background: Some(Background::Color(Color {
a: 0.25,
..p.normal.primary
})),
text_color: p.bright.primary,
border: Border {
color: p.normal.primary,
width: 0.0,
radius: 5.0.into(),
},
..appearance
},
Button::Unavailable | Button::UninstallPackage => {
active_appearance(None, p.bright.error)
}
Button::Hidden => button::Appearance {
background: Some(Background::Color(Color::TRANSPARENT)),
text_color: Color::TRANSPARENT,
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
..appearance
},
}
}
fn hovered(&self, style: &Self::Style) -> button::Appearance {
let active = self.active(style);
let p = self.palette();
let hover_appearance = |bg, tc: Option<Color>| button::Appearance {
background: Some(Background::Color(Color { a: 0.25, ..bg })),
text_color: tc.unwrap_or(bg),
..active
};
match style {
Button::Primary | Button::SelfUpdate => hover_appearance(p.bright.primary, None),
Button::NormalPackage => hover_appearance(p.normal.primary, Some(p.bright.surface)),
Button::SelectedPackage => hover_appearance(p.normal.primary, None),
Button::RestorePackage => hover_appearance(p.bright.secondary, None),
Button::Unavailable | Button::UninstallPackage => {
hover_appearance(p.bright.error, None)
}
Button::Hidden => hover_appearance(Color::TRANSPARENT, None),
}
}
fn pressed(&self, style: &Self::Style) -> button::Appearance {
self.active(style)
}
fn disabled(&self, style: &Self::Style) -> button::Appearance {
let active = self.active(style);
let p = self.palette();
let disabled_appearance = |bg, tc: Option<Color>| button::Appearance {
background: Some(Background::Color(Color { a: 0.05, ..bg })),
text_color: Color {
a: 0.50,
..tc.unwrap_or(bg)
},
..active
};
match style {
Button::RestorePackage => disabled_appearance(p.normal.primary, Some(p.bright.primary)),
Button::UninstallPackage => disabled_appearance(p.bright.error, None),
Button::Primary => disabled_appearance(p.bright.primary, Some(p.bright.primary)),
_ => active,
}
}
}
#[derive(Default, Debug, Clone, Copy)]
pub enum Scrollable {
#[default]
Description,
Packages,
}
impl scrollable::StyleSheet for Theme {
type Style = Scrollable;
fn active(&self, style: &Self::Style) -> scrollable::Appearance {
let from_appearance = |c: Color| scrollable::Appearance {
container: container::Appearance::default(),
gap: Some(Background::Color(Color::TRANSPARENT)),
scrollbar: scrollable::Scrollbar {
background: Some(Background::Color(Color::TRANSPARENT)),
border: Border {
color: Color::TRANSPARENT,
width: 0.0,
radius: 5.0.into(),
},
scroller: scrollable::Scroller {
color: c,
border: Border {
color: Color::TRANSPARENT,
width: 1.0,
radius: 5.0.into(),
},
},
},
};
match style {
Scrollable::Description => from_appearance(self.palette().normal.surface),
Scrollable::Packages => from_appearance(self.palette().base.foreground),
}
}
fn hovered(&self, style: &Self::Style, _mouse_over_scrollbar: bool) -> scrollable::Appearance {
scrollable::Appearance {
scrollbar: self.active(style).scrollbar,
..self.active(style)
}
}
fn dragging(&self, style: &Self::Style) -> scrollable::Appearance {
let hovered = self.hovered(style, true);
scrollable::Appearance {
scrollbar: hovered.scrollbar,
..hovered
}
}
}
#[derive(Default, Debug, Clone, Copy)]
pub enum CheckBox {
#[default]
PackageEnabled,
PackageDisabled,
SettingsEnabled,
SettingsDisabled,
}
impl checkbox::StyleSheet for Theme {
type Style = CheckBox;
fn active(&self, style: &Self::Style, _is_checked: bool) -> checkbox::Appearance {
match style {
CheckBox::PackageEnabled => checkbox::Appearance {
background: Background::Color(self.palette().base.background),
icon_color: self.palette().bright.primary,
border: Border {
color: self.palette().base.background,
width: 1.0,
radius: 5.0.into(),
},
text_color: Some(self.palette().bright.surface),
},
CheckBox::PackageDisabled => checkbox::Appearance {
background: Background::Color(Color {
a: 0.55,
..self.palette().base.background
}),
icon_color: self.palette().bright.primary,
border: Border {
color: self.palette().normal.primary,
width: 1.0,
radius: 5.0.into(),
},
text_color: Some(self.palette().normal.primary),
},
CheckBox::SettingsEnabled => checkbox::Appearance {
background: Background::Color(self.palette().base.background),
icon_color: self.palette().bright.primary,
border: Border {
color: self.palette().bright.primary,
width: 1.0,
radius: 5.0.into(),
},
text_color: Some(self.palette().bright.surface),
},
CheckBox::SettingsDisabled => checkbox::Appearance {
background: Background::Color(self.palette().base.foreground),
icon_color: self.palette().bright.primary,
border: Border {
color: self.palette().normal.primary,
width: 1.0,
radius: 5.0.into(),
},
text_color: Some(self.palette().bright.surface),
},
}
}
fn hovered(&self, style: &Self::Style, is_checked: bool) -> checkbox::Appearance {
let from_appearance = || checkbox::Appearance {
background: Background::Color(self.palette().base.foreground),
icon_color: self.palette().bright.primary,
border: Border {
color: self.palette().bright.primary,
width: 2.0,
radius: 5.0.into(),
},
text_color: Some(self.palette().bright.surface),
};
match style {
CheckBox::PackageEnabled | CheckBox::SettingsEnabled => from_appearance(),
CheckBox::PackageDisabled | CheckBox::SettingsDisabled => {
self.active(style, is_checked)
}
}
}
}
#[derive(Default, Debug, Clone, Copy)]
pub enum TextInput {
#[default]
Default,
}
impl text_input::StyleSheet for Theme {
type Style = TextInput;
fn active(&self, _style: &Self::Style) -> text_input::Appearance {
text_input::Appearance {
background: Background::Color(self.palette().base.foreground),
border: Border {
color: self.palette().base.foreground,
width: 0.0,
radius: 5.0.into(),
},
icon_color: Color {
a: 0.5,
..self.palette().normal.primary
},
}
}
fn focused(&self, _style: &Self::Style) -> text_input::Appearance {
text_input::Appearance {
background: Background::Color(self.palette().base.foreground),
border: Border {
color: Color {
a: 0.5,
..self.palette().normal.primary
},
width: 1.0,
radius: 2.0.into(),
},
icon_color: Color {
a: 0.5,
..self.palette().normal.primary
},
}
}
fn disabled_color(
&self,
_: &<Self as iced::widget::text_input::StyleSheet>::Style,
) -> iced::Color {
todo!()
}
fn disabled(&self, _style: &Self::Style) -> text_input::Appearance {
text_input::Appearance {
background: Background::Color(self.palette().base.background),
border: Border {
color: Color {
a: 0.5,
..self.palette().base.foreground
},
width: 1.0,
radius: 2.0.into(),
},
icon_color: Color {
a: 0.5,
..self.palette().base.foreground
},
}
}
fn placeholder_color(&self, _style: &Self::Style) -> Color {
self.palette().normal.surface
}
fn value_color(&self, _style: &Self::Style) -> Color {
self.palette().bright.primary
}
fn selection_color(&self, _style: &Self::Style) -> Color {
self.palette().normal.primary
}
/// Produces the style of an hovered text input.
fn hovered(&self, style: &Self::Style) -> text_input::Appearance {
self.focused(style)
}
}
#[derive(Default, Debug, Clone, Copy)]
pub enum PickList {
#[default]
Default,
}
impl menu::StyleSheet for Theme {
type Style = ();
fn appearance(&self, _style: &Self::Style) -> menu::Appearance {
let p = self.palette();
menu::Appearance {
text_color: p.bright.surface,
background: p.base.background.into(),
border: Border {
color: p.base.background,
width: 1.0,
radius: 2.0.into(),
},
selected_text_color: p.bright.surface,
selected_background: p.normal.primary.into(),
}
}
}
impl pick_list::StyleSheet for Theme {
type Style = ();
fn active(&self, _style: &()) -> pick_list::Appearance {
pick_list::Appearance {
text_color: self.palette().bright.surface,
background: self.palette().base.background.into(),
border: Border {
color: Color {
a: 0.5,
..self.palette().normal.primary
},
width: 1.0,
radius: 2.0.into(),
},
handle_color: self.palette().bright.surface,
placeholder_color: self.palette().bright.surface,
}
}
fn hovered(&self, style: &()) -> pick_list::Appearance {
let active = self.active(style);
pick_list::Appearance {
border: Border {
color: self.palette().normal.primary,
width: 1.0,
radius: 2.0.into(),
},
..active
}
}
}
#[derive(Default, Clone, Copy)]
pub enum Text {
#[default]
Default,
Ok,
Danger,
Commentary,
Color(Color),
}
impl From<Color> for Text {
fn from(color: Color) -> Self {
Self::Color(color)
}
}
impl text::StyleSheet for Theme {
type Style = Text;
fn appearance(&self, style: Self::Style) -> text::Appearance {
match style {
Text::Default => text::Appearance::default(),
Text::Ok => text::Appearance {
color: Some(self.palette().bright.secondary),
},
Text::Danger => text::Appearance {
color: Some(self.palette().bright.error),
},
Text::Commentary => text::Appearance {
color: Some(self.palette().normal.surface),
},
Text::Color(c) => text::Appearance { color: Some(c) },
}
}
}
impl radio::StyleSheet for Theme {
type Style = ();
fn active(&self, _style: &Self::Style, _is_selected: bool) -> radio::Appearance {
radio::Appearance {
background: Color::TRANSPARENT.into(),
dot_color: self.palette().bright.primary,
border_width: 1.0,
border_color: self.palette().bright.primary,
text_color: None,
}
}
fn hovered(&self, style: &Self::Style, _is_selected: bool) -> radio::Appearance {
let active = self.active(style, true);
radio::Appearance {
dot_color: self.palette().bright.primary,
border_color: self.palette().bright.primary,
border_width: 2.0,
..active
}
}
}
#[derive(Default, Clone, Copy)]
pub enum Rule {
#[default]
Default,
}
impl rule::StyleSheet for Theme {
type Style = Rule;
fn appearance(&self, style: &Self::Style) -> rule::Appearance {
match style {
Rule::Default => rule::Appearance {
color: self.palette().bright.surface,
width: 2,
radius: 2.0.into(),
fill_mode: rule::FillMode::Full,
},
}
}
}

130
src/gui/views/about.rs Normal file
View file

@ -0,0 +1,130 @@
use crate::core::helpers::button_primary;
use crate::core::theme::Theme;
use crate::core::uad_lists::LIST_FNAME;
use crate::core::utils::{last_modified_date, open_url, NAME};
use crate::gui::{style, UpdateState};
use crate::CACHE_DIR;
use iced::widget::{column, container, row, text, Space};
use iced::{Alignment, Element, Length, Renderer};
use std::path::PathBuf;
#[cfg(feature = "self-update")]
use crate::core::update::SelfUpdateStatus;
#[derive(Default, Debug, Clone)]
pub struct About {}
#[derive(Debug, Clone)]
pub enum Message {
UrlPressed(PathBuf),
UpdateUadLists,
DoSelfUpdate,
}
impl About {
pub fn update(&mut self, msg: Message) {
if let Message::UrlPressed(url) = msg {
open_url(url);
}
// other events are handled by UadGui update()
}
pub fn view(&self, update_state: &UpdateState) -> Element<Message, Theme, Renderer> {
let about_text = text(format!("Universal Android Debloater Next Generation ({NAME}) is a free and open-source community project \naiming at simplifying the removal of pre-installed apps on any Android device."));
let descr_container = container(about_text)
.width(Length::Fill)
.padding(25)
.style(style::Container::Frame);
let date = last_modified_date(CACHE_DIR.join(LIST_FNAME));
let uad_list_text =
text(format!("{NAME} package list: v{}", date.format("%Y%m%d"))).width(250);
let last_update_text = text(update_state.uad_list.to_string());
let uad_lists_btn = button_primary("Update").on_press(Message::UpdateUadLists);
#[cfg(feature = "self-update")]
let self_update_btn = button_primary("Update").on_press(Message::DoSelfUpdate);
#[cfg(feature = "self-update")]
let uad_version_text =
text(format!("{NAME} version: v{}", env!("CARGO_PKG_VERSION"))).width(250);
#[cfg(feature = "self-update")]
#[rustfmt::skip]
let self_update_text = update_state.self_update.latest_release.as_ref().map_or_else(||
if update_state.self_update.status == SelfUpdateStatus::Done {
"(No update available)".to_string()
} else {
update_state.self_update.status.to_string()
}, |r| if update_state.self_update.status == SelfUpdateStatus::Updating {
update_state.self_update.status.to_string()
} else {
format!("({} available)", r.tag_name)
});
#[cfg(feature = "self-update")]
let last_self_update_text = text(self_update_text).style(style::Text::Default);
#[cfg(feature = "self-update")]
let self_update_row = row![uad_version_text, self_update_btn, last_self_update_text,]
.align_items(Alignment::Center)
.spacing(10)
.width(550);
let uad_list_row = row![uad_list_text, uad_lists_btn, last_update_text,]
.align_items(Alignment::Center)
.spacing(10)
.width(550);
#[cfg(feature = "self-update")]
let update_column = column![uad_list_row, self_update_row]
.align_items(Alignment::Center)
.spacing(10);
#[cfg(not(feature = "self-update"))]
let update_column = column![uad_list_row]
.align_items(Alignment::Center)
.spacing(10);
let update_container = container(update_column)
.width(Length::Fill)
.center_x()
.padding(10)
.style(style::Container::Frame);
let website_btn =
button_primary("GitHub page").on_press(Message::UrlPressed(PathBuf::from(
"https://github.com/Universal-Debloater-Alliance/universal-android-debloater",
)));
let issue_btn = button_primary("Have an issue?")
.on_press(Message::UrlPressed(PathBuf::from(
"https://github.com/Universal-Debloater-Alliance/universal-android-debloater/issues",
)));
let log_btn = button_primary("Locate the logfiles")
.on_press(Message::UrlPressed(CACHE_DIR.to_path_buf()));
let wiki_btn = button_primary("Wiki").on_press(Message::UrlPressed(PathBuf::from(
"https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki",
)));
let row = row![website_btn, wiki_btn, issue_btn, log_btn,].spacing(20);
let content = column![
Space::new(Length::Fill, Length::Shrink),
descr_container,
update_container,
row,
]
.width(Length::Fill)
.spacing(20)
.align_items(Alignment::Center);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.padding(10)
.into()
}
}

1021
src/gui/views/list.rs Normal file

File diff suppressed because it is too large Load diff

579
src/gui/views/settings.rs Normal file
View file

@ -0,0 +1,579 @@
use crate::core::helpers::button_primary;
use crate::core::sync::AdbError;
use crate::core::config::{BackupSettings, Config, DeviceSettings, GeneralSettings};
use crate::core::save::{
backup_phone, list_available_backup_user, list_available_backups, restore_backup,
};
use crate::core::sync::{get_android_sdk, perform_adb_commands, CommandType, Phone, User};
use crate::core::theme::Theme;
use crate::core::utils::{
export_packages, open_folder, open_url, string_to_theme, DisplayablePath,
UNINSTALLED_PACKAGES_FILE_NAME,
};
use crate::gui::style;
use crate::gui::views::list::{List as AppsView, PackageInfo};
use crate::gui::widgets::modal::Modal;
use crate::gui::widgets::navigation_menu::ICONS;
use crate::gui::widgets::package_row::PackageRow;
use iced::widget::{
button, checkbox, column, container, pick_list, radio, row, scrollable, text, Space, Text,
};
use iced::{alignment, Alignment, Command, Element, Length, Renderer};
use std::path::PathBuf;
use crate::core::utils::{Error, NAME};
#[derive(Debug, Clone)]
pub enum PopUpModal {
ExportUninstalled,
}
#[derive(Debug, Clone)]
pub struct Settings {
pub general: GeneralSettings,
pub device: DeviceSettings,
is_loading: bool,
modal: Option<PopUpModal>,
}
impl Default for Settings {
fn default() -> Self {
Self {
general: Config::load_configuration_file().general,
device: DeviceSettings::default(),
is_loading: false,
modal: None,
}
}
}
#[derive(Debug, Clone)]
pub enum Message {
LoadDeviceSettings,
ExpertMode(bool),
DisableMode(bool),
MultiUserMode(bool),
ApplyTheme(Theme),
UrlPressed(PathBuf),
BackupSelected(DisplayablePath),
BackupDevice,
RestoreDevice,
RestoringDevice(Result<CommandType, AdbError>),
DeviceBackedUp(Result<bool, String>),
ChooseBackUpFolder,
FolderChosen(Result<PathBuf, Error>),
ExportPackages,
PackagesExported(Result<bool, String>),
ModalHide,
}
impl Settings {
// TODO: refactor later
#[allow(clippy::too_many_lines)]
pub fn update(
&mut self,
phone: &Phone,
packages: &[Vec<PackageRow>],
nb_running_async_adb_commands: &mut u32,
msg: Message,
selected_user: Option<User>,
) -> Command<Message> {
match msg {
Message::ModalHide => {
self.modal = None;
Command::none()
}
Message::ExpertMode(toggled) => {
self.general.expert_mode = toggled;
debug!("Config change: {:?}", self);
Config::save_changes(self, &phone.adb_id);
Command::none()
}
Message::DisableMode(toggled) => {
if phone.android_sdk >= 23 {
self.device.disable_mode = toggled;
debug!("Config change: {:?}", self);
Config::save_changes(self, &phone.adb_id);
}
Command::none()
}
Message::MultiUserMode(toggled) => {
self.device.multi_user_mode = toggled;
debug!("Config change: {:?}", self);
Config::save_changes(self, &phone.adb_id);
Command::none()
}
Message::ApplyTheme(theme) => {
self.general.theme = theme.to_string();
debug!("Config change: {:?}", self);
Config::save_changes(self, &phone.adb_id);
Command::none()
}
Message::UrlPressed(url) => {
open_url(url);
Command::none()
}
Message::LoadDeviceSettings => {
let backups =
list_available_backups(&self.general.backup_folder.join(&phone.adb_id));
let backup = BackupSettings {
backups: backups.clone(),
selected: backups.first().cloned(),
users: phone.user_list.clone(),
selected_user: phone.user_list.first().copied(),
backup_state: String::default(),
};
match Config::load_configuration_file()
.devices
.iter()
.find(|d| d.device_id == phone.adb_id)
{
Some(device) => {
self.device.clone_from(device);
self.device.backup = backup;
}
None => {
self.device = DeviceSettings {
device_id: phone.adb_id.clone(),
multi_user_mode: phone.android_sdk > 21,
disable_mode: false,
backup,
}
}
};
Command::none()
}
Message::BackupSelected(d_path) => {
self.device.backup.selected = Some(d_path.clone());
self.device.backup.users = list_available_backup_user(d_path);
Command::none()
}
Message::BackupDevice => Command::perform(
backup_phone(
phone.user_list.clone(),
self.device.device_id.clone(),
packages.to_vec(),
),
Message::DeviceBackedUp,
),
Message::DeviceBackedUp(is_backed_up) => {
match is_backed_up {
Ok(_) => {
info!("[BACKUP] Backup successfully created");
self.device.backup.backups = list_available_backups(
&self.general.backup_folder.join(phone.adb_id.clone()),
);
self.device.backup.selected = self.device.backup.backups.first().cloned();
}
Err(err) => {
error!("[BACKUP FAILED] Backup creation failed: {:?}", err);
}
}
Command::none()
}
Message::RestoreDevice => match restore_backup(phone, packages, &self.device) {
Ok(r_packages) => {
let mut commands = vec![];
*nb_running_async_adb_commands = 0;
for p in &r_packages {
let p_info = PackageInfo {
i_user: 0,
index: p.index,
removal: "RESTORE".to_string(),
};
for command in p.commands.clone() {
*nb_running_async_adb_commands += 1;
commands.push(Command::perform(
perform_adb_commands(
command,
CommandType::PackageManager(p_info.clone()),
),
Message::RestoringDevice,
));
}
}
if r_packages.is_empty() {
if get_android_sdk() == 0 {
self.device.backup.backup_state = "Device is not connected".to_string();
} else {
self.device.backup.backup_state =
"Device state is already restored".to_string();
}
}
info!(
"[RESTORE] Restoring backup {}",
self.device.backup.selected.as_ref().unwrap()
);
Command::batch(commands)
}
Err(e) => {
self.device.backup.backup_state.clone_from(&e);
error!("{} - {}", self.device.backup.selected.as_ref().unwrap(), e);
Command::none()
}
},
// Trigger an action in mod.rs (Message::SettingsAction(msg))
Message::RestoringDevice(_) => Command::none(),
Message::FolderChosen(result) => {
self.is_loading = false;
if let Ok(path) = result {
self.general.backup_folder = path;
Config::save_changes(self, &phone.adb_id);
#[allow(unused_must_use)]
{
self.update(
phone,
packages,
nb_running_async_adb_commands,
Message::LoadDeviceSettings,
selected_user,
);
}
}
Command::none()
}
Message::ChooseBackUpFolder => {
if self.is_loading {
Command::none()
} else {
self.is_loading = true;
Command::perform(open_folder(), Message::FolderChosen)
}
}
Message::ExportPackages => Command::perform(
export_packages(selected_user.unwrap_or_default(), packages.to_vec()),
Message::PackagesExported,
),
Message::PackagesExported(exported) => {
match exported {
Ok(_) => self.modal = Some(PopUpModal::ExportUninstalled),
Err(err) => error!("Failed to export list of uninstalled packages: {:?}", err),
}
Command::none()
}
}
}
// TODO: refactor later
#[allow(clippy::too_many_lines)]
pub fn view(&self, phone: &Phone, apps_view: &AppsView) -> Element<Message, Theme, Renderer> {
let radio_btn_theme = Theme::ALL
.iter()
.fold(row![].spacing(10), |column, option| {
column.push(
radio(
format!("{}", option.clone()),
*option,
Some(string_to_theme(&self.general.theme)),
Message::ApplyTheme,
)
.size(24),
)
});
let theme_ctn = container(radio_btn_theme)
.padding(10)
.width(Length::Fill)
.height(Length::Shrink)
.style(style::Container::Frame);
let expert_mode_checkbox = checkbox(
"Allow to uninstall packages marked as \"unsafe\" (I KNOW WHAT I AM DOING)",
self.general.expert_mode,
)
.on_toggle(Message::ExpertMode)
.style(style::CheckBox::SettingsEnabled);
let expert_mode_descr =
text("Most unsafe packages are known to bootloop the device if removed.")
.style(style::Text::Commentary);
let choose_backup_descr = text("Note: If you have previous backups, you will need to transfer them manually to newly changed backup folder to be able to use Restore functionality")
.style(style::Text::Commentary);
let choose_backup_btn = button(Text::new("\u{E930}").font(ICONS))
.padding([5, 10])
.on_press(Message::ChooseBackUpFolder)
.style(style::Button::Primary);
let choose_backup_row = row![
choose_backup_btn,
"Choose backup folder",
Space::new(Length::Fill, Length::Shrink),
"Current folder: ",
Text::new(self.general.backup_folder.to_string_lossy())
]
.spacing(10)
.align_items(Alignment::Center);
let general_ctn = container(
column![
expert_mode_checkbox,
expert_mode_descr,
choose_backup_row,
choose_backup_descr,
]
.spacing(10),
)
.padding(10)
.width(Length::Fill)
.height(Length::Shrink)
.style(style::Container::Frame);
let warning_ctn = container(
row![
text("The following settings only affect the currently selected device:")
.style(style::Text::Danger),
text(phone.model.clone()),
Space::new(Length::Fill, Length::Shrink),
text(phone.adb_id.clone()).style(style::Text::Commentary)
]
.spacing(7),
)
.padding(10)
.width(Length::Fill)
.style(style::Container::BorderedFrame);
let multi_user_mode_descr = row![
text("This will not affect the following protected work profile users: ")
.style(style::Text::Commentary),
text(
phone
.user_list
.iter()
.filter(|&u| u.protected)
.map(|u| u.id.to_string())
.collect::<Vec<String>>()
.join(", ")
)
.style(style::Text::Danger)
];
let multi_user_mode_checkbox = checkbox(
"Affect all the users of the device (not only the selected user)",
self.device.multi_user_mode,
)
.on_toggle(Message::MultiUserMode)
.style(style::CheckBox::SettingsEnabled);
let disable_checkbox_style = if phone.android_sdk >= 23 {
style::CheckBox::SettingsEnabled
} else {
style::CheckBox::SettingsDisabled
};
let disable_mode_descr =
text("In some cases, it can be better to disable a package instead of uninstalling it")
.style(style::Text::Commentary);
let unavailable_btn = button(text("Unavailable").size(14))
.on_press(Message::UrlPressed(PathBuf::from(
"https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki/FAQ#\
why-is-the-disable-mode-setting-not-available-for-my-device",
)))
.height(22)
.style(style::Button::Unavailable);
// Disabling package without root isn't really possible before Android Oreo (8.0)
// see https://github.com/Universal-Debloater-Alliance/universal-android-debloater/wiki/ADB-reference
let disable_mode_checkbox = checkbox(
"Clear and disable packages instead of uninstalling them",
self.device.disable_mode,
)
.on_toggle(Message::DisableMode)
.style(disable_checkbox_style);
let disable_setting_row = if phone.android_sdk >= 23 {
row![
disable_mode_checkbox,
Space::new(Length::Fill, Length::Shrink),
]
.width(Length::Fill)
} else {
row![
disable_mode_checkbox,
Space::new(Length::Fill, Length::Shrink),
unavailable_btn,
]
.width(Length::Fill)
};
let device_specific_ctn = container(
column![
multi_user_mode_checkbox,
multi_user_mode_descr,
disable_setting_row,
disable_mode_descr,
]
.spacing(10),
)
.padding(10)
.width(Length::Fill)
.height(Length::Shrink)
.style(style::Container::Frame);
let backup_pick_list = pick_list(
self.device.backup.backups.clone(),
self.device.backup.selected.clone(),
Message::BackupSelected,
)
.padding(6);
let backup_btn =
button_primary(text("Backup").horizontal_alignment(alignment::Horizontal::Center))
.on_press(Message::BackupDevice)
.width(77);
let restore_btn = |enabled| {
if enabled {
button(text("Restore").horizontal_alignment(alignment::Horizontal::Center))
.padding([5, 10])
.on_press(Message::RestoreDevice)
.width(77)
} else {
button(
text("No backup")
.horizontal_alignment(alignment::Horizontal::Center)
.vertical_alignment(alignment::Vertical::Center),
)
.padding([5, 10])
.width(77)
}
};
let locate_backup_btn = if self.device.backup.backups.is_empty() {
button_primary("Open backup directory")
} else {
button_primary("Open backup directory").on_press(Message::UrlPressed(
self.general.backup_folder.join(phone.adb_id.clone()),
))
};
let export_btn = button_primary("Export").on_press(Message::ExportPackages);
let backup_row = row![
backup_btn,
"Backup the current state of the phone",
Space::new(Length::Fill, Length::Shrink),
locate_backup_btn,
]
.spacing(10)
.align_items(Alignment::Center);
let restore_row = if !self.device.backup.backups.is_empty() {
row![
restore_btn(true),
"Restore the state of the device",
Space::new(Length::Fill, Length::Shrink),
text(self.device.backup.backup_state.clone()).style(style::Text::Danger),
backup_pick_list,
]
.spacing(10)
.align_items(Alignment::Center)
} else {
row![]
};
let no_device_ctn = || {
container(text("No device detected").style(style::Text::Danger))
.padding(10)
.width(Length::Fill)
.style(style::Container::BorderedFrame)
};
let content = if phone.adb_id.is_empty() {
column![
text("Theme").size(26),
theme_ctn,
text("General").size(26),
general_ctn,
text("Current device").size(26),
no_device_ctn(),
text("Backup / Restore").size(26),
no_device_ctn(),
]
.width(Length::Fill)
.spacing(20)
} else {
let export_row = row![
export_btn,
"Export uninstalled packages with their description",
Space::new(Length::Fill, Length::Shrink),
text(format!(
"Selected: user {}",
apps_view.selected_user.unwrap_or_default().id
)),
]
.spacing(10)
.align_items(Alignment::Center);
let backup_restore_ctn =
container(column![backup_row, restore_row, export_row].spacing(10))
.padding(10)
.width(Length::Fill)
.height(Length::Shrink)
.style(style::Container::Frame);
column![
text("Theme").size(26),
theme_ctn,
text("General").size(26),
general_ctn,
text("Current device").size(26),
warning_ctn,
device_specific_ctn,
text("Backup / Restore").size(26),
backup_restore_ctn,
]
.width(Length::Fill)
.spacing(20)
};
if let Some(PopUpModal::ExportUninstalled) = self.modal {
let title = container(row![text("Success").size(24)].align_items(Alignment::Center))
.width(Length::Fill)
.style(style::Container::Frame)
.padding([10, 0, 10, 0])
.center_y()
.center_x();
let text_box = row![
text(format!("Exported uninstalled packages into file.\nFile is exported in same directory where {NAME} is located.")).width(Length::Fill),
].padding(20);
let file_row = row![text(format!(
"{}_{}.txt",
UNINSTALLED_PACKAGES_FILE_NAME,
chrono::Local::now().format("%Y%m%d")
))
.style(style::Text::Commentary)]
.padding(20);
let modal_btn_row = row![
Space::new(Length::Fill, Length::Shrink),
button(text("Close").width(Length::Shrink))
.width(Length::Shrink)
.on_press(Message::ModalHide),
Space::new(Length::Fill, Length::Shrink),
];
let ctn = container(column![title, text_box, file_row, modal_btn_row])
.height(Length::Shrink)
.width(500)
.padding(10)
.style(style::Container::Frame);
return Modal::new(content.padding(10), ctn)
.on_blur(Message::ModalHide)
.into();
}
container(scrollable(content))
.padding(10)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
}

View file

@ -1,6 +1,3 @@
pub mod modal;
pub mod navigation_menu;
pub mod package_row;
mod text;
pub use text::text;

View file

@ -1,7 +1,7 @@
use iced::advanced::widget::{self, Tree, Widget};
use iced::advanced::{Clipboard, Layout, Shell, layout, overlay, renderer};
use iced::advanced::{layout, overlay, renderer, Clipboard, Layout, Shell};
use iced::mouse::{self, Cursor};
use iced::{Alignment, Color, Element, Event, Length, Point, Rectangle, Size, Vector, advanced};
use iced::{advanced, event, Alignment, Color, Element, Event, Length, Point, Rectangle, Size};
/// A widget that centers a modal element over some base element
pub struct Modal<'a, Message, Theme, Renderer> {
@ -25,7 +25,6 @@ impl<'a, Message, Theme, Renderer> Modal<'a, Message, Theme, Renderer> {
/// Sets the message that will be produces when the background
/// of the [`Modal`] is pressed
#[must_use]
pub fn on_blur(self, on_blur: Message) -> Self {
Self {
on_blur: Some(on_blur),
@ -34,8 +33,8 @@ impl<'a, Message, Theme, Renderer> Modal<'a, Message, Theme, Renderer> {
}
}
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for Modal<'_, Message, Theme, Renderer>
impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for Modal<'a, Message, Theme, Renderer>
where
Renderer: advanced::Renderer,
Message: Clone,
@ -53,28 +52,28 @@ where
}
fn layout(
&mut self,
&self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.base
.as_widget_mut()
.as_widget()
.layout(&mut tree.children[0], renderer, limits)
}
fn update(
fn on_event(
&mut self,
state: &mut Tree,
event: &Event,
event: Event,
layout: Layout<'_>,
cursor_position: Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
self.base.as_widget_mut().update(
) -> event::Status {
self.base.as_widget_mut().on_event(
&mut state.children[0],
event,
layout,
@ -83,7 +82,7 @@ where
clipboard,
shell,
viewport,
);
)
}
fn draw(
@ -110,10 +109,9 @@ where
fn overlay<'b>(
&'b mut self,
state: &'b mut Tree,
layout: Layout<'b>,
layout: Layout<'_>,
_renderer: &Renderer,
viewport: &Rectangle,
_translation: Vector,
_translation: iced::Vector,
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
Some(overlay::Element::new(Box::new(Overlay {
position: layout.position(),
@ -121,7 +119,6 @@ where
tree: &mut state.children[1],
size: layout.bounds().size(),
on_blur: self.on_blur.clone(),
viewport: *viewport,
})))
}
@ -143,14 +140,14 @@ where
}
fn operate(
&mut self,
&self,
state: &mut Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn widget::Operation,
operation: &mut dyn widget::Operation<Message>,
) {
self.base
.as_widget_mut()
.as_widget()
.operate(&mut state.children[0], layout, renderer, operation);
}
}
@ -161,11 +158,10 @@ struct Overlay<'a, 'b, Message, Theme, Renderer> {
tree: &'b mut Tree,
size: Size,
on_blur: Option<Message>,
viewport: Rectangle,
}
impl<Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer>
for Overlay<'_, '_, Message, Theme, Renderer>
impl<'a, 'b, Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer>
for Overlay<'a, 'b, Message, Theme, Renderer>
where
Renderer: advanced::Renderer,
Message: Clone,
@ -177,41 +173,42 @@ where
let child = self
.content
.as_widget_mut()
.as_widget()
.layout(self.tree, renderer, &limits)
.align(Alignment::Center, Alignment::Center, limits.max());
layout::Node::with_children(self.size, vec![child]).move_to(self.position)
}
fn update(
fn on_event(
&mut self,
event: &Event,
event: Event,
layout: Layout<'_>,
cursor: Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
) {
if let Some(message) = self.on_blur.as_ref()
&& matches!(
) -> event::Status {
if let Some(message) = self.on_blur.as_ref() {
if matches!(
event,
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
)
&& let Some(cursor_position) = cursor.position()
{
let content_bounds = layout
.children()
.next()
.expect("Layout must have at least 1 child")
.bounds();
if !content_bounds.contains(cursor_position) {
shell.publish(message.clone());
return;
) {
if let Some(cursor_position) = cursor.position() {
let content_bounds = layout
.children()
.next()
.expect("Layout must have at least 1 child")
.bounds();
if !content_bounds.contains(cursor_position) {
shell.publish(message.clone());
return event::Status::Captured;
}
}
}
}
self.content.as_widget_mut().update(
self.content.as_widget_mut().on_event(
self.tree,
event,
layout.children().next().unwrap(),
@ -219,8 +216,8 @@ where
renderer,
clipboard,
shell,
&self.viewport,
);
&layout.bounds(),
)
}
fn draw(
@ -257,9 +254,9 @@ where
&mut self,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn widget::Operation,
operation: &mut dyn widget::Operation<Message>,
) {
self.content.as_widget_mut().operate(
self.content.as_widget().operate(
self.tree,
layout.children().next().unwrap(),
renderer,
@ -271,13 +268,14 @@ where
&self,
layout: Layout<'_>,
cursor: Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
self.tree,
layout.children().next().unwrap(),
cursor,
&self.viewport,
viewport,
renderer,
)
}

View file

@ -1,22 +1,19 @@
use crate::helpers::button_primary;
use crate::theme::Theme;
pub use crate::views::about::Message as AboutMessage;
pub use crate::views::list::{List as AppsView, LoadingState as ListLoadingState};
use crate::{gui::Message, style, widgets::text};
use iced::widget::{Space, button, container, pick_list, row, tooltip};
use iced::{Alignment, Element, Font, Length, Renderer, alignment, font};
pub use uad_core::sync::Phone;
use uad_core::update::{SelfUpdateState, SelfUpdateStatus};
use crate::core::helpers::button_primary;
pub use crate::core::sync::Phone;
use crate::core::theme::Theme;
use crate::core::update::{SelfUpdateState, SelfUpdateStatus};
pub use crate::gui::views::about::Message as AboutMessage;
pub use crate::gui::views::list::{List as AppsView, LoadingState as ListLoadingState};
use crate::gui::{style, Message};
use iced::widget::{button, container, pick_list, row, text, tooltip, Space, Text};
use iced::{alignment, font, Alignment, Element, Font, Length, Renderer};
/// resources/assets/icons.ttf, loaded in [`crate::gui::UadGui`]
pub const ICONS: Font = Font {
family: font::Family::Name("icomoon"),
..Font::DEFAULT
};
#[allow(
clippy::too_many_lines,
reason = "Navigation layout composes many widgets inline"
)]
pub fn nav_menu<'a>(
device_list: &'a [Phone],
selected_device: Option<Phone>,
@ -24,44 +21,33 @@ pub fn nav_menu<'a>(
self_update_state: &SelfUpdateState,
) -> Element<'a, Message, Theme, Renderer> {
let apps_refresh_btn = button_primary(
text("\u{E900}")
Text::new("\u{E900}")
.font(ICONS)
.width(22)
.align_x(alignment::Horizontal::Center),
.horizontal_alignment(alignment::Horizontal::Center),
)
.on_press(Message::RefreshButtonPressed);
let apps_refresh_tooltip = tooltip(
apps_refresh_btn,
"Refresh apps (Ctrl+Shift+5)",
tooltip::Position::Bottom,
)
.style(style::Container::Tooltip)
.gap(4);
let apps_refresh_tooltip = tooltip(apps_refresh_btn, "Refresh apps", tooltip::Position::Bottom)
.style(style::Container::Tooltip)
.gap(4);
let reboot_btn = button_primary("Reboot").on_press(Message::RebootButtonPressed);
let reboot_btn = tooltip(
reboot_btn,
"Reboot device (Ctrl+Shift+R)",
tooltip::Position::Bottom,
)
.style(style::Container::Tooltip)
.gap(4);
#[allow(clippy::option_if_let_else)]
let uad_version_text = if let Some(r) = &self_update_state.latest_release {
match self_update_state.status {
SelfUpdateStatus::Failed => text(format!("Failed to update to {}", r.tag_name)),
SelfUpdateStatus::Checking => text(SelfUpdateStatus::Checking.to_string()),
SelfUpdateStatus::Done => text(format!(
SelfUpdateStatus::Failed => Text::new(format!("Failed to update to {}", r.tag_name)),
SelfUpdateStatus::Checking => Text::new(SelfUpdateStatus::Checking.to_string()),
SelfUpdateStatus::Done => Text::new(format!(
"Update available: {} -> {}",
env!("CARGO_PKG_VERSION"),
r.tag_name
)),
SelfUpdateStatus::Updating => text("Updating please wait..."),
SelfUpdateStatus::Updating => Text::new("Updating please wait..."),
}
} else {
text(format!("v{}", env!("CARGO_PKG_VERSION")))
Text::new(format!("v{}", env!("CARGO_PKG_VERSION")))
};
let update_btn = if self_update_state.latest_release.is_some() {
@ -75,28 +61,16 @@ pub fn nav_menu<'a>(
let apps_btn = button_primary("Apps").on_press(Message::AppsPress);
let apps_btn = tooltip(apps_btn, "(Ctrl+Shift+A)", tooltip::Position::Bottom)
.style(style::Container::Tooltip)
.gap(4);
let about_btn = button_primary("About").on_press(Message::AboutPressed);
let about_btn = tooltip(about_btn, "(Ctrl+Shift+I)", tooltip::Position::Bottom)
.style(style::Container::Tooltip)
.gap(4);
let settings_btn = button_primary(
text("\u{E994}")
Text::new("\u{E994}")
.font(ICONS)
.width(22)
.align_x(alignment::Horizontal::Center),
.horizontal_alignment(alignment::Horizontal::Center),
)
.on_press(Message::SettingsPressed);
let settings_btn = tooltip(settings_btn, "(Ctrl+Shift+S)", tooltip::Position::Bottom)
.style(style::Container::Tooltip)
.gap(4);
let device_list_text = match apps_view.loading_state {
ListLoadingState::FindingPhones => text("Finding connected devices..."),
_ => text("No devices/emulators found"),
@ -107,7 +81,7 @@ pub fn nav_menu<'a>(
reboot_btn,
apps_refresh_tooltip,
pick_list(device_list, Some(phone), Message::DeviceSelected,),
Space::new().width(Length::Fill).height(Length::Shrink),
Space::new(Length::Fill, Length::Shrink),
uad_version_text,
update_btn,
apps_btn,
@ -115,13 +89,13 @@ pub fn nav_menu<'a>(
settings_btn,
]
.width(Length::Fill)
.align_y(Alignment::Center)
.align_items(Alignment::Center)
.spacing(10),
None => row![
reboot_btn,
apps_refresh_tooltip,
device_list_text,
Space::new().width(Length::Fill).height(Length::Shrink),
Space::new(Length::Fill, Length::Shrink),
uad_version_text,
update_btn,
apps_btn,
@ -129,7 +103,7 @@ pub fn nav_menu<'a>(
settings_btn,
]
.width(Length::Fill)
.align_y(Alignment::Center)
.align_items(Alignment::Center)
.spacing(10),
};

View file

@ -1,21 +1,19 @@
use crate::style;
use crate::theme::Theme;
use crate::views::settings::Settings;
use crate::widgets::text;
use log::warn;
use uad_core::sync::{CorePackage, Phone};
use uad_core::uad_lists::{PackageState, Removal, UadList};
use crate::core::sync::Phone;
use crate::core::theme::Theme;
use crate::core::uad_lists::{PackageState, Removal, UadList};
use crate::gui::style;
use crate::gui::views::settings::Settings;
use iced::widget::{Space, button, checkbox, row};
use iced::{Alignment, Element, Length, Renderer, Task, alignment};
use iced::widget::{button, checkbox, row, text, Space};
use iced::{alignment, Alignment, Command, Element, Length, Renderer};
#[derive(Clone, Debug)]
pub struct PackageRow {
pub name: String,
pub description: String,
pub removal: Removal,
pub state: PackageState,
pub list: UadList,
pub description: String,
pub uad_list: UadList,
pub removal: Removal,
pub selected: bool,
pub current: bool,
}
@ -28,43 +26,34 @@ pub enum Message {
}
impl PackageRow {
#[must_use]
pub fn new(
name: &str,
description: &str,
removal: Removal,
state: PackageState,
list: UadList,
description: &str,
uad_list: UadList,
removal: Removal,
selected: bool,
current: bool,
) -> Self {
Self {
name: name.to_string(),
description: description.to_string(),
removal,
state,
list,
description: description.to_string(),
uad_list,
removal,
selected,
current,
}
}
#[allow(
clippy::unused_self,
reason = "Consistent component API; may change later"
)]
pub fn update(&mut self, _message: &Message) -> Task<Message> {
Task::none()
pub fn update(&mut self, _message: &Message) -> Command<Message> {
Command::none()
}
pub fn view(
&self,
settings: &Settings,
_phone: &Phone,
) -> Element<'_, Message, Theme, Renderer> {
pub fn view(&self, settings: &Settings, _phone: &Phone) -> Element<Message, Theme, Renderer> {
//let trash_svg = format!("{}/resources/assets/trash.svg", env!("CARGO_MANIFEST_DIR"));
//let restore_svg = format!("{}/resources/assets/rotate.svg", env!("CARGO_MANIFEST_DIR"));
let button_style: fn(&Theme, iced::widget::button::Status) -> iced::widget::button::Style;
let button_style;
let action_text;
let action_btn;
let selection_checkbox;
@ -97,26 +86,24 @@ impl PackageRow {
|| self.state != PackageState::Enabled
|| settings.general.expert_mode
{
selection_checkbox = checkbox(self.selected)
selection_checkbox = checkbox("", self.selected)
.on_toggle(Message::ToggleSelection)
.size(20)
.style(style::CheckBox::PackageEnabled);
action_btn = button(
text(action_text)
.align_x(alignment::Horizontal::Center)
.horizontal_alignment(alignment::Horizontal::Center)
.width(100),
)
.on_press(Message::ActionPressed);
} else {
selection_checkbox = checkbox(self.selected)
selection_checkbox = checkbox("", self.selected)
.on_toggle(Message::ToggleSelection)
.size(20)
.style(style::CheckBox::PackageDisabled);
action_btn = button(
text(action_text)
.align_x(alignment::Horizontal::Center)
.horizontal_alignment(alignment::Horizontal::Center)
.width(100),
);
}
@ -128,8 +115,7 @@ impl PackageRow {
text(&self.name).width(Length::FillPortion(8)),
action_btn.style(button_style)
]
.spacing(8)
.align_y(Alignment::Center)
.align_items(Alignment::Center)
)
.padding(8)
.style(if self.current {
@ -139,62 +125,9 @@ impl PackageRow {
})
.width(Length::Fill)
.on_press(Message::PackagePressed),
Space::new().width(Length::Fixed(15.0))
Space::with_width(15)
]
.align_y(Alignment::Center)
.align_items(Alignment::Center)
.into()
}
}
// Conversions between PackageRow and CorePackage
impl From<CorePackage> for PackageRow {
fn from(core: CorePackage) -> Self {
Self {
name: core.name.clone(),
description: core.description,
removal: core.removal,
state: core.state,
list: core.list,
selected: false, // Default to not selected
current: false, // Default to not current
}
}
}
impl From<&CorePackage> for PackageRow {
fn from(core: &CorePackage) -> Self {
Self {
name: core.name.clone(),
description: core.description.clone(),
removal: core.removal,
state: core.state,
list: core.list,
selected: false,
current: false,
}
}
}
impl From<&PackageRow> for CorePackage {
fn from(row: &PackageRow) -> Self {
Self {
name: row.name.clone(),
description: row.description.clone(),
removal: row.removal,
state: row.state,
list: row.list,
}
}
}
impl From<PackageRow> for CorePackage {
fn from(row: PackageRow) -> Self {
Self {
name: row.name,
description: row.description,
removal: row.removal,
state: row.state,
list: row.list,
}
}
}

View file

@ -1,39 +1,38 @@
#![windows_subsystem = "windows"]
#[macro_use]
extern crate log;
use crate::core::utils::setup_uad_dir;
use fern::{
FormatCallback,
colors::{Color, ColoredLevelConfig},
FormatCallback,
};
use log::Record;
use std::sync::LazyLock;
use std::{fmt::Arguments, fs::OpenOptions, path::PathBuf};
use uad_core::utils::setup_uad_dir;
use static_init::dynamic;
use std::path::PathBuf;
use std::{fmt::Arguments, fs::OpenOptions};
use uad_gui::gui::UadGui;
mod core;
mod gui;
static CACHE_DIR: LazyLock<PathBuf> =
LazyLock::new(|| setup_uad_dir(&dirs::cache_dir().expect("Can't detect cache dir")));
#[dynamic]
static CONFIG_DIR: PathBuf = setup_uad_dir(&dirs::config_dir().expect("Can't detect config dir"));
#[dynamic]
static CACHE_DIR: PathBuf = setup_uad_dir(&dirs::cache_dir().expect("Can't detect cache dir"));
fn main() -> iced::Result {
// Safety: This function is safe to call in a single-threaded program.
// The exact requirement is: you must ensure that there are no other threads concurrently writing or
// reading(!) the environment through functions or global variables other than the ones in this module.
unsafe {
// Force WGPU/Iced to use discrete GPU to prevent crashes on PCs with two GPUs.
// See #848 and related pull 850.
std::env::set_var("WGPU_POWER_PREF", "high");
}
setup_logger().expect("setup logging");
UadGui::start()
gui::UadGui::start()
}
/// Sets up logging to a new file in `CACHE_DIR"/uadng.log"`
/// Sets up logging to a new file in `CACHE_DIR/UAD`_{time}.log
/// Also attaches the terminal on Windows machines
/// '''
/// match `setup_logger().expect("Error` setting up logger")
/// '''
fn setup_logger() -> Result<(), fern::InitError> {
/// Attach Windows terminal, only on Windows
#[cfg(target_os = "windows")]
{
attach_windows_console();
@ -63,20 +62,20 @@ fn setup_logger() -> Result<(), fern::InitError> {
.create(true)
.append(true)
.truncate(false)
.open(CACHE_DIR.join("uadng.log"))?;
.open(CACHE_DIR.join(format!("UAD_{}.log", chrono::Local::now().format("%Y%m%d"))))?;
let file_dispatcher = fern::Dispatch::new()
.format(make_formatter(false))
.level(default_log_level)
// Rust compiler makes module names use _ instead of -
.level_for("uad_gui", log::LevelFilter::Debug)
.level_for("uad_ng", log::LevelFilter::Debug)
.chain(log_file);
let stdout_dispatcher = fern::Dispatch::new()
.format(make_formatter(true))
.level(default_log_level)
// Rust compiler makes module names use _ instead of -
.level_for("uad_gui", log::LevelFilter::Warn)
.level_for("uad_ng", log::LevelFilter::Warn)
.chain(std::io::stdout());
fern::Dispatch::new()