93 lines
2.8 KiB
Rust
93 lines
2.8 KiB
Rust
//! Windows 系统代理开关。
|
||
|
||
use super::MihomoManager;
|
||
|
||
// ===================== 系统代理(Windows) =====================
|
||
|
||
#[cfg(windows)]
|
||
pub(crate) fn set_system_proxy_windows(addr: &str) -> Result<(), String> {
|
||
use winreg::enums::*;
|
||
use winreg::RegKey;
|
||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||
let (settings, _) = hkcu
|
||
.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings")
|
||
.map_err(|e| e.to_string())?;
|
||
settings
|
||
.set_value("ProxyEnable", &1u32)
|
||
.map_err(|e| e.to_string())?;
|
||
settings
|
||
.set_value("ProxyServer", &addr)
|
||
.map_err(|e| e.to_string())?;
|
||
notify_wininet();
|
||
Ok(())
|
||
}
|
||
|
||
#[cfg(windows)]
|
||
pub(crate) fn clear_system_proxy_windows() -> Result<(), String> {
|
||
use winreg::enums::*;
|
||
use winreg::RegKey;
|
||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||
let (settings, _) = hkcu
|
||
.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings")
|
||
.map_err(|e| e.to_string())?;
|
||
settings
|
||
.set_value("ProxyEnable", &0u32)
|
||
.map_err(|e| e.to_string())?;
|
||
notify_wininet();
|
||
Ok(())
|
||
}
|
||
|
||
#[cfg(windows)]
|
||
pub fn get_system_proxy_windows() -> bool {
|
||
use winreg::enums::*;
|
||
use winreg::RegKey;
|
||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||
hkcu.open_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings")
|
||
.ok()
|
||
.and_then(|s| s.get_value::<u32, _>("ProxyEnable").ok())
|
||
.map(|v| v != 0)
|
||
.unwrap_or(false)
|
||
}
|
||
|
||
#[cfg(windows)]
|
||
fn notify_wininet() {
|
||
unsafe {
|
||
use windows_sys::Win32::Networking::WinInet::*;
|
||
InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_SETTINGS_CHANGED, std::ptr::null(), 0);
|
||
InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_REFRESH, std::ptr::null(), 0);
|
||
}
|
||
}
|
||
|
||
#[cfg(not(windows))]
|
||
pub(crate) fn set_system_proxy_windows(_addr: &str) -> Result<(), String> {
|
||
Err("系统代理仅支持 Windows".into())
|
||
}
|
||
#[cfg(not(windows))]
|
||
pub(crate) fn clear_system_proxy_windows() -> Result<(), String> {
|
||
Err("系统代理仅支持 Windows".into())
|
||
}
|
||
#[cfg(not(windows))]
|
||
pub fn get_system_proxy_windows() -> bool {
|
||
false
|
||
}
|
||
|
||
impl MihomoManager {
|
||
/// 开启系统代理(托盘菜单调用)
|
||
pub fn enable_system_proxy(&self) -> Result<(), String> {
|
||
let settings = self.load_settings();
|
||
let addr = format!("127.0.0.1:{}", settings.mixed_port);
|
||
set_system_proxy_windows(&addr)?;
|
||
let mut s = settings;
|
||
s.system_proxy = true;
|
||
self.save_settings(&s)
|
||
}
|
||
|
||
/// 关闭系统代理(托盘菜单调用)
|
||
pub fn disable_system_proxy(&self) -> Result<(), String> {
|
||
clear_system_proxy_windows()?;
|
||
let mut s = self.load_settings();
|
||
s.system_proxy = false;
|
||
self.save_settings(&s)
|
||
}
|
||
}
|