team-ljyzipelo

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