| 1 | use crate::archive_ui::*; |
| 2 | use std::{ |
| 3 | collections::{BTreeMap, BTreeSet}, |
| 4 | fs, io, |
| 5 | path::{Path, PathBuf}, |
| 6 | }; |
| 7 | |
| 8 | pub const UNCERTAIN: &str = "저장이 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요."; |
| 9 | pub const PARTIAL: &str = "일부 파일만 풀렸습니다. 풀린 파일은 풀 위치 폴더에 남아 있습니다."; |
| 10 | pub const LEFTOVERS: &str = |
| 11 | "선택한 파일은 모두 저장했지만 임시 파일을 지우지 못했습니다. 풀 위치 폴더를 확인하세요."; |
| 12 | pub const SYNC_FAILED: &str = |
| 13 | "파일을 디스크에 완전히 저장하지 못했습니다. 풀 위치 폴더를 확인하세요."; |
| 14 | pub const SYNC_WARNING: &str = "파일을 디스크에 완전히 저장했는지 확인하지 못했습니다."; |
| 15 | pub const CLEANUP_WARNING: &str = |
| 16 | "임시 파일을 지우지 못했습니다. 풀 위치 폴더에 남은 임시 파일이 있을 수 있습니다."; |
| 17 | pub const INTERNAL: &str = "내부 오류가 발생했습니다. 프로그램을 다시 시작해 주세요"; |
| 18 | pub const FOLDER_ERROR: &str = "풀 위치 폴더를 만들 수 없습니다. 접근 권한을 확인하세요"; |
| 19 | |
| 20 | pub fn error_text(code: ErrorCode) -> &'static str { |
| 21 | match code { |
| 22 | ErrorCode::RecoveryIncomplete => "일부 항목만 복구했습니다. 복구본과 경고를 확인하세요.", |
| 23 | ErrorCode::RecoveryImpossible => "복구 가능한 항목이 없습니다.", |
| 24 | ErrorCode::MissingVolume => { |
| 25 | "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 .001을 다시 여세요" |
| 26 | } |
| 27 | ErrorCode::Integrity => "압축파일이 손상됐습니다", |
| 28 | ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다", |
| 29 | ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다", |
| 30 | ErrorCode::WrongPassword => "암호가 올바르지 않습니다", |
| 31 | ErrorCode::UnsafePath => "파일 경로의 안전성을 확인할 수 없어 중단했습니다", |
| 32 | ErrorCode::Conflict => "같은 이름의 파일이 이미 있습니다. 다른 폴더를 선택하세요", |
| 33 | ErrorCode::Limit => "처리 한도를 초과했습니다", |
| 34 | ErrorCode::Io => "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요", |
| 35 | ErrorCode::DiskFull => "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요", |
| 36 | ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요", |
| 37 | ErrorCode::InvalidRequest => "풀 위치와 선택한 항목을 확인하세요", |
| 38 | ErrorCode::Protocol | ErrorCode::Internal => INTERNAL, |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | pub fn progress_text(stage: Stage, creating: bool) -> &'static str { |
| 43 | match stage { |
| 44 | Stage::Scan | Stage::Read => "압축파일을 읽는 중", |
| 45 | Stage::Decode if creating => "압축하는 중", |
| 46 | Stage::Decode => "압축을 푸는 중", |
| 47 | Stage::Write => "파일을 저장하는 중", |
| 48 | Stage::Verify => "확인하는 중", |
| 49 | Stage::Commit => "마무리하는 중", |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | pub fn bytes_text(bytes: u64) -> String { |
| 54 | for (unit, size) in [("GB", 1_u64 << 30), ("MB", 1 << 20), ("KB", 1 << 10)] { |
| 55 | if bytes >= size { |
| 56 | return format!("{:.1} {unit}", bytes as f64 / size as f64); |
| 57 | } |
| 58 | } |
| 59 | format!("{bytes} B") |
| 60 | } |
| 61 | |
| 62 | pub fn middle_text(text: &str, max_chars: usize) -> String { |
| 63 | let chars = text.chars().collect::<Vec<_>>(); |
| 64 | if chars.len() <= max_chars || max_chars < 5 { |
| 65 | return text.into(); |
| 66 | } |
| 67 | let left = (max_chars - 1) / 2; |
| 68 | chars[..left] |
| 69 | .iter() |
| 70 | .chain(std::iter::once(&'…')) |
| 71 | .chain(chars[chars.len() - (max_chars - left - 1)..].iter()) |
| 72 | .collect() |
| 73 | } |
| 74 | |
| 75 | pub fn default_destination(archive: &Path) -> PathBuf { |
| 76 | let name = archive.file_name().unwrap_or_default().to_string_lossy(); |
| 77 | let lower = name.to_ascii_lowercase(); |
| 78 | let compound = [".tar.bz2", ".tar.gz", ".tar.xz"] |
| 79 | .into_iter() |
| 80 | .find(|suffix| lower.ends_with(suffix)); |
| 81 | let stem = if let Some(suffix) = compound { |
| 82 | &name[..name.len() - suffix.len()] |
| 83 | } else { |
| 84 | name.rsplit_once('.') |
| 85 | .map_or(name.as_ref(), |(stem, _)| stem) |
| 86 | }; |
| 87 | archive.with_file_name(if stem.is_empty() { |
| 88 | "압축 해제" |
| 89 | } else { |
| 90 | stem |
| 91 | }) |
| 92 | } |
| 93 | |
| 94 | pub fn prepare_destination(path: &Path, automatic: bool) -> io::Result<bool> { |
| 95 | match fs::symlink_metadata(path) { |
| 96 | Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(false), |
| 97 | Ok(_) => Err(io::Error::other(FOLDER_ERROR)), |
| 98 | Err(error) if error.kind() == io::ErrorKind::NotFound && automatic => { |
| 99 | let mut builder = fs::DirBuilder::new(); |
| 100 | #[cfg(unix)] |
| 101 | { |
| 102 | use std::os::unix::fs::DirBuilderExt; |
| 103 | builder.mode(0o700); |
| 104 | } |
| 105 | builder.create(path)?; |
| 106 | Ok(true) |
| 107 | } |
| 108 | Err(error) => Err(error), |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | pub fn remove_owned_empty(path: &Path) { |
| 113 | // 이번 요청에서 만든 폴더만 호출하며 비어 있지 않으면 보존함. |
| 114 | let _ = fs::remove_dir(path); |
| 115 | } |
| 116 | |
| 117 | fn requested(entry: &Entry, selection: &Selection) -> bool { |
| 118 | match selection { |
| 119 | Selection::All => true, |
| 120 | Selection::EntryIds(ids) => ids.contains(&entry.id), |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | pub fn target_files( |
| 125 | entries: &[Entry], |
| 126 | selection: &Selection, |
| 127 | gzip: Option<&str>, |
| 128 | ) -> Option<BTreeSet<String>> { |
| 129 | let mut names = BTreeSet::new(); |
| 130 | for entry in entries |
| 131 | .iter() |
| 132 | .filter(|entry| entry.kind == Kind::File && requested(entry, selection)) |
| 133 | { |
| 134 | if !names.insert(gzip.unwrap_or(&entry.name).replace('\\', "/")) { |
| 135 | return None; |
| 136 | } |
| 137 | } |
| 138 | Some(names) |
| 139 | } |
| 140 | |
| 141 | pub fn resolved_targets( |
| 142 | targets: Option<&BTreeSet<String>>, |
| 143 | entries: &[Entry], |
| 144 | gzip: Option<&str>, |
| 145 | resolutions: &[Resolution], |
| 146 | ) -> Option<BTreeSet<String>> { |
| 147 | let mut names = targets?.clone(); |
| 148 | let entries: BTreeMap<_, _> = entries.iter().map(|entry| (entry.id, entry)).collect(); |
| 149 | for resolution in resolutions { |
| 150 | let entry = entries.get(&resolution.entry_id)?; |
| 151 | let original = gzip.unwrap_or(&entry.name).replace('\\', "/"); |
| 152 | if !names.remove(&original) { |
| 153 | return None; |
| 154 | } |
| 155 | } |
| 156 | for resolution in resolutions { |
| 157 | if resolution.choice != ConflictChoice::Skip |
| 158 | && !names.insert(resolution.relative_name.replace('\\', "/")) |
| 159 | { |
| 160 | return None; |
| 161 | } |
| 162 | } |
| 163 | Some(names) |
| 164 | } |
| 165 | |
| 166 | pub fn target_directories(entries: &[Entry], selection: &Selection) -> BTreeSet<String> { |
| 167 | let mut directories = BTreeSet::new(); |
| 168 | for entry in entries.iter().filter(|entry| { |
| 169 | matches!(entry.kind, Kind::File | Kind::Directory) && requested(entry, selection) |
| 170 | }) { |
| 171 | let normalized = entry.name.replace('\\', "/"); |
| 172 | let name = normalized.trim_end_matches('/'); |
| 173 | if entry.kind == Kind::Directory { |
| 174 | directories.insert(name.to_owned()); |
| 175 | } |
| 176 | let mut parent = name; |
| 177 | while let Some((directory, _)) = parent.rsplit_once('/') { |
| 178 | directories.insert(directory.to_owned()); |
| 179 | parent = directory; |
| 180 | } |
| 181 | } |
| 182 | directories |
| 183 | } |
| 184 | |
| 185 | pub fn durability_warning(durability: Durability) -> Option<&'static str> { |
| 186 | match durability { |
| 187 | Durability::Failed => Some(SYNC_FAILED), |
| 188 | Durability::Unconfirmed => Some(SYNC_WARNING), |
| 189 | _ => None, |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | pub fn warnings( |
| 194 | terminal: Option<&Terminal>, |
| 195 | confirmed: bool, |
| 196 | targets: Option<&BTreeSet<String>>, |
| 197 | directories: &BTreeSet<String>, |
| 198 | outputs: &[(String, Disposition)], |
| 199 | ) -> Vec<&'static str> { |
| 200 | let mut result = publication_warnings(terminal, confirmed, targets, directories, outputs); |
| 201 | if let Some(warning) = terminal |
| 202 | .filter(|_| confirmed) |
| 203 | .and_then(|t| durability_warning(t.durability)) |
| 204 | { |
| 205 | result.push(warning); |
| 206 | } |
| 207 | result |
| 208 | } |
| 209 | |
| 210 | pub fn publication_warnings( |
| 211 | terminal: Option<&Terminal>, |
| 212 | confirmed: bool, |
| 213 | targets: Option<&BTreeSet<String>>, |
| 214 | directories: &BTreeSet<String>, |
| 215 | outputs: &[(String, Disposition)], |
| 216 | ) -> Vec<&'static str> { |
| 217 | let Some(t) = terminal.filter(|_| confirmed) else { |
| 218 | return vec![UNCERTAIN]; |
| 219 | }; |
| 220 | let created = outputs |
| 221 | .iter() |
| 222 | .filter(|(_, state)| *state == Disposition::Created) |
| 223 | .map(|(name, _)| name.replace('\\', "/")) |
| 224 | .collect::<BTreeSet<_>>(); |
| 225 | let created_reports = outputs |
| 226 | .iter() |
| 227 | .filter(|(_, state)| *state == Disposition::Created) |
| 228 | .count(); |
| 229 | let uncertain = t.publication == Publication::Uncertain |
| 230 | || outputs |
| 231 | .iter() |
| 232 | .any(|(_, state)| *state == Disposition::CommitUncertain) |
| 233 | || created.len() != created_reports |
| 234 | || created_reports as u64 != t.created_count |
| 235 | || (t.publication == Publication::None && !created.is_empty()); |
| 236 | let retained = t.retained_partial_count > 0 |
| 237 | || outputs |
| 238 | .iter() |
| 239 | .any(|(_, state)| *state == Disposition::PartialRetained); |
| 240 | let mut result = Vec::new(); |
| 241 | let mut all_saved_with_leftovers = false; |
| 242 | if uncertain { |
| 243 | result.push(UNCERTAIN); |
| 244 | } else if let Some(targets) = targets { |
| 245 | let files = created |
| 246 | .difference(directories) |
| 247 | .cloned() |
| 248 | .collect::<BTreeSet<_>>(); |
| 249 | let saved = targets.intersection(&files).count(); |
| 250 | let unknown = !targets.is_disjoint(directories) |
| 251 | || created |
| 252 | .iter() |
| 253 | .any(|name| !targets.contains(name) && !directories.contains(name)); |
| 254 | if unknown { |
| 255 | result.push(UNCERTAIN); |
| 256 | } else if !targets.is_empty() && saved == targets.len() && retained { |
| 257 | result.push(LEFTOVERS); |
| 258 | all_saved_with_leftovers = true; |
| 259 | } else if saved > 0 && saved < targets.len() && t.outcome != Outcome::Completed { |
| 260 | result.push(PARTIAL); |
| 261 | } else if (saved == 0 && !files.is_empty()) |
| 262 | || (retained && saved == 0) |
| 263 | || (t.outcome == Outcome::Completed && saved != targets.len()) |
| 264 | { |
| 265 | result.push(UNCERTAIN); |
| 266 | } |
| 267 | } else { |
| 268 | result.push(UNCERTAIN); |
| 269 | } |
| 270 | if (retained || t.cleanup != Cleanup::Complete) && !all_saved_with_leftovers { |
| 271 | result.push(CLEANUP_WARNING); |
| 272 | } |
| 273 | result |
| 274 | } |
| 275 | |
| 276 | pub fn definitely_unsaved( |
| 277 | t: Option<&Terminal>, |
| 278 | confirmed: bool, |
| 279 | outputs: &[(String, Disposition)], |
| 280 | ) -> bool { |
| 281 | t.is_some_and(|t| { |
| 282 | confirmed |
| 283 | && t.publication == Publication::None |
| 284 | && t.created_count == 0 |
| 285 | && t.retained_partial_count == 0 |
| 286 | && t.cleanup == Cleanup::Complete |
| 287 | && outputs |
| 288 | .iter() |
| 289 | .all(|(_, state)| *state == Disposition::Removed) |
| 290 | }) |
| 291 | } |
| 292 | |
| 293 | #[derive(Clone)] |
| 294 | pub struct BrowserEntry { |
| 295 | pub path: PathBuf, |
| 296 | pub name: String, |
| 297 | pub directory: bool, |
| 298 | pub link: bool, |
| 299 | } |
| 300 | |
| 301 | pub fn directory_entries(path: &Path) -> io::Result<Vec<BrowserEntry>> { |
| 302 | if fs::symlink_metadata(path)?.file_type().is_symlink() { |
| 303 | return Err(io::Error::other("링크 폴더는 탐색하지 않음")); |
| 304 | } |
| 305 | let mut entries = Vec::new(); |
| 306 | for item in fs::read_dir(path)? { |
| 307 | let item = item?; |
| 308 | let kind = item.file_type()?; |
| 309 | entries.push(BrowserEntry { |
| 310 | path: item.path(), |
| 311 | name: item.file_name().to_string_lossy().into(), |
| 312 | directory: kind.is_dir(), |
| 313 | link: kind.is_symlink(), |
| 314 | }); |
| 315 | } |
| 316 | entries.sort_by(|a, b| { |
| 317 | b.directory |
| 318 | .cmp(&a.directory) |
| 319 | .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) |
| 320 | }); |
| 321 | Ok(entries) |
| 322 | } |
| 323 | |
| 324 | pub fn home_directory() -> PathBuf { |
| 325 | std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }) |
| 326 | .map(PathBuf::from) |
| 327 | .filter(|p| p.is_absolute()) |
| 328 | .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"))) |
| 329 | } |
| 330 | |
| 331 | pub fn shortcuts() -> Vec<(String, PathBuf)> { |
| 332 | let home = home_directory(); |
| 333 | let mut paths = vec![("홈".into(), home.clone())]; |
| 334 | for (label, candidates) in [ |
| 335 | ("바탕 화면", ["Desktop", "바탕화면"]), |
| 336 | ("문서", ["Documents", "문서"]), |
| 337 | ("다운로드", ["Downloads", "다운로드"]), |
| 338 | ] { |
| 339 | if let Some(path) = candidates |
| 340 | .iter() |
| 341 | .map(|name| home.join(name)) |
| 342 | .find(|p| p.is_dir()) |
| 343 | { |
| 344 | paths.push((label.into(), path)); |
| 345 | } |
| 346 | } |
| 347 | #[cfg(windows)] |
| 348 | for drive in b'A'..=b'Z' { |
| 349 | let path = PathBuf::from(format!("{}:\\", drive as char)); |
| 350 | if path.is_dir() { |
| 351 | paths.push((format!("{}:", drive as char), path)); |
| 352 | } |
| 353 | } |
| 354 | paths |
| 355 | } |
| 356 | |
| 357 | pub fn folder_command(path: &Path) -> std::process::Command { |
| 358 | let mut command = std::process::Command::new(if cfg!(windows) { |
| 359 | "explorer" |
| 360 | } else { |
| 361 | "xdg-open" |
| 362 | }); |
| 363 | command.arg(path); |
| 364 | command |
| 365 | } |
| 366 | |
| 367 | pub const UNCONFIRMED_FINISH: &str = |
| 368 | "작업이 정상적으로 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요"; |
| 369 | |
| 370 | pub fn client_error_text(error: &str) -> &'static str { |
| 371 | if error.starts_with("작업자 종료 결과를 확인할 수 없습니다") { |
| 372 | UNCONFIRMED_FINISH |
| 373 | } else { |
| 374 | INTERNAL |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | pub fn activity_text(model: &Model, creating: bool) -> &'static str { |
| 379 | if model.terminal.is_some() |
| 380 | || matches!( |
| 381 | model.cancel, |
| 382 | Some(CancelStatus::TooLate | CancelStatus::Finished) |
| 383 | ) |
| 384 | { |
| 385 | "마무리하는 중" |
| 386 | } else if model.cancellation_requested() || model.cancel.is_some() { |
| 387 | "취소하는 중..." |
| 388 | } else if model.conflict.is_some() { |
| 389 | "파일 충돌 선택 대기 중" |
| 390 | } else if model.challenge.is_some() { |
| 391 | "암호를 입력하세요" |
| 392 | } else { |
| 393 | model |
| 394 | .progress |
| 395 | .map_or("압축파일을 읽는 중", |(stage, _, _, _)| { |
| 396 | progress_text(stage, creating) |
| 397 | }) |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | pub fn valid_output_leaf(name: &str) -> bool { |
| 402 | valid_leaf(name) && worker_protocol::archive::valid_name(name, false).is_ok() |
| 403 | } |
| 404 | |
| 405 | pub fn gzip_output_name(archive: &Path) -> String { |
| 406 | let file_name = archive |
| 407 | .file_name() |
| 408 | .and_then(|name| name.to_str()) |
| 409 | .unwrap_or(""); |
| 410 | let candidate = file_name |
| 411 | .rsplit_once('.') |
| 412 | .filter(|(_, suffix)| suffix.eq_ignore_ascii_case("gz")) |
| 413 | .map_or(file_name, |(stem, _)| stem); |
| 414 | if valid_output_leaf(candidate) { |
| 415 | candidate.to_owned() |
| 416 | } else { |
| 417 | "압축 해제 파일".into() |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | pub fn operation_text(text: &str, creating: bool) -> String { |
| 422 | if creating { |
| 423 | text.replace("풀 위치", "저장 위치") |
| 424 | .replace("선택한 항목", "추가한 항목") |
| 425 | .replace( |
| 426 | "일부 파일만 풀렸습니다. 풀린 파일은", |
| 427 | "ZIP 파일이 일부만 저장됐습니다. 저장된 파일은", |
| 428 | ) |
| 429 | } else { |
| 430 | text.to_owned() |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | pub fn volume_problem_text(problem: &VolumeProblem) -> String { |
| 435 | fn visible(c: char) -> String { |
| 436 | if c.is_control() || matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') { |
| 437 | c.escape_unicode().to_string() |
| 438 | } else { |
| 439 | c.to_string() |
| 440 | } |
| 441 | } |
| 442 | let name = match &problem.volume { |
| 443 | NativePath::Unix(bytes) => bytes |
| 444 | .utf8_chunks() |
| 445 | .map(|chunk| { |
| 446 | let mut text = chunk.valid().chars().map(visible).collect::<String>(); |
| 447 | for byte in chunk.invalid() { |
| 448 | text.push_str(&format!("\\x{byte:02x}")); |
| 449 | } |
| 450 | text |
| 451 | }) |
| 452 | .collect::<String>(), |
| 453 | NativePath::Windows(units) => char::decode_utf16(units.iter().copied()) |
| 454 | .map(|c| { |
| 455 | c.map(visible) |
| 456 | .unwrap_or_else(|e| format!("\\u{{{:04x}}}", e.unpaired_surrogate())) |
| 457 | }) |
| 458 | .collect::<String>(), |
| 459 | }; |
| 460 | match problem.reason { |
| 461 | VolumeProblemReason::FirstVolumeRequired => format!("첫 조각 {name}을 선택해 다시 여세요."), |
| 462 | VolumeProblemReason::MissingVolume => { |
| 463 | format!("{name} 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 .001을 다시 여세요.") |
| 464 | } |
| 465 | VolumeProblemReason::IncompleteSet => format!( |
| 466 | "{name}의 분할 묶음이 불완전하거나 손상됐습니다. 모든 조각의 존재와 손상을 확인한 뒤 .001을 다시 여세요." |
| 467 | ), |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | pub const SPLIT_SUPPORT: &str = |
| 472 | "분할 7z는 .7z.001부터 열 수 있습니다. 분할 ZIP과 RAR, 분할 압축 만들기는 지원하지 않습니다."; |
| 473 | |
| 474 | pub fn excluded_split(path: &Path) -> bool { |
| 475 | let name = path |
| 476 | .file_name() |
| 477 | .unwrap_or_default() |
| 478 | .to_string_lossy() |
| 479 | .to_ascii_lowercase(); |
| 480 | name.ends_with(".zip.001") || name.ends_with(".z01") || name.ends_with(".rar") |
| 481 | } |