feat(app): the bot browser's window on a virtual monitor to share in Discord
- features.browserShare (봇용 크롬창 화면공유 선택 표시, off by default) and a driver card on the features screen: the Virtual Display Driver 25.7.23 (MIT, SignPath-signed) ships in display-driver/ (hash-checked by package.sh); install and uninstall run jarvis.exe elevated once (--display-driver), settings in %ProgramData%\JarvisBot\display-driver, another program's copy of the driver is left alone - the monitor is on the desktop only while the bot browser uses it, at the rightmost real monitor's bottom-right corner; the stop closes Chrome first, then takes the monitor off - Chrome starts with no window and the app opens it over CDP in the background, so it never takes the focus; the window is a tool window (no Alt+Tab, no taskbar button), fills the monitor's work area and keeps drawing when covered; without a monitor it runs headless with the reason on the dashboard - Chrome runs with --do-not-de-elevate on Windows: started by an app running as administrator it restarted itself as the user and the app lost hold of it - checked on the win-ci Windows VM from install to uninstall (focus kept while typing, no taskbar button, no Chrome left, nothing left after uninstall) and on Linux with a real Chrome Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
531
app/src/vdisplay.rs
Normal file
531
app/src/vdisplay.rs
Normal file
@@ -0,0 +1,531 @@
|
||||
//! 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 (its settings folder is the driver's).
|
||||
pub installed: bool,
|
||||
/// Another program's copy of the same driver is installed; the app leaves it alone.
|
||||
pub other: bool,
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn status() -> DriverStatus {
|
||||
DriverStatus { supported: false, installed: false, other: false }
|
||||
}
|
||||
|
||||
#[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)
|
||||
}
|
||||
|
||||
pub fn status() -> DriverStatus {
|
||||
let present = adapter().is_some() || !hardware_devices(false).is_empty();
|
||||
let ours = ours();
|
||||
DriverStatus { supported: true, installed: ours && present, other: present && !ours }
|
||||
}
|
||||
|
||||
/// 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 display-class devices with the driver's hardware ID (`present`: only those plugged in).
|
||||
fn hardware_devices(present: bool) -> Vec<SP_DEVINFO_DATA> {
|
||||
let (set, list) = hardware_set(present);
|
||||
if set != INVALID_HANDLE_VALUE as HDEVINFO {
|
||||
// SAFETY: the list from `hardware_set`, no longer used.
|
||||
unsafe { SetupDiDestroyDeviceInfoList(set) };
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
fn hardware_set(present: bool) -> (HDEVINFO, Vec<SP_DEVINFO_DATA>) {
|
||||
// SAFETY: a device list for the display class; destroyed by the callers that keep it.
|
||||
let set = unsafe { SetupDiGetClassDevsW(&GUID_DEVCLASS_DISPLAY, std::ptr::null(), std::ptr::null_mut(), if present { DIGCF_PRESENT } else { 0 }) };
|
||||
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.
|
||||
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 (present, ours) = (adapter().is_some() || !hardware_devices(false).is_empty(), ours());
|
||||
if present && !ours {
|
||||
return Err("다른 프로그램이 설치한 가상 디스플레이 드라이버가 이미 있습니다".into());
|
||||
}
|
||||
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 hardware_devices(false).is_empty() {
|
||||
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() };
|
||||
return Err(if e == ERROR_CANCELLED { "드라이버 설치를 취소했습니다".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(())
|
||||
}
|
||||
|
||||
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.
|
||||
pub(super) fn uninstall(driver: &Path) -> Result<(), String> {
|
||||
if !ours() {
|
||||
return Err("이 앱이 설치한 가상 디스플레이 드라이버가 아닙니다".into());
|
||||
}
|
||||
let (set, list) = hardware_set(false);
|
||||
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) };
|
||||
}
|
||||
let inf = wide_path(&driver.join("MttVDD.inf"));
|
||||
let mut reboot: BOOL = 0;
|
||||
// SAFETY: valid NUL-terminated path; a driver not in the store is just a failure we ignore.
|
||||
unsafe { DiUninstallDriverW(std::ptr::null_mut(), inf.as_ptr(), 0, &mut reboot) };
|
||||
let _ = run("reg", &["delete", &format!("HKLM\\{REG_KEY}"), "/f"]);
|
||||
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);
|
||||
}
|
||||
}
|
||||
if hardware_devices(false).is_empty() { Ok(()) } else { Err("가상 모니터 장치를 지우지 못했습니다".into()) }
|
||||
}
|
||||
|
||||
/// 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(¶ms));
|
||||
// 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})")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user