windows.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. use std::{
  2. ffi::c_void,
  3. os::windows::process::CommandExt,
  4. path::{Path, PathBuf},
  5. process::Command,
  6. };
  7. use windows_sys::Win32::{
  8. Foundation::ERROR_SUCCESS,
  9. System::{
  10. Registry::{
  11. RegGetValueW, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, REG_EXPAND_SZ, REG_SZ,
  12. RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ,
  13. },
  14. Threading::{CREATE_NEW_CONSOLE, CREATE_NO_WINDOW},
  15. },
  16. };
  17. pub fn check_windows_app(app_name: &str) -> bool {
  18. resolve_windows_app_path(app_name).is_some()
  19. }
  20. pub fn resolve_windows_app_path(app_name: &str) -> Option<String> {
  21. fn expand_env(value: &str) -> String {
  22. let mut out = String::with_capacity(value.len());
  23. let mut index = 0;
  24. while let Some(start) = value[index..].find('%') {
  25. let start = index + start;
  26. out.push_str(&value[index..start]);
  27. let Some(end_rel) = value[start + 1..].find('%') else {
  28. out.push_str(&value[start..]);
  29. return out;
  30. };
  31. let end = start + 1 + end_rel;
  32. let key = &value[start + 1..end];
  33. if key.is_empty() {
  34. out.push('%');
  35. index = end + 1;
  36. continue;
  37. }
  38. if let Ok(v) = std::env::var(key) {
  39. out.push_str(&v);
  40. index = end + 1;
  41. continue;
  42. }
  43. out.push_str(&value[start..=end]);
  44. index = end + 1;
  45. }
  46. out.push_str(&value[index..]);
  47. out
  48. }
  49. fn extract_exe(value: &str) -> Option<String> {
  50. let value = value.trim();
  51. if value.is_empty() {
  52. return None;
  53. }
  54. if let Some(rest) = value.strip_prefix('"') {
  55. if let Some(end) = rest.find('"') {
  56. let inner = rest[..end].trim();
  57. if inner.to_ascii_lowercase().contains(".exe") {
  58. return Some(inner.to_string());
  59. }
  60. }
  61. }
  62. let lower = value.to_ascii_lowercase();
  63. let end = lower.find(".exe")?;
  64. Some(value[..end + 4].trim().trim_matches('"').to_string())
  65. }
  66. fn candidates(app_name: &str) -> Vec<String> {
  67. let app_name = app_name.trim().trim_matches('"');
  68. if app_name.is_empty() {
  69. return vec![];
  70. }
  71. let mut out = Vec::<String>::new();
  72. let mut push = |value: String| {
  73. let value = value.trim().trim_matches('"').to_string();
  74. if value.is_empty() {
  75. return;
  76. }
  77. if out.iter().any(|v| v.eq_ignore_ascii_case(&value)) {
  78. return;
  79. }
  80. out.push(value);
  81. };
  82. push(app_name.to_string());
  83. let lower = app_name.to_ascii_lowercase();
  84. if !lower.ends_with(".exe") {
  85. push(format!("{app_name}.exe"));
  86. }
  87. let snake = {
  88. let mut s = String::new();
  89. let mut underscore = false;
  90. for c in lower.chars() {
  91. if c.is_ascii_alphanumeric() {
  92. s.push(c);
  93. underscore = false;
  94. continue;
  95. }
  96. if underscore {
  97. continue;
  98. }
  99. s.push('_');
  100. underscore = true;
  101. }
  102. s.trim_matches('_').to_string()
  103. };
  104. if !snake.is_empty() {
  105. push(snake.clone());
  106. if !snake.ends_with(".exe") {
  107. push(format!("{snake}.exe"));
  108. }
  109. }
  110. let alnum = lower
  111. .chars()
  112. .filter(|c| c.is_ascii_alphanumeric())
  113. .collect::<String>();
  114. if !alnum.is_empty() {
  115. push(alnum.clone());
  116. push(format!("{alnum}.exe"));
  117. }
  118. match lower.as_str() {
  119. "sublime text" | "sublime-text" | "sublime_text" | "sublime text.exe" => {
  120. push("subl".to_string());
  121. push("subl.exe".to_string());
  122. push("sublime_text".to_string());
  123. push("sublime_text.exe".to_string());
  124. }
  125. _ => {}
  126. }
  127. out
  128. }
  129. fn reg_app_path(exe: &str) -> Option<String> {
  130. let exe = exe.trim().trim_matches('"');
  131. if exe.is_empty() {
  132. return None;
  133. }
  134. let query = |root: *mut c_void, subkey: &str| -> Option<String> {
  135. let flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ;
  136. let mut kind: u32 = 0;
  137. let mut size = 0u32;
  138. let mut key = subkey.encode_utf16().collect::<Vec<_>>();
  139. key.push(0);
  140. let status = unsafe {
  141. RegGetValueW(
  142. root,
  143. key.as_ptr(),
  144. std::ptr::null(),
  145. flags,
  146. &mut kind,
  147. std::ptr::null_mut(),
  148. &mut size,
  149. )
  150. };
  151. if status != ERROR_SUCCESS || size == 0 {
  152. return None;
  153. }
  154. if kind != REG_SZ && kind != REG_EXPAND_SZ {
  155. return None;
  156. }
  157. let mut data = vec![0u8; size as usize];
  158. let status = unsafe {
  159. RegGetValueW(
  160. root,
  161. key.as_ptr(),
  162. std::ptr::null(),
  163. flags,
  164. &mut kind,
  165. data.as_mut_ptr() as *mut c_void,
  166. &mut size,
  167. )
  168. };
  169. if status != ERROR_SUCCESS || size < 2 {
  170. return None;
  171. }
  172. let words = unsafe {
  173. std::slice::from_raw_parts(data.as_ptr().cast::<u16>(), (size as usize) / 2)
  174. };
  175. let len = words.iter().position(|v| *v == 0).unwrap_or(words.len());
  176. let value = String::from_utf16_lossy(&words[..len]).trim().to_string();
  177. if value.is_empty() {
  178. return None;
  179. }
  180. Some(value)
  181. };
  182. let keys = [
  183. (
  184. HKEY_CURRENT_USER,
  185. format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{exe}"),
  186. ),
  187. (
  188. HKEY_LOCAL_MACHINE,
  189. format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{exe}"),
  190. ),
  191. (
  192. HKEY_LOCAL_MACHINE,
  193. format!(r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\{exe}"),
  194. ),
  195. ];
  196. for (root, key) in keys {
  197. let Some(value) = query(root, &key) else {
  198. continue;
  199. };
  200. let Some(exe) = extract_exe(&value) else {
  201. continue;
  202. };
  203. let exe = expand_env(&exe);
  204. let path = Path::new(exe.trim().trim_matches('"'));
  205. if path.exists() {
  206. return Some(path.to_string_lossy().to_string());
  207. }
  208. }
  209. None
  210. }
  211. let app_name = app_name.trim().trim_matches('"');
  212. if app_name.is_empty() {
  213. return None;
  214. }
  215. let direct = Path::new(app_name);
  216. if direct.is_absolute() && direct.exists() {
  217. return Some(direct.to_string_lossy().to_string());
  218. }
  219. let key = app_name
  220. .chars()
  221. .filter(|v| v.is_ascii_alphanumeric())
  222. .flat_map(|v| v.to_lowercase())
  223. .collect::<String>();
  224. let has_ext = |path: &Path, ext: &str| {
  225. path.extension()
  226. .and_then(|v| v.to_str())
  227. .map(|v| v.eq_ignore_ascii_case(ext))
  228. .unwrap_or(false)
  229. };
  230. let resolve_cmd = |path: &Path| -> Option<String> {
  231. let bytes = std::fs::read(path).ok()?;
  232. let content = String::from_utf8_lossy(&bytes);
  233. for token in content.split('"') {
  234. let Some(exe) = extract_exe(token) else {
  235. continue;
  236. };
  237. let lower = exe.to_ascii_lowercase();
  238. if let Some(index) = lower.find("%~dp0") {
  239. let base = path.parent()?;
  240. let suffix = &exe[index + 5..];
  241. let mut resolved = PathBuf::from(base);
  242. for part in suffix.replace('/', "\\").split('\\') {
  243. if part.is_empty() || part == "." {
  244. continue;
  245. }
  246. if part == ".." {
  247. let _ = resolved.pop();
  248. continue;
  249. }
  250. resolved.push(part);
  251. }
  252. if resolved.exists() {
  253. return Some(resolved.to_string_lossy().to_string());
  254. }
  255. continue;
  256. }
  257. let resolved = PathBuf::from(expand_env(&exe));
  258. if resolved.exists() {
  259. return Some(resolved.to_string_lossy().to_string());
  260. }
  261. }
  262. None
  263. };
  264. let resolve_where = |query: &str| -> Option<String> {
  265. let output = Command::new("where")
  266. .creation_flags(CREATE_NO_WINDOW)
  267. .arg(query)
  268. .output()
  269. .ok()?;
  270. if !output.status.success() {
  271. return None;
  272. }
  273. let paths = String::from_utf8_lossy(&output.stdout)
  274. .lines()
  275. .map(str::trim)
  276. .filter(|line| !line.is_empty())
  277. .map(PathBuf::from)
  278. .collect::<Vec<_>>();
  279. if paths.is_empty() {
  280. return None;
  281. }
  282. if let Some(path) = paths.iter().find(|path| has_ext(path, "exe")) {
  283. return Some(path.to_string_lossy().to_string());
  284. }
  285. for path in &paths {
  286. if has_ext(path, "cmd") || has_ext(path, "bat") {
  287. if let Some(resolved) = resolve_cmd(path) {
  288. return Some(resolved);
  289. }
  290. }
  291. if path.extension().is_none() {
  292. let cmd = path.with_extension("cmd");
  293. if cmd.exists() {
  294. if let Some(resolved) = resolve_cmd(&cmd) {
  295. return Some(resolved);
  296. }
  297. }
  298. let bat = path.with_extension("bat");
  299. if bat.exists() {
  300. if let Some(resolved) = resolve_cmd(&bat) {
  301. return Some(resolved);
  302. }
  303. }
  304. }
  305. }
  306. if !key.is_empty() {
  307. for path in &paths {
  308. let dirs = [
  309. path.parent(),
  310. path.parent().and_then(|dir| dir.parent()),
  311. path.parent()
  312. .and_then(|dir| dir.parent())
  313. .and_then(|dir| dir.parent()),
  314. ];
  315. for dir in dirs.into_iter().flatten() {
  316. if let Ok(entries) = std::fs::read_dir(dir) {
  317. for entry in entries.flatten() {
  318. let candidate = entry.path();
  319. if !has_ext(&candidate, "exe") {
  320. continue;
  321. }
  322. let Some(stem) = candidate.file_stem().and_then(|v| v.to_str()) else {
  323. continue;
  324. };
  325. let name = stem
  326. .chars()
  327. .filter(|v| v.is_ascii_alphanumeric())
  328. .flat_map(|v| v.to_lowercase())
  329. .collect::<String>();
  330. if name.contains(&key) || key.contains(&name) {
  331. return Some(candidate.to_string_lossy().to_string());
  332. }
  333. }
  334. }
  335. }
  336. }
  337. }
  338. paths.first().map(|path| path.to_string_lossy().to_string())
  339. };
  340. let list = candidates(app_name);
  341. for query in &list {
  342. if let Some(path) = resolve_where(query) {
  343. return Some(path);
  344. }
  345. }
  346. let mut exes = Vec::<String>::new();
  347. for query in &list {
  348. let query = query.trim().trim_matches('"');
  349. if query.is_empty() {
  350. continue;
  351. }
  352. let name = Path::new(query)
  353. .file_name()
  354. .and_then(|v| v.to_str())
  355. .unwrap_or(query);
  356. let exe = if name.to_ascii_lowercase().ends_with(".exe") {
  357. name.to_string()
  358. } else {
  359. format!("{name}.exe")
  360. };
  361. if exes.iter().any(|v| v.eq_ignore_ascii_case(&exe)) {
  362. continue;
  363. }
  364. exes.push(exe);
  365. }
  366. for exe in exes {
  367. if let Some(path) = reg_app_path(&exe) {
  368. return Some(path);
  369. }
  370. }
  371. None
  372. }
  373. pub fn open_in_powershell(path: String) -> Result<(), String> {
  374. let path = PathBuf::from(path);
  375. let dir = if path.is_dir() {
  376. path
  377. } else if let Some(parent) = path.parent() {
  378. parent.to_path_buf()
  379. } else {
  380. std::env::current_dir()
  381. .map_err(|e| format!("Failed to determine current directory: {e}"))?
  382. };
  383. Command::new("powershell.exe")
  384. .creation_flags(CREATE_NEW_CONSOLE)
  385. .current_dir(dir)
  386. .args(["-NoExit"])
  387. .spawn()
  388. .map_err(|e| format!("Failed to start PowerShell: {e}"))?;
  389. Ok(())
  390. }