Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: sync & set_var #653

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ panic = "abort"
embed-resource = "2.4.2"

[lints.rust]
# "forbid" may cause conflicts with libs (static and dynamic)
unsafe_code = "deny"
# "forbid" may cause conflicts with libs (static and dynamic).
# "deny" is annoying.
unsafe_code = "warn"
deprecated_safe = "warn"

[lints.clippy]
undocumented_unsafe_blocks = "forbid"
Expand Down
34 changes: 20 additions & 14 deletions src/core/sync.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
use crate::core::uad_lists::PackageState;
use crate::core::utils::ANDROID_SERIAL;
use crate::core::utils::set_adb_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;

const PM_LIST_PACKS: &str = "pm list packages";
const PM_CLEAR_PACK: &str = "pm clear";

#[dynamic]
static RE: Regex = Regex::new(r"\n(\S+)\s+device").unwrap();
static RE: Regex = Regex::new(r"\n(\S+)\s+device").unwrap_or_else(|_| unreachable!());

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Phone {
Expand Down Expand Up @@ -140,14 +142,15 @@ pub async fn perform_adb_commands(
}
}

/// If `None`, returns an empty String, not " --user 0"
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));
let action = format!("{PM_LIST_PACKS} -s -u{}", user_flag(user_id));

adb_shell_command(true, &action)
.unwrap_or_default()
Expand All @@ -157,8 +160,8 @@ pub fn list_all_system_packages(user_id: Option<&User>) -> String {
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}"),
PackageState::Enabled => format!("{PM_LIST_PACKS} -s -e{user}"),
PackageState::Disabled => format!("{PM_LIST_PACKS} -s -d{user}"),
_ => String::default(), // You probably don't need to use this function for anything else
};

Expand Down Expand Up @@ -221,25 +224,25 @@ pub fn apply_pkg_state_commands(
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"],
19 | 20 => vec!["pm unblock", PM_CLEAR_PACK],
_ => 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"],
sdk if sdk >= 23 => vec!["pm disable-user", "am force-stop", PM_CLEAR_PACK],
_ => 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
21 | 22 => vec!["pm hide", PM_CLEAR_PACK], // Android Lollipop (5.x)
19 | 20 => vec!["pm block", PM_CLEAR_PACK], // Android KitKat (4.4/4.4W)
_ => vec!["pm block", PM_CLEAR_PACK], // Disable mode is unavailable on older devices because the specific ADB commands need root
},
_ => vec![],
},
Expand Down Expand Up @@ -292,12 +295,12 @@ pub fn get_phone_brand() -> String {
/// 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()
adb_shell_command(true, &format!("{PM_LIST_PACKS} -s --user {user_id}")).is_err()
}

pub fn get_user_list() -> Vec<User> {
#[dynamic]
static RE: Regex = Regex::new(r"\{([0-9]+)").unwrap();
static RE: Regex = Regex::new(r"\{([0-9]+)").unwrap_or_else(|_| unreachable!());
adb_shell_command(true, "pm list users")
.map(|users| {
RE.find_iter(&users)
Expand All @@ -323,7 +326,10 @@ pub async fn get_devices_list() -> Vec<Phone> {
return OperationResult::Retry(vec![]);
}
for device in RE.captures_iter(&devices) {
env::set_var(ANDROID_SERIAL, &device[1]);
#[allow(unsafe_code)]
unsafe {
set_adb_serial(&device[1])
};
device_list.push(Phone {
model: get_phone_brand(),
android_sdk: get_android_sdk(),
Expand Down
16 changes: 11 additions & 5 deletions src/core/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,13 @@ use crate::gui::widgets::package_row::PackageRow;
use chrono::offset::Utc;
use chrono::{DateTime, Local};
use csv::Writer;
use std::ffi::OsStr;
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";

Expand All @@ -24,6 +20,16 @@ pub enum Error {
DialogClosed,
}

#[allow(unsafe_code)]
#[allow(
clippy::semicolon_if_nothing_returned,
reason = "fn must return whatever `set_var` returns"
)]
pub unsafe fn set_adb_serial<D: AsRef<OsStr>>(device_serial: D) {
// https://developer.android.com/tools/variables#adb
std::env::set_var("ANDROID_SERIAL", device_serial)
}

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);
Expand Down
8 changes: 5 additions & 3 deletions src/gui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::core::sync::{get_devices_list, initial_load, perform_adb_commands, Co
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 crate::core::utils::{set_adb_serial, string_to_theme, NAME};

use iced::advanced::graphics::image::image_rs::ImageFormat;
use iced::font;
Expand All @@ -21,7 +21,6 @@ use iced::{
window::Settings as Window, Alignment, Application, Command, Element, Length, Renderer,
Settings,
};
use std::env;
#[cfg(feature = "self-update")]
use std::path::PathBuf;

Expand Down Expand Up @@ -255,7 +254,10 @@ impl Application for UadGui {
Message::DeviceSelected(s_device) => {
self.selected_device = Some(s_device.clone());
self.view = View::List;
env::set_var(ANDROID_SERIAL, s_device.adb_id);
#[allow(unsafe_code)]
unsafe {
set_adb_serial(s_device.adb_id)
};
info!("{:-^65}", "-");
info!(
"ANDROID_SDK: {} | DEVICE: {}",
Expand Down
12 changes: 7 additions & 5 deletions src/gui/views/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@ use crate::core::uad_lists::{
load_debloat_lists, Opposite, PackageHashMap, PackageState, Removal, UadList, UadListState,
};
use crate::core::utils::{
export_selection, fetch_packages, open_url, ANDROID_SERIAL, EXPORT_FILE_NAME, NAME,
export_selection, fetch_packages, open_url, set_adb_serial, EXPORT_FILE_NAME, NAME,
};
use crate::gui::style;
use crate::gui::widgets::navigation_menu::ICONS;
use std::env;
use std::path::PathBuf;

use crate::gui::views::settings::Settings;
Expand Down Expand Up @@ -864,12 +863,15 @@ impl List {
}

#[expect(clippy::unused_async, reason = "1 call-site")]
async fn init_apps_view(remote: bool, phone: Phone) -> (PackageHashMap, UadListState) {
async fn init_apps_view(remote: bool, device: Phone) -> (PackageHashMap, UadListState) {
let uad_lists = load_debloat_lists(remote);
match uad_lists {
Ok(list) => {
env::set_var(ANDROID_SERIAL, phone.adb_id.clone());
if phone.adb_id.is_empty() {
#[allow(unsafe_code)]
unsafe {
set_adb_serial(device.adb_id.clone())
};
if device.adb_id.is_empty() {
error!("AppsView ready but no phone found");
}
(list, UadListState::Done)
Expand Down
Loading