Skip to content

Commit ea333a9

Browse files
author
Mikachu2333
committed
improve path resolve
1 parent 2d3d234 commit ea333a9

File tree

1 file changed

+68
-13
lines changed

1 file changed

+68
-13
lines changed

src/types.rs

Lines changed: 68 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
1-
use std::{collections::HashMap, env, path::PathBuf};
1+
use std::{
2+
collections::HashMap,
3+
env,
4+
path::{Component, PathBuf, Prefix},
5+
};
26
use windows_hotkeys::keys::{ModKey, VKey};
37

8+
use crate::msgbox::warn_msgbox;
9+
410
/// 嵌入式 ScreenCapture 程序的相关信息与程序信息
511
pub static RES_HASH_SHA1: &str = "5857D9E31E9B29739FA051DF537F36E8C1986528";
612
pub static RES_VERSION: &str = "2.3.3";
@@ -456,23 +462,72 @@ pub fn resolve_path(path: impl ToString, should_dir: bool) -> PathBuf {
456462
.unwrap()
457463
.to_path_buf(),
458464
x => {
459-
// 验证路径是否存在
460-
let temp = PathBuf::from(x);
465+
let mut path = PathBuf::from(x.replace("/", "\\"));
466+
let base_dir = env::current_dir().unwrap_or_default();
467+
468+
let is_absolute = {
469+
let mut components = path.components();
470+
if let Some(Component::Prefix(prefix_component)) = components.next() {
471+
let has_root_dir = matches!(components.next(), Some(Component::RootDir));
472+
if DEBUG {
473+
dbg!(has_root_dir);
474+
}
475+
if !has_root_dir {
476+
false
477+
} else {
478+
if DEBUG {
479+
dbg!(prefix_component.kind());
480+
}
481+
482+
matches!(
483+
prefix_component.kind(),
484+
Prefix::VerbatimUNC(..)
485+
| Prefix::UNC(..)
486+
| Prefix::VerbatimDisk(..)
487+
| Prefix::Disk(_)
488+
| Prefix::DeviceNS(..)
489+
| Prefix::Verbatim(_)
490+
)
491+
}
492+
} else {
493+
path.is_absolute()
494+
}
495+
};
496+
497+
if !is_absolute {
498+
if path.starts_with("~") {
499+
if let Ok(home_dir) = std::env::var("USERPROFILE") {
500+
let mut new_path = PathBuf::from(home_dir);
501+
let remaining = path.strip_prefix("~/").ok();
502+
if let Some(rem) = remaining {
503+
new_path.push(rem);
504+
path = new_path;
505+
} else if *path == *"~" {
506+
path = new_path;
507+
} else {
508+
// "~something"
509+
path = base_dir.join(path);
510+
}
511+
}
512+
} else if path.starts_with(".") {
513+
let remaining = path.strip_prefix(".\\").ok();
514+
path = base_dir.join(remaining.unwrap());
515+
} else {
516+
path = base_dir.join(path);
517+
}
518+
}
461519

462-
if temp.exists() {
463-
temp.canonicalize().unwrap()
520+
let canonical = path.canonicalize().unwrap_or_default();
521+
if canonical.exists() {
522+
canonical
464523
} else {
465524
if should_dir {
466-
crate::msgbox::warn_msgbox(
467-
format!(
468-
"{}\nPath you give is valid, so we use EMPTY as default.",
469-
&path
470-
),
471-
"",
472-
0,
525+
warn_msgbox(
526+
format!("{}\nPath is invalid, use EMPTY as default.", path.display()),
527+
"Warn Path Invalid",
528+
5,
473529
);
474530
}
475-
476531
PathBuf::new()
477532
}
478533
}

0 commit comments

Comments
 (0)