| 1 | use crate::archive_ui::*; |
| 2 | use std::{ |
| 3 | collections::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_WARNING: &str = "파일을 디스크에 완전히 저장했는지 확인하지 못했습니다."; |
| 13 | pub const CLEANUP_WARNING: &str = |
| 14 | "임시 파일을 지우지 못했습니다. 풀 위치 폴더에 남은 임시 파일이 있을 수 있습니다."; |
| 15 | pub const INTERNAL: &str = "내부 오류가 발생했습니다. 프로그램을 다시 시작해 주세요"; |
| 16 | pub const FOLDER_ERROR: &str = "풀 위치 폴더를 만들 수 없습니다. 접근 권한을 확인하세요"; |
| 17 | |
| 18 | pub fn error_text(code: ErrorCode) -> &'static str { |
| 19 | match code { |
| 20 | ErrorCode::Integrity => "압축파일이 손상됐습니다", |
| 21 | ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다", |
| 22 | ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다", |
| 23 | ErrorCode::WrongPassword => "암호가 올바르지 않습니다", |
| 24 | ErrorCode::UnsafePath => "파일 경로의 안전성을 확인할 수 없어 중단했습니다", |
| 25 | ErrorCode::Conflict => "같은 이름의 파일이 이미 있습니다. 다른 폴더를 선택하세요", |
| 26 | ErrorCode::Limit => "처리 한도를 초과했습니다", |
| 27 | ErrorCode::Io => "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요", |
| 28 | ErrorCode::DiskFull => "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요", |
| 29 | ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요", |
| 30 | ErrorCode::InvalidRequest => "풀 위치와 선택한 항목을 확인하세요", |
| 31 | ErrorCode::Protocol | ErrorCode::Internal => INTERNAL, |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | pub fn progress_text(stage: Stage, creating: bool) -> &'static str { |
| 36 | match stage { |
| 37 | Stage::Scan | Stage::Read => "압축파일을 읽는 중", |
| 38 | Stage::Decode if creating => "압축하는 중", |
| 39 | Stage::Decode => "압축을 푸는 중", |
| 40 | Stage::Write => "파일을 저장하는 중", |
| 41 | Stage::Verify => "확인하는 중", |
| 42 | Stage::Commit => "마무리하는 중", |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub fn bytes_text(bytes: u64) -> String { |
| 47 | for (unit, size) in [("GB", 1_u64 << 30), ("MB", 1 << 20), ("KB", 1 << 10)] { |
| 48 | if bytes >= size { |
| 49 | return format!("{:.1} {unit}", bytes as f64 / size as f64); |
| 50 | } |
| 51 | } |
| 52 | format!("{bytes} B") |
| 53 | } |
| 54 | |
| 55 | pub fn middle_text(text: &str, max_chars: usize) -> String { |
| 56 | let chars = text.chars().collect::<Vec<_>>(); |
| 57 | if chars.len() <= max_chars || max_chars < 5 { |
| 58 | return text.into(); |
| 59 | } |
| 60 | let left = (max_chars - 1) / 2; |
| 61 | chars[..left] |
| 62 | .iter() |
| 63 | .chain(std::iter::once(&'…')) |
| 64 | .chain(chars[chars.len() - (max_chars - left - 1)..].iter()) |
| 65 | .collect() |
| 66 | } |
| 67 | |
| 68 | pub fn default_destination(archive: &Path) -> PathBuf { |
| 69 | let name = archive.file_name().unwrap_or_default().to_string_lossy(); |
| 70 | let lower = name.to_ascii_lowercase(); |
| 71 | let stem = if lower.ends_with(".tar.gz") { |
| 72 | &name[..name.len() - 7] |
| 73 | } else { |
| 74 | name.rsplit_once('.') |
| 75 | .map_or(name.as_ref(), |(stem, _)| stem) |
| 76 | }; |
| 77 | archive.with_file_name(if stem.is_empty() { |
| 78 | "압축 해제" |
| 79 | } else { |
| 80 | stem |
| 81 | }) |
| 82 | } |
| 83 | |
| 84 | pub fn prepare_destination(path: &Path, automatic: bool) -> io::Result<bool> { |
| 85 | match fs::symlink_metadata(path) { |
| 86 | Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(false), |
| 87 | Ok(_) => Err(io::Error::other(FOLDER_ERROR)), |
| 88 | Err(error) if error.kind() == io::ErrorKind::NotFound && automatic => { |
| 89 | let mut builder = fs::DirBuilder::new(); |
| 90 | #[cfg(unix)] |
| 91 | { |
| 92 | use std::os::unix::fs::DirBuilderExt; |
| 93 | builder.mode(0o700); |
| 94 | } |
| 95 | builder.create(path)?; |
| 96 | Ok(true) |
| 97 | } |
| 98 | Err(error) => Err(error), |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | pub fn remove_owned_empty(path: &Path) { |
| 103 | // 이번 요청에서 만든 폴더만 호출하며 비어 있지 않으면 보존함. |
| 104 | let _ = fs::remove_dir(path); |
| 105 | } |
| 106 | |
| 107 | fn requested(entry: &Entry, selection: &Selection) -> bool { |
| 108 | match selection { |
| 109 | Selection::All => true, |
| 110 | Selection::EntryIds(ids) => ids.contains(&entry.id), |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | pub fn target_files( |
| 115 | entries: &[Entry], |
| 116 | selection: &Selection, |
| 117 | gzip: Option<&str>, |
| 118 | ) -> Option<BTreeSet<String>> { |
| 119 | let mut names = BTreeSet::new(); |
| 120 | for entry in entries |
| 121 | .iter() |
| 122 | .filter(|entry| entry.kind == Kind::File && requested(entry, selection)) |
| 123 | { |
| 124 | if !names.insert(gzip.unwrap_or(&entry.name).replace('\\', "/")) { |
| 125 | return None; |
| 126 | } |
| 127 | } |
| 128 | Some(names) |
| 129 | } |
| 130 | |
| 131 | pub fn target_directories(entries: &[Entry], selection: &Selection) -> BTreeSet<String> { |
| 132 | let mut directories = BTreeSet::new(); |
| 133 | for entry in entries.iter().filter(|entry| { |
| 134 | matches!(entry.kind, Kind::File | Kind::Directory) && requested(entry, selection) |
| 135 | }) { |
| 136 | let normalized = entry.name.replace('\\', "/"); |
| 137 | let name = normalized.trim_end_matches('/'); |
| 138 | if entry.kind == Kind::Directory { |
| 139 | directories.insert(name.to_owned()); |
| 140 | } |
| 141 | let mut parent = name; |
| 142 | while let Some((directory, _)) = parent.rsplit_once('/') { |
| 143 | directories.insert(directory.to_owned()); |
| 144 | parent = directory; |
| 145 | } |
| 146 | } |
| 147 | directories |
| 148 | } |
| 149 | |
| 150 | pub fn warnings( |
| 151 | terminal: Option<&Terminal>, |
| 152 | confirmed: bool, |
| 153 | targets: Option<&BTreeSet<String>>, |
| 154 | directories: &BTreeSet<String>, |
| 155 | outputs: &[(String, Disposition)], |
| 156 | ) -> Vec<&'static str> { |
| 157 | let Some(t) = terminal.filter(|_| confirmed) else { |
| 158 | return vec![UNCERTAIN]; |
| 159 | }; |
| 160 | let created = outputs |
| 161 | .iter() |
| 162 | .filter(|(_, state)| *state == Disposition::Created) |
| 163 | .map(|(name, _)| name.replace('\\', "/")) |
| 164 | .collect::<BTreeSet<_>>(); |
| 165 | let created_reports = outputs |
| 166 | .iter() |
| 167 | .filter(|(_, state)| *state == Disposition::Created) |
| 168 | .count(); |
| 169 | let uncertain = t.publication == Publication::Uncertain |
| 170 | || outputs |
| 171 | .iter() |
| 172 | .any(|(_, state)| *state == Disposition::CommitUncertain) |
| 173 | || created.len() != created_reports |
| 174 | || created_reports as u64 != t.created_count |
| 175 | || (t.publication == Publication::None && !created.is_empty()); |
| 176 | let retained = t.retained_partial_count > 0 |
| 177 | || outputs |
| 178 | .iter() |
| 179 | .any(|(_, state)| *state == Disposition::PartialRetained); |
| 180 | let mut result = Vec::new(); |
| 181 | let mut all_saved_with_leftovers = false; |
| 182 | if uncertain { |
| 183 | result.push(UNCERTAIN); |
| 184 | } else if let Some(targets) = targets { |
| 185 | let files = created |
| 186 | .difference(directories) |
| 187 | .cloned() |
| 188 | .collect::<BTreeSet<_>>(); |
| 189 | let saved = targets.intersection(&files).count(); |
| 190 | let unknown = !targets.is_disjoint(directories) |
| 191 | || created |
| 192 | .iter() |
| 193 | .any(|name| !targets.contains(name) && !directories.contains(name)); |
| 194 | if unknown { |
| 195 | result.push(UNCERTAIN); |
| 196 | } else if !targets.is_empty() && saved == targets.len() && retained { |
| 197 | result.push(LEFTOVERS); |
| 198 | all_saved_with_leftovers = true; |
| 199 | } else if saved > 0 && saved < targets.len() && t.outcome != Outcome::Completed { |
| 200 | result.push(PARTIAL); |
| 201 | } else if (saved == 0 && !files.is_empty()) |
| 202 | || (retained && saved == 0) |
| 203 | || (t.outcome == Outcome::Completed && saved != targets.len()) |
| 204 | { |
| 205 | result.push(UNCERTAIN); |
| 206 | } |
| 207 | } else { |
| 208 | result.push(UNCERTAIN); |
| 209 | } |
| 210 | if matches!(t.durability, Durability::Failed | Durability::Unconfirmed) { |
| 211 | result.push(SYNC_WARNING); |
| 212 | } |
| 213 | if (retained || t.cleanup != Cleanup::Complete) && !all_saved_with_leftovers { |
| 214 | result.push(CLEANUP_WARNING); |
| 215 | } |
| 216 | result |
| 217 | } |
| 218 | |
| 219 | pub fn definitely_unsaved( |
| 220 | t: Option<&Terminal>, |
| 221 | confirmed: bool, |
| 222 | outputs: &[(String, Disposition)], |
| 223 | ) -> bool { |
| 224 | t.is_some_and(|t| { |
| 225 | confirmed |
| 226 | && t.publication == Publication::None |
| 227 | && t.created_count == 0 |
| 228 | && t.retained_partial_count == 0 |
| 229 | && t.cleanup == Cleanup::Complete |
| 230 | && outputs |
| 231 | .iter() |
| 232 | .all(|(_, state)| *state == Disposition::Removed) |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | #[derive(Clone)] |
| 237 | pub struct BrowserEntry { |
| 238 | pub path: PathBuf, |
| 239 | pub name: String, |
| 240 | pub directory: bool, |
| 241 | pub link: bool, |
| 242 | } |
| 243 | |
| 244 | pub fn directory_entries(path: &Path) -> io::Result<Vec<BrowserEntry>> { |
| 245 | if fs::symlink_metadata(path)?.file_type().is_symlink() { |
| 246 | return Err(io::Error::other("링크 폴더는 탐색하지 않음")); |
| 247 | } |
| 248 | let mut entries = Vec::new(); |
| 249 | for item in fs::read_dir(path)? { |
| 250 | let item = item?; |
| 251 | let kind = item.file_type()?; |
| 252 | entries.push(BrowserEntry { |
| 253 | path: item.path(), |
| 254 | name: item.file_name().to_string_lossy().into(), |
| 255 | directory: kind.is_dir(), |
| 256 | link: kind.is_symlink(), |
| 257 | }); |
| 258 | } |
| 259 | entries.sort_by(|a, b| { |
| 260 | b.directory |
| 261 | .cmp(&a.directory) |
| 262 | .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) |
| 263 | }); |
| 264 | Ok(entries) |
| 265 | } |
| 266 | |
| 267 | pub fn home_directory() -> PathBuf { |
| 268 | std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }) |
| 269 | .map(PathBuf::from) |
| 270 | .filter(|p| p.is_absolute()) |
| 271 | .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"))) |
| 272 | } |
| 273 | |
| 274 | pub fn shortcuts() -> Vec<(String, PathBuf)> { |
| 275 | let home = home_directory(); |
| 276 | let mut paths = vec![("홈".into(), home.clone())]; |
| 277 | for (label, candidates) in [ |
| 278 | ("바탕 화면", ["Desktop", "바탕화면"]), |
| 279 | ("문서", ["Documents", "문서"]), |
| 280 | ("다운로드", ["Downloads", "다운로드"]), |
| 281 | ] { |
| 282 | if let Some(path) = candidates |
| 283 | .iter() |
| 284 | .map(|name| home.join(name)) |
| 285 | .find(|p| p.is_dir()) |
| 286 | { |
| 287 | paths.push((label.into(), path)); |
| 288 | } |
| 289 | } |
| 290 | #[cfg(windows)] |
| 291 | for drive in b'A'..=b'Z' { |
| 292 | let path = PathBuf::from(format!("{}:\\", drive as char)); |
| 293 | if path.is_dir() { |
| 294 | paths.push((format!("{}:", drive as char), path)); |
| 295 | } |
| 296 | } |
| 297 | paths |
| 298 | } |
| 299 | |
| 300 | pub fn folder_command(path: &Path) -> std::process::Command { |
| 301 | let mut command = std::process::Command::new(if cfg!(windows) { |
| 302 | "explorer" |
| 303 | } else { |
| 304 | "xdg-open" |
| 305 | }); |
| 306 | command.arg(path); |
| 307 | command |
| 308 | } |
| 309 | |
| 310 | pub const UNCONFIRMED_FINISH: &str = |
| 311 | "작업이 정상적으로 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요"; |
| 312 | |
| 313 | pub fn client_error_text(error: &str) -> &'static str { |
| 314 | if error.starts_with("작업자 종료 결과를 확인할 수 없습니다") { |
| 315 | UNCONFIRMED_FINISH |
| 316 | } else { |
| 317 | INTERNAL |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | pub fn activity_text(model: &Model, creating: bool) -> &'static str { |
| 322 | if model.terminal.is_some() |
| 323 | || matches!( |
| 324 | model.cancel, |
| 325 | Some(CancelStatus::TooLate | CancelStatus::Finished) |
| 326 | ) |
| 327 | { |
| 328 | "마무리하는 중" |
| 329 | } else if model.cancellation_requested() || model.cancel.is_some() { |
| 330 | "취소하는 중..." |
| 331 | } else if model.challenge.is_some() { |
| 332 | "암호를 입력하세요" |
| 333 | } else { |
| 334 | model |
| 335 | .progress |
| 336 | .map_or("압축파일을 읽는 중", |(stage, _, _, _)| { |
| 337 | progress_text(stage, creating) |
| 338 | }) |
| 339 | } |
| 340 | } |