Files
javis_bot/app/src/vdisplay.rs
javis-bot 9b53af169d fix(app): what is left of the virtual monitor's driver stays ours and can be removed from the screen
- a failed install forgets the driver (registry value, settings folder) only when its clean-up
  left no device and no package, and never when it was ours before; otherwise it stays ours and
  the error gives both the install's reason and that something is left to remove
- the driver status separates a usable monitor (installed) from what this app left without one
  (leftover) and names the button (action): uninstall for both, so a removal whose package step
  failed can be retried from the features screen
- pure rules after_failed_install and driver_status with unit tests; checked again on the win-ci
  VM: a declined install leaves nothing, then install and uninstall

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:00:54 +09:00

657 lines
31 KiB
Rust

//! The virtual monitor the bot browser's window sits on, so the user can share it in Discord's
//! "Screen" tab while no real monitor shows it (admin.spec.md, "Virtual monitor";
//! `docs/v2/pc-features.md`, "봇용 크롬창과 디스코드 화면공유").
//!
//! The monitor comes from the open-source Virtual Display Driver (MIT, signed by the SignPath
//! Foundation), shipped next to `jarvis.exe` in `display-driver/`. Installing it needs the
//! administrator once (`--display-driver install`, started elevated by the app); turning the monitor
//! on and off does not: the app attaches it to the desktop only while the bot browser uses it.
use std::path::{Path, PathBuf};
use serde::Serialize;
/// The monitor's mode (the driver offers only this one): small enough to share cheaply.
pub const WIDTH: i32 = 1280;
pub const HEIGHT: i32 = 720;
pub const REFRESH: u32 = 30;
/// The adapter name the driver's INF gives its monitors.
pub const ADAPTER_NAME: &str = "Virtual Display Driver";
pub const HARDWARE_ID: &str = "Root\\MttVDD";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Rect {
pub x: i32,
pub y: i32,
pub w: i32,
pub h: i32,
}
/// Where the virtual monitor goes: right of and below the rightmost real monitor, touching it only
/// at that monitor's bottom-right corner, so the mouse hardly ever wanders onto it and no real
/// monitor overlaps it (nothing reaches further right).
pub fn corner(real: &[Rect]) -> (i32, i32) {
real.iter()
.max_by_key(|r| (r.x + r.w, r.y + r.h))
.map(|r| (r.x + r.w, r.y + r.h))
.unwrap_or((0, 0))
}
/// The driver's settings file: one monitor with one mode, the driver's other options at their
/// defaults.
pub fn settings_xml() -> String {
format!(
"<?xml version='1.0' encoding='utf-8'?>\r\n<vdd_settings>\r\n\
<monitors><count>1</count></monitors>\r\n\
<gpu><friendlyname>default</friendlyname></gpu>\r\n\
<global><g_refresh_rate>{REFRESH}</g_refresh_rate></global>\r\n\
<resolutions><resolution><width>{WIDTH}</width><height>{HEIGHT}</height><refresh_rate>{REFRESH}</refresh_rate></resolution></resolutions>\r\n\
<options><CustomEdid>false</CustomEdid><PreventSpoof>false</PreventSpoof><EdidCeaOverride>false</EdidCeaOverride>\
<HardwareCursor>true</HardwareCursor><SDR10bit>false</SDR10bit><HDRPlus>false</HDRPlus>\
<logging>false</logging><debuglogging>false</debuglogging></options>\r\n</vdd_settings>\r\n"
)
}
/// Where the driver reads its settings: the driver runs as a system service, which cannot read a
/// data folder in the user's profile, so this is the one place outside the data folder.
pub fn config_dir() -> Option<PathBuf> {
std::env::var_os("ProgramData").map(|p| PathBuf::from(p).join("JarvisBot").join("display-driver"))
}
/// The driver files shipped with the app.
pub fn driver_dir() -> Option<PathBuf> {
std::env::current_exe().ok()?.parent().map(|d| d.join("display-driver"))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct DriverStatus {
/// Windows only.
pub supported: bool,
/// Installed by this app with its monitor there: usable.
pub installed: bool,
/// Something this app installed is left without a usable monitor (a removal or a failed
/// install's clean-up that did not finish): to be removed.
pub leftover: bool,
/// Another program's copy of the same driver is installed; the app leaves it alone.
pub other: bool,
/// The button the screen offers: `install`, `uninstall` (also for a leftover), or none.
pub action: Option<&'static str>,
}
/// The status from whether the driver is ours (its registry value points at our settings), its
/// monitor is there, and any of its devices is.
#[cfg_attr(not(windows), allow(dead_code))]
fn driver_status(ours: bool, monitor: bool, devices: bool) -> DriverStatus {
let installed = ours && monitor;
let leftover = ours && !installed;
let other = (monitor || devices) && !ours;
let action = if ours { Some("uninstall") } else if other { None } else { Some("install") };
DriverStatus { supported: true, installed, leftover, other, action }
}
/// After a failed install: whether to forget the driver (its registry value and settings folder)
/// and what to report. Only an attempt that was not ours before and left no device and no package
/// (1168: not in the driver store) is forgotten; otherwise it stays ours so the screen can remove
/// what is left.
#[cfg_attr(not(windows), allow(dead_code))]
fn after_failed_install(failure: String, was_ours: bool, devices_left: usize, package: Result<(), u32>) -> (bool, String) {
match removal_done(devices_left, package) {
Ok(()) => (!was_ours, failure),
Err(e) => (false, format!("{failure}. 정리하지 못한 것이 남아 있으니 제거를 눌러 주세요 ({e})")),
}
}
#[cfg(not(windows))]
pub fn status() -> DriverStatus {
DriverStatus { supported: false, installed: false, leftover: false, other: false, action: None }
}
#[cfg(not(windows))]
pub fn attach() -> Result<Rect, String> {
Err("가상 모니터는 Windows에서만 씁니다".into())
}
#[cfg(not(windows))]
pub fn detach() {}
#[cfg(not(windows))]
pub fn settle_windows(_pid: u32) -> usize {
0
}
#[cfg(not(windows))]
pub async fn run_elevated(_action: &str) -> Result<(), String> {
Err("가상 모니터는 Windows에서만 씁니다".into())
}
/// `jarvis.exe --display-driver install|uninstall --result FILE`: the elevated half of
/// `run_elevated`; the outcome (empty, or why it failed) goes to FILE. `None` without the option.
pub fn elevated_main(args: &[String]) -> Option<i32> {
let i = args.iter().position(|a| a == "--display-driver")?;
let action = args.get(i + 1).map(String::as_str).unwrap_or("");
let result = args.iter().position(|a| a == "--result").and_then(|j| args.get(j + 1)).map(PathBuf::from);
let outcome = match (action, driver_dir()) {
(_, None) => Err("앱 폴더를 찾지 못했습니다".to_owned()),
("install", Some(d)) => install(&d),
("uninstall", Some(d)) => uninstall(&d),
_ => Err(format!("알 수 없는 동작: {action}")),
};
if let Some(f) = result {
let _ = std::fs::write(f, outcome.as_ref().err().map(String::as_str).unwrap_or(""));
}
Some(if outcome.is_ok() { 0 } else { 1 })
}
#[cfg(not(windows))]
fn install(_driver: &Path) -> Result<(), String> {
Err("가상 모니터는 Windows에서만 씁니다".into())
}
#[cfg(not(windows))]
fn uninstall(_driver: &Path) -> Result<(), String> {
Err("가상 모니터는 Windows에서만 씁니다".into())
}
#[cfg(windows)]
pub use win::{attach, detach, run_elevated, settle_windows, status};
#[cfg(windows)]
use win::{install, uninstall};
#[cfg(windows)]
mod win {
use super::*;
use std::os::windows::ffi::OsStrExt;
use windows_sys::core::BOOL;
use windows_sys::Win32::Devices::DeviceAndDriverInstallation::*;
use windows_sys::Win32::Foundation::*;
use windows_sys::Win32::Graphics::Gdi::*;
use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ};
use windows_sys::Win32::System::Threading::{GetExitCodeProcess, WaitForSingleObject, INFINITE};
use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW};
use windows_sys::Win32::UI::WindowsAndMessaging::*;
const REG_KEY: &str = "SOFTWARE\\MikeTheTech\\VirtualDisplayDriver";
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn wide_path(p: &Path) -> Vec<u16> {
p.as_os_str().encode_wide().chain(Some(0)).collect()
}
fn text(buf: &[u16]) -> String {
String::from_utf16_lossy(&buf[..buf.iter().position(|&c| c == 0).unwrap_or(buf.len())])
}
struct Device {
name: [u16; 32],
string: String,
attached: bool,
}
fn devices() -> Vec<Device> {
let mut out = vec![];
for i in 0.. {
let mut dd = DISPLAY_DEVICEW { cb: std::mem::size_of::<DISPLAY_DEVICEW>() as u32, ..Default::default() };
// SAFETY: `dd` is a DISPLAY_DEVICEW with its size set, as the call requires.
if unsafe { EnumDisplayDevicesW(std::ptr::null(), i, &mut dd, 0) } == 0 {
break;
}
out.push(Device { name: dd.DeviceName, string: text(&dd.DeviceString),
attached: dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP != 0 });
}
out
}
fn current(name: &[u16; 32]) -> Option<Rect> {
let mut dm = DEVMODEW { dmSize: std::mem::size_of::<DEVMODEW>() as u16, ..Default::default() };
// SAFETY: `name` is NUL-terminated (from EnumDisplayDevicesW) and `dm` has its size set.
if unsafe { EnumDisplaySettingsExW(name.as_ptr(), ENUM_CURRENT_SETTINGS, &mut dm, 0) } == 0 {
return None;
}
// SAFETY: for a display, the position variant of the union is the one Windows fills.
let pos = unsafe { dm.Anonymous1.Anonymous2.dmPosition };
Some(Rect { x: pos.x, y: pos.y, w: dm.dmPelsWidth as i32, h: dm.dmPelsHeight as i32 })
}
/// Put the display at `rect`, or take it off the desktop with `None`, and keep that.
fn set_mode(name: &[u16; 32], rect: Option<Rect>) -> Result<(), String> {
let mut dm = DEVMODEW { dmSize: std::mem::size_of::<DEVMODEW>() as u16, ..Default::default() };
// SAFETY: as in `current`; a failure leaves `dm` zeroed, which the fields below complete.
unsafe { EnumDisplaySettingsExW(name.as_ptr(), ENUM_REGISTRY_SETTINGS, &mut dm, 0) };
let r = rect.unwrap_or(Rect { x: 0, y: 0, w: 0, h: 0 });
dm.dmFields = DM_POSITION | DM_PELSWIDTH | DM_PELSHEIGHT;
dm.Anonymous1.Anonymous2 = DEVMODEW_0_1 { dmPosition: POINTL { x: r.x, y: r.y }, ..Default::default() };
dm.dmPelsWidth = r.w as u32;
dm.dmPelsHeight = r.h as u32;
// SAFETY: valid NUL-terminated device name and DEVMODEW; null window and parameter.
let changed = unsafe {
ChangeDisplaySettingsExW(name.as_ptr(), &dm, std::ptr::null_mut(), CDS_UPDATEREGISTRY | CDS_NORESET, std::ptr::null())
};
// SAFETY: the documented "apply the stored changes" call: all null, no flags.
let applied = unsafe { ChangeDisplaySettingsExW(std::ptr::null(), std::ptr::null(), std::ptr::null_mut(), 0, std::ptr::null()) };
if changed != DISP_CHANGE_SUCCESSFUL || applied != DISP_CHANGE_SUCCESSFUL {
return Err(format!("화면 설정을 바꾸지 못했습니다 ({changed}, {applied})"));
}
Ok(())
}
fn vdd_path() -> Option<String> {
let mut buf = [0u16; 520];
let mut size = (buf.len() * 2) as u32;
let (key, value) = (wide(REG_KEY), wide("VDDPATH"));
// SAFETY: valid NUL-terminated strings; `buf` holds `size` bytes.
let r = unsafe {
RegGetValueW(HKEY_LOCAL_MACHINE, key.as_ptr(), value.as_ptr(), RRF_RT_REG_SZ, std::ptr::null_mut(),
buf.as_mut_ptr().cast(), &mut size)
};
(r == ERROR_SUCCESS).then(|| text(&buf))
}
fn ours() -> bool {
match (vdd_path(), config_dir()) {
(Some(p), Some(c)) => p.trim_end_matches('\\').eq_ignore_ascii_case(c.to_string_lossy().trim_end_matches('\\')),
_ => false,
}
}
fn adapter() -> Option<Device> {
devices().into_iter().find(|d| d.string == ADAPTER_NAME)
}
/// Installed means ours with its monitor there (the driver loaded); ours without it is a
/// leftover the screen offers to remove.
pub fn status() -> DriverStatus {
driver_status(ours(), adapter().is_some(), !hardware_devices().is_empty())
}
/// Put the virtual monitor on the desktop at `corner` and return where it is.
pub fn attach() -> Result<Rect, String> {
if !ours() {
return Err("가상 모니터 드라이버가 설치되지 않았습니다".into());
}
let v = adapter().ok_or("가상 모니터를 찾지 못했습니다")?;
let real: Vec<Rect> = devices().iter().filter(|d| d.attached && d.string != ADAPTER_NAME)
.filter_map(|d| current(&d.name)).collect();
let (x, y) = corner(&real);
set_mode(&v.name, Some(Rect { x, y, w: WIDTH, h: HEIGHT }))?;
current(&v.name).filter(|r| r.w > 0).ok_or_else(|| "가상 모니터가 켜지지 않았습니다".into())
}
/// Take the virtual monitor off the desktop (when it is ours and on it).
pub fn detach() {
if !ours() {
return;
}
if let Some(v) = adapter().filter(|d| d.attached) {
if let Err(e) = set_mode(&v.name, None) {
crate::warn_log!("browser", "Warning: the virtual monitor stays on: {e}");
}
}
}
struct Found {
pid: u32,
windows: Vec<HWND>,
}
unsafe extern "system" fn collect(hwnd: HWND, lparam: LPARAM) -> BOOL {
// SAFETY: `lparam` is the `Found` that `settle_windows` passes and outlives EnumWindows.
let found = unsafe { &mut *(lparam as *mut Found) };
let mut pid = 0u32;
let mut class = [0u16; 64];
// SAFETY: plain queries on a window handle EnumWindows gave; buffers are sized as passed.
unsafe {
GetWindowThreadProcessId(hwnd, &mut pid);
if pid == found.pid && IsWindowVisible(hwnd) != 0 && GetWindow(hwnd, GW_OWNER).is_null()
&& GetClassNameW(hwnd, class.as_mut_ptr(), class.len() as i32) > 0 && text(&class) == "Chrome_WidgetWin_1" {
found.windows.push(hwnd);
}
}
1
}
/// Make process `pid`'s top-level Chrome windows tool windows (not in Alt+Tab, Win+Tab or the
/// taskbar), fill their monitor's work area (Windows may give the virtual monitor a taskbar of
/// its own, which would cover the page's bottom) and put them behind all others, all without
/// activating them. Returns how many it made tool windows.
pub fn settle_windows(pid: u32) -> usize {
let mut found = Found { pid, windows: vec![] };
// SAFETY: `collect` only reads windows and writes into `found`, which lives through the call.
unsafe { EnumWindows(Some(collect), &mut found as *mut Found as LPARAM) };
let mut changed = 0;
for h in found.windows {
// SAFETY: style changes on a window of our own child process; hiding and showing it
// again is what makes the taskbar notice the new style.
unsafe {
let ex = GetWindowLongPtrW(h, GWL_EXSTYLE) as u32;
if ex & WS_EX_TOOLWINDOW == 0 {
ShowWindow(h, SW_HIDE);
SetWindowLongPtrW(h, GWL_EXSTYLE, ((ex | WS_EX_TOOLWINDOW) & !WS_EX_APPWINDOW) as isize);
ShowWindow(h, SW_SHOWNOACTIVATE);
changed += 1;
}
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
if GetMonitorInfoW(MonitorFromWindow(h, MONITOR_DEFAULTTONEAREST), &mut mi) != 0 {
let w = mi.rcWork;
SetWindowPos(h, HWND_BOTTOM, w.left, w.top, w.right - w.left, w.bottom - w.top, SWP_NOACTIVATE);
} else {
SetWindowPos(h, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
}
}
changed
}
/// The root devices with the driver's hardware ID, in any class (a device whose driver install
/// was declined has none), present or not.
fn hardware_devices() -> Vec<SP_DEVINFO_DATA> {
let (set, list) = hardware_set();
if set != INVALID_HANDLE_VALUE as HDEVINFO {
// SAFETY: the list from `hardware_set`, no longer used.
unsafe { SetupDiDestroyDeviceInfoList(set) };
}
list
}
fn hardware_set() -> (HDEVINFO, Vec<SP_DEVINFO_DATA>) {
let root = wide("ROOT");
let flags = DIGCF_ALLCLASSES;
// SAFETY: a device list of the root enumerator; destroyed by the callers that keep it.
let set = unsafe { SetupDiGetClassDevsW(std::ptr::null(), root.as_ptr(), std::ptr::null_mut(), flags) };
let mut out = vec![];
if set == INVALID_HANDLE_VALUE as HDEVINFO {
return (set, out);
}
for i in 0.. {
let mut di = SP_DEVINFO_DATA { cbSize: std::mem::size_of::<SP_DEVINFO_DATA>() as u32, ..Default::default() };
// SAFETY: `di` has its size set; the loop ends at the first index past the list.
if unsafe { SetupDiEnumDeviceInfo(set, i, &mut di) } == 0 {
break;
}
let mut buf = [0u16; 256];
// SAFETY: `buf` holds the byte count passed.
let ok = unsafe {
SetupDiGetDeviceRegistryPropertyW(set, &di, SPDRP_HARDWAREID, std::ptr::null_mut(), buf.as_mut_ptr().cast(),
(buf.len() * 2) as u32, std::ptr::null_mut())
};
if ok != 0 && text(&buf).eq_ignore_ascii_case(HARDWARE_ID) {
out.push(di);
}
}
(set, out)
}
fn run(cmd: &str, args: &[&str]) -> Result<(), String> {
use std::os::windows::process::CommandExt;
let s = std::process::Command::new(cmd).args(args).creation_flags(0x0800_0000)
.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status()
.map_err(|e| format!("{cmd}: {e}"))?;
if s.success() { Ok(()) } else { Err(format!("{cmd} failed ({s})")) }
}
/// Elevated: settings folder, the driver's registry value, the device, and its driver. Windows
/// asks the user once whether to install software from the SignPath Foundation. A failure (also
/// the user saying no) undoes what this attempt made, so nothing looks installed and the next
/// attempt starts clean.
pub(super) fn install(driver: &Path) -> Result<(), String> {
let inf = driver.join("MttVDD.inf");
if !inf.is_file() {
return Err("드라이버 파일이 없습니다 (display-driver\\MttVDD.inf)".into());
}
let (was_ours, had_device) = (ours(), !hardware_devices().is_empty());
if (had_device || adapter().is_some()) && !was_ours {
return Err("다른 프로그램이 설치한 가상 디스플레이 드라이버가 이미 있습니다".into());
}
let Err(failure) = install_steps(&inf, had_device) else { return Ok(()) };
let left = if had_device { 0 } else { remove_devices() };
let package = if was_ours || left > 0 { Ok(()) } else { uninstall_package(&inf) };
let (forget, why) = after_failed_install(failure, was_ours, left, package);
if forget {
let _ = run("reg", &["delete", &format!("HKLM\\{REG_KEY}"), "/f"]);
remove_config_dir();
}
Err(why)
}
fn install_steps(inf: &Path, had_device: bool) -> Result<(), String> {
let dir = config_dir().ok_or("ProgramData 폴더를 찾지 못했습니다")?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
std::fs::write(dir.join("vdd_settings.xml"), settings_xml()).map_err(|e| e.to_string())?;
// Only the system, administrators, the driver's service account (LOCAL SERVICE) and users
// reading: no user can change what the driver reads.
let d = dir.to_string_lossy().into_owned();
run("icacls", &[&d, "/inheritance:r", "/grant:r", "*S-1-5-18:(OI)(CI)F", "*S-1-5-32-544:(OI)(CI)F",
"*S-1-5-19:(OI)(CI)RX", "*S-1-5-32-545:(OI)(CI)RX"])?;
run("reg", &["add", &format!("HKLM\\{REG_KEY}"), "/v", "VDDPATH", "/t", "REG_SZ", "/d", &d, "/f"])?;
if !had_device {
create_device()?;
}
let (hw, inf_w) = (wide(HARDWARE_ID), wide_path(inf));
let mut reboot: BOOL = 0;
// SAFETY: valid NUL-terminated strings; no parent window.
if unsafe { UpdateDriverForPlugAndPlayDevicesW(std::ptr::null_mut(), hw.as_ptr(), inf_w.as_ptr(), INSTALLFLAG_FORCE, &mut reboot) } == 0 {
// SAFETY: plain call.
let e = unsafe { GetLastError() };
// No to Windows' question about the publisher comes back as "publisher not trusted".
const PUBLISHER_NOT_TRUSTED: u32 = 0xE000_0243;
return Err(if e == ERROR_CANCELLED || e == PUBLISHER_NOT_TRUSTED { "드라이버 설치를 취소했습니다".into() }
else { format!("드라이버를 설치하지 못했습니다 ({e})") });
}
// The new monitor joins the desktop at once; it stays off until the bot browser uses it.
for _ in 0..50 {
if adapter().is_some_and(|a| a.attached) {
detach();
break;
}
std::thread::sleep(std::time::Duration::from_millis(200));
}
Ok(())
}
/// Remove every device with the driver's hardware ID; returns how many are left.
fn remove_devices() -> usize {
let (set, list) = hardware_set();
for di in &list {
// SAFETY: removing a device of the list `set`, which is destroyed after the loop.
unsafe { SetupDiCallClassInstaller(DIF_REMOVE, set, di) };
}
if set != INVALID_HANDLE_VALUE as HDEVINFO {
// SAFETY: the list from `hardware_set`.
unsafe { SetupDiDestroyDeviceInfoList(set) };
}
hardware_devices().len()
}
/// Remove the driver package from the driver store; `Err` with the Windows error code.
fn uninstall_package(inf: &Path) -> Result<(), u32> {
let inf = wide_path(inf);
let mut reboot: BOOL = 0;
// SAFETY: valid NUL-terminated path; no parent window.
if unsafe { DiUninstallDriverW(std::ptr::null_mut(), inf.as_ptr(), 0, &mut reboot) } != 0 {
return Ok(());
}
// SAFETY: plain call.
Err(unsafe { GetLastError() })
}
fn remove_config_dir() {
if let Some(dir) = config_dir() {
let _ = std::fs::remove_dir_all(&dir);
if let Some(parent) = dir.parent() {
let _ = std::fs::remove_dir(parent);
}
}
}
fn create_device() -> Result<(), String> {
let (name, hw) = (wide("Display"), {
let mut v: Vec<u16> = HARDWARE_ID.encode_utf16().collect();
v.extend([0, 0]);
v
});
// SAFETY: the devcon "install" sequence: a list, one generated device with the hardware ID,
// registered with the class installer; the list is destroyed on every path.
unsafe {
let set = SetupDiCreateDeviceInfoList(&GUID_DEVCLASS_DISPLAY, std::ptr::null_mut());
if set == INVALID_HANDLE_VALUE as HDEVINFO {
return Err(format!("장치 목록을 만들지 못했습니다 ({})", GetLastError()));
}
let mut di = SP_DEVINFO_DATA { cbSize: std::mem::size_of::<SP_DEVINFO_DATA>() as u32, ..Default::default() };
let ok = SetupDiCreateDeviceInfoW(set, name.as_ptr(), &GUID_DEVCLASS_DISPLAY, std::ptr::null(), std::ptr::null_mut(), DICD_GENERATE_ID, &mut di) != 0
&& SetupDiSetDeviceRegistryPropertyW(set, &mut di, SPDRP_HARDWAREID, hw.as_ptr().cast(), (hw.len() * 2) as u32) != 0
&& SetupDiCallClassInstaller(DIF_REGISTERDEVICE, set, &di) != 0;
let e = GetLastError();
SetupDiDestroyDeviceInfoList(set);
if ok { Ok(()) } else { Err(format!("가상 모니터 장치를 만들지 못했습니다 ({e})")) }
}
}
/// Elevated: remove the device, the driver, the registry value and the settings folder; only
/// when this app installed it. The registry value (what makes it ours) goes only once the
/// device and the driver are gone, so a failed removal can be retried.
pub(super) fn uninstall(driver: &Path) -> Result<(), String> {
if !ours() {
return Err("이 앱이 설치한 가상 디스플레이 드라이버가 아닙니다".into());
}
let left = remove_devices();
let package = if left == 0 { uninstall_package(&driver.join("MttVDD.inf")) } else { Ok(()) };
removal_done(left, package)?;
run("reg", &["delete", &format!("HKLM\\{REG_KEY}"), "/f"])
.map_err(|e| format!("드라이버 등록 정보를 지우지 못했습니다: {e}"))?;
remove_config_dir();
Ok(())
}
/// Run `jarvis.exe --display-driver <action>` as administrator (Windows asks the user) and wait.
pub async fn run_elevated(action: &str) -> Result<(), String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let result = std::env::temp_dir().join(format!("jarvis-display-{}.txt", std::process::id()));
let _ = std::fs::remove_file(&result);
let params = format!("--display-driver {action} --result \"{}\"", result.display());
let code = tokio::task::spawn_blocking(move || -> Result<u32, String> {
let (verb, file, params) = (wide("runas"), wide_path(&exe), wide(&params));
// SAFETY: SHELLEXECUTEINFOW is plain data; all zero is its documented empty state.
let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() };
info.cbSize = std::mem::size_of::<SHELLEXECUTEINFOW>() as u32;
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpVerb = verb.as_ptr();
info.lpFile = file.as_ptr();
info.lpParameters = params.as_ptr();
info.nShow = SW_HIDE;
// SAFETY: `info` is filled as documented and its strings live through the call; the
// process handle it returns is waited on and closed here.
unsafe {
if ShellExecuteExW(&mut info) == 0 {
let e = GetLastError();
return Err(if e == ERROR_CANCELLED { "관리자 권한을 받지 못했습니다".into() } else { format!("관리자 권한으로 실행하지 못했습니다 ({e})") });
}
WaitForSingleObject(info.hProcess, INFINITE);
let mut code = 1u32;
GetExitCodeProcess(info.hProcess, &mut code);
CloseHandle(info.hProcess);
Ok(code)
}
}).await.map_err(|e| e.to_string())??;
let why = std::fs::read_to_string(&result).unwrap_or_default();
let _ = std::fs::remove_file(&result);
match code {
0 => Ok(()),
_ if !why.is_empty() => Err(why),
c => Err(format!("드라이버 작업이 실패했습니다 (종료 코드 {c})")),
}
}
}
/// Whether a removal may forget the driver was ours: no device left, and the driver package
/// removed or not in the driver store (Windows error 1168, ERROR_NOT_FOUND).
#[cfg_attr(not(windows), allow(dead_code))]
fn removal_done(devices_left: usize, package: Result<(), u32>) -> Result<(), String> {
if devices_left > 0 {
return Err(format!("가상 모니터 장치 {devices_left}개를 지우지 못했습니다. 다시 시도해 주세요"));
}
match package {
Ok(()) | Err(1168) => Ok(()),
Err(e) => Err(format!("드라이버 패키지를 지우지 못했습니다 ({e}). 다시 시도해 주세요")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_failed_install_forgets_the_driver_only_when_its_leftovers_are_gone() {
let declined = || "드라이버 설치를 취소했습니다".to_owned();
// Cleaned up: forgotten (when it was not ours before), the failure reported as it was.
assert_eq!(after_failed_install(declined(), false, 0, Err(1168)), (true, declined()));
// A device left: kept ours, so the leftover can be removed; both reasons reported.
let (forget, why) = after_failed_install(declined(), false, 1, Ok(()));
assert!(!forget, "a device left keeps the registry value");
assert!(why.starts_with(&declined()) && why.contains("제거"), "{why}");
// A package left: the same.
let (forget, why) = after_failed_install(declined(), false, 0, Err(5));
assert!(!forget);
assert!(why.contains("제거"), "{why}");
// Ours before the attempt: never forgotten by a failed reinstall.
assert!(!after_failed_install(declined(), true, 0, Ok(())).0);
}
#[test]
fn what_is_left_of_the_driver_can_always_be_removed_from_the_screen() {
// Installed and working: remove.
let s = driver_status(true, true, true);
assert!(s.installed && !s.leftover && !s.other);
assert_eq!(s.action, Some("uninstall"));
// Device gone but the package (and the registry value) left after a failed removal.
let s = driver_status(true, false, false);
assert!(!s.installed && s.leftover);
assert_eq!(s.action, Some("uninstall"), "the leftover can be removed again");
// Nothing of ours: install. Another program's copy: nothing to press.
assert_eq!(driver_status(false, false, false).action, Some("install"));
let s = driver_status(false, true, true);
assert!(s.other && !s.installed && !s.leftover);
assert_eq!(s.action, None);
}
#[test]
fn a_removal_forgets_the_driver_only_when_device_and_package_are_gone() {
assert_eq!(removal_done(0, Ok(())), Ok(()));
assert_eq!(removal_done(0, Err(1168)), Ok(()), "a package not in the store is already gone");
assert!(removal_done(1, Ok(())).is_err(), "a device left keeps it ours, so it can be retried");
assert!(removal_done(0, Err(5)).is_err());
}
#[test]
fn the_monitor_touches_the_rightmost_monitor_only_at_its_corner() {
let one = [Rect { x: 0, y: 0, w: 1920, h: 1080 }];
assert_eq!(corner(&one), (1920, 1080));
// A second monitor left of the main one, and one above-right: the rightmost decides.
let three = [Rect { x: 0, y: 0, w: 2560, h: 1440 }, Rect { x: -1920, y: 0, w: 1920, h: 1080 },
Rect { x: 2560, y: -400, w: 1080, h: 1920 }];
let (x, y) = corner(&three);
assert_eq!((x, y), (3640, 1520));
for r in &three {
assert!(r.x + r.w <= x, "no real monitor reaches into the virtual one");
}
// Two equally far right: the lower corner, so neither overlaps.
let stacked = [Rect { x: 0, y: 0, w: 1920, h: 1080 }, Rect { x: 0, y: 1080, w: 1920, h: 1080 }];
assert_eq!(corner(&stacked), (1920, 2160));
}
#[test]
fn the_driver_gets_one_monitor_with_the_one_mode() {
let x = settings_xml();
assert!(x.contains("<count>1</count>"));
assert!(x.contains(&format!("<width>{WIDTH}</width><height>{HEIGHT}</height><refresh_rate>{REFRESH}</refresh_rate>")));
assert_eq!(x.matches("<resolution>").count(), 1);
assert!(x.contains("<CustomEdid>false</CustomEdid>"), "the driver never loads an EDID file from its folder");
}
#[test]
fn only_the_display_driver_option_runs_the_elevated_half() {
assert_eq!(elevated_main(&["jarvis".into(), "--location".into(), "x".into()]), None);
}
}