team-ljyzipelo

공개
711줄26 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::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
42pub 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
53pub 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
62pub 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
75pub 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
94pub 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
112pub fn remove_owned_empty(path: &Path) {
113 // 이번 요청에서 만든 폴더만 호출하며 비어 있지 않으면 보존함.
114 let _ = fs::remove_dir(path);
115}
116
117fn requested(entry: &Entry, selection: &Selection) -> bool {
118 match selection {
119 Selection::All => true,
120 Selection::EntryIds(ids) => ids.contains(&entry.id),
121 }
122}
123
124pub 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
141pub 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
166pub 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
185pub 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
193pub 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
210pub 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
276pub 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)]
294pub struct BrowserEntry {
295 pub path: PathBuf,
296 pub name: String,
297 pub directory: bool,
298 pub link: bool,
299}
300
301pub 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
324pub 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
331pub 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
357pub 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
367pub const UNCONFIRMED_FINISH: &str =
368 "작업이 정상적으로 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요";
369
370pub fn client_error_text(error: &str) -> &'static str {
371 if error.starts_with("작업자 종료 결과를 확인할 수 없습니다") {
372 UNCONFIRMED_FINISH
373 } else {
374 INTERNAL
375 }
376}
377
378pub 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
401pub fn valid_output_leaf(name: &str) -> bool {
402 valid_leaf(name) && worker_protocol::archive::valid_name(name, false).is_ok()
403}
404
405pub 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
421pub 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
434pub 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
471pub const SPLIT_SUPPORT: &str =
472 "분할 7z는 .7z.001부터 열 수 있습니다. 분할 ZIP과 RAR, 분할 압축 만들기는 지원하지 않습니다.";
473
474pub 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}
482
483/// 같은 이름이 이미 있으면 `이름 (1)`, `이름 (2)`처럼 비어 있는 이름을 찾음.
484pub fn unique_folder(base: &Path) -> PathBuf {
485 let taken = |path: &Path| fs::symlink_metadata(path).is_ok();
486 if !taken(base) {
487 return base.to_path_buf();
488 }
489 let name = base.file_name().unwrap_or_default().to_string_lossy();
490 (1..)
491 .map(|n| base.with_file_name(format!("{name} ({n})")))
492 .find(|path| !taken(path))
493 .unwrap()
494}
495
496fn private_dir(path: &Path) -> io::Result<()> {
497 let mut builder = fs::DirBuilder::new();
498 #[cfg(unix)]
499 {
500 use std::os::unix::fs::DirBuilderExt;
501 builder.mode(0o700);
502 }
503 builder.create(path)
504}
505
506pub struct OpenRoot {
507 path: PathBuf,
508 handle: fs::File,
509 identity: worker_protocol::protocol::SourceObject,
510}
511
512impl OpenRoot {
513 fn capture(path: PathBuf) -> io::Result<Self> {
514 let handle = open_root_handle(&path)?;
515 // 만든 직후에는 비어 있어야 함. 만든 뒤 핸들을 잡기 전에 다른 폴더로 바뀌었다면
516 // 사용자 데이터가 들어 있을 수 있으므로 원본으로 기록하지 않음.
517 if !worker_protocol::tree_remove::is_empty(&handle, &path)? {
518 return Err(io::Error::other("만든 임시 폴더가 아님"));
519 }
520 let identity = worker_protocol::filesystem::object(&handle)
521 .map_err(|_| io::Error::other("임시 폴더 식별 실패"))?;
522 Ok(Self {
523 path,
524 handle,
525 identity,
526 })
527 }
528
529 pub fn path(&self) -> &Path {
530 &self.path
531 }
532
533 pub fn is_current(&self) -> bool {
534 // 원본 핸들을 유지해 삭제된 inode가 재사용되어도 같다고 판정하지 않음.
535 self.handle.metadata().is_ok()
536 && open_root_handle(&self.path)
537 .ok()
538 .and_then(|file| worker_protocol::filesystem::object(&file).ok())
539 .is_some_and(|identity| identity == self.identity)
540 }
541}
542
543fn open_root_handle(path: &Path) -> io::Result<fs::File> {
544 let mut options = fs::OpenOptions::new();
545 options.read(true);
546 #[cfg(target_os = "linux")]
547 {
548 use std::os::unix::fs::OpenOptionsExt;
549 options.custom_flags(0x20000); // 심볼릭 링크를 따라가지 않음.
550 }
551 #[cfg(windows)]
552 {
553 use std::os::windows::fs::OpenOptionsExt;
554 // 폴더 자체를 열며 재분석 지점을 따라가지 않음.
555 // 삭제 공유를 허용하지 않아 열어 둔 동안 폴더 이름을 바꾸거나 지울 수 없게 함.
556 options.share_mode(1 | 2).custom_flags(0x02000000 | 0x00200000);
557 }
558 let file = options.open(path)?;
559 let metadata = file.metadata()?;
560 if !metadata.is_dir() || fs::symlink_metadata(path)?.file_type().is_symlink() {
561 return Err(io::Error::other("임시 폴더가 아님"));
562 }
563 #[cfg(windows)]
564 {
565 use std::os::windows::fs::MetadataExt;
566 if metadata.file_attributes() & 0x400 != 0 {
567 return Err(io::Error::other("재분석 지점은 임시 폴더로 쓰지 않음"));
568 }
569 }
570 Ok(file)
571}
572
573/// 압축파일 안 파일을 기본 프로그램으로 열 때 쓸 임시 폴더를 만듦.
574/// 압축파일과 같은 폴더에 만들고, 그곳에 만들 수 없으면 시스템 임시 폴더를 씀.
575/// 숨김 폴더로 만들지 않음. snap으로 설치한 Firefox 등은 홈 바로 아래 숨김 폴더와
576/// 시스템 임시 폴더의 파일을 읽지 못해 열기 요청을 조용히 무시함.
577pub fn create_open_root(archive: &Path) -> io::Result<OpenRoot> {
578 create_open_root_with(archive, |_| {})
579}
580
581/// `create_open_root`와 같고, 폴더를 만든 직후 핸들을 잡기 전에 `after_create`를 실행함.
582/// 만든 뒤 경로가 바뀌는 경우를 시험하려고 둠.
583/// 폴더를 만든 뒤 핸들을 잡기까지의 틈에 경로가 바뀌어도, 핸들로 확인한 폴더가 비어 있지
584/// 않으면 원본으로 쓰지 않고 다른 이름으로 다시 만듦. 바뀐 폴더는 건드리지 않음.
585pub fn create_open_root_with(
586 archive: &Path,
587 mut after_create: impl FnMut(&Path),
588) -> io::Result<OpenRoot> {
589 let name = archive.file_name().unwrap_or_default().to_string_lossy();
590 let mut error = None;
591 if let Some(parent) = archive.parent().filter(|p| !p.as_os_str().is_empty()) {
592 let base = parent.join(open_root_name(&name));
593 for _ in 0..8 {
594 let path = unique_folder(&base);
595 match private_dir(&path) {
596 Ok(()) => {
597 after_create(&path);
598 match OpenRoot::capture(path.clone()) {
599 Ok(root) => return Ok(root),
600 Err(e) => {
601 // 비어 있는 폴더만 지워지므로 바뀐 폴더의 내용은 남음.
602 let _ = fs::remove_dir(&path);
603 error = Some(e);
604 continue;
605 }
606 }
607 }
608 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
609 Err(e) => {
610 error = Some(e);
611 break;
612 }
613 }
614 }
615 }
616 let base = std::env::temp_dir().join(format!("zipelo-{}-{name}", std::process::id()));
617 let path = unique_folder(&base);
618 private_dir(&path).map_err(|e| error.unwrap_or(e))?;
619 after_create(&path);
620 OpenRoot::capture(path.clone()).inspect_err(|_| {
621 let _ = fs::remove_dir(&path);
622 })
623}
624
625/// 열기용 임시 폴더 이름. 예: `자료.zip (Zipelo 임시)`.
626pub fn open_root_name(archive_name: &str) -> String {
627 format!("{archive_name} (Zipelo 임시)")
628}
629
630/// 이 앱이 만든 열기용 폴더를 지움. 다른 프로그램이 파일을 쓰고 있으면 남을 수 있음.
631pub fn remove_open_root(root: OpenRoot) {
632 remove_open_root_with(root, || {});
633}
634
635/// `remove_open_root`와 같고, 정체를 확인한 직후 삭제 전에 `after_check`를 실행함.
636/// 확인과 삭제 사이에 경로가 바뀌는 경우를 시험하려고 둠.
637/// 내용은 만들 때 열어 둔 폴더 핸들에 묶어 지우므로 경로가 바뀌어도 다른 폴더는 건드리지 않음.
638pub fn remove_open_root_with(root: OpenRoot, after_check: impl FnOnce()) {
639 if !root.is_current() {
640 return;
641 }
642 after_check();
643 let OpenRoot { path, handle, .. } = root;
644 let _ = worker_protocol::tree_remove::remove_contents(&handle, &path);
645 // Windows는 핸들을 닫아야 폴더를 지울 수 있음.
646 drop(handle);
647 // 비어 있지 않거나 링크로 바뀐 경로는 지워지지 않으므로 다른 내용이 사라지지 않음.
648 let _ = fs::remove_dir(&path);
649}
650
651/// 기본 프로그램으로 열면 실행될 수 있는 파일은 바로 열지 않음.
652/// Windows는 스크립트도 연결 프로그램이 바로 실행하므로 범위가 넓고,
653/// Linux는 스크립트를 편집기로 열므로 실행·설치 파일만 막음.
654pub fn blocked_open(name: &str) -> bool {
655 #[cfg(windows)]
656 const EXECUTABLE: &[&str] = &[
657 "exe", "com", "bat", "cmd", "scr", "pif", "msi", "msp", "msc", "ps1", "psm1", "vbs",
658 "vbe", "js", "jse", "wsf", "wsh", "hta", "cpl", "lnk", "url", "reg", "jar", "inf", "scf",
659 "chm", "dll", "sys", "appref-ms", "application", "gadget", "settingcontent-ms",
660 ];
661 #[cfg(not(windows))]
662 const EXECUTABLE: &[&str] = &[
663 "desktop", "appimage", "run", "bin", "jar", "deb", "rpm", "snap", "flatpakref",
664 "flatpak", "exe", "msi",
665 ];
666 open_extension(name).is_some_and(|ext| EXECUTABLE.contains(&ext.to_ascii_lowercase().as_str()))
667}
668
669fn open_extension(name: &str) -> Option<&str> {
670 let leaf = name.rsplit(['/', '\\']).next().unwrap_or(name);
671 leaf.rsplit_once('.')
672 .map(|(_, ext)| ext)
673 .filter(|ext| !ext.is_empty())
674}
675
676/// 실행 파일이라 열지 않았다는 짧은 안내. 압축은 풀지 않음.
677pub fn open_blocked_text(name: &str) -> String {
678 match open_extension(name) {
679 Some(ext) => format!("실행 파일(.{ext})은 안전을 위해 바로 열 수 없습니다"),
680 None => "실행 파일은 안전을 위해 바로 열 수 없습니다".into(),
681 }
682}
683
684pub const OPEN_FAILED: &str = "파일을 열 프로그램을 실행하지 못했습니다";
685pub const OPEN_MISSING: &str = "풀린 파일을 찾지 못해 열지 못했습니다";
686
687/// 운영체제에 설정된 기본 프로그램으로 파일을 엶.
688pub fn open_with_default(path: &Path) -> Result<(), String> {
689 #[cfg(windows)]
690 let mut command = {
691 let mut command = std::process::Command::new("explorer.exe");
692 command.arg(path);
693 command
694 };
695 #[cfg(not(windows))]
696 let mut command = {
697 let mut command = std::process::Command::new("xdg-open");
698 command.arg(path);
699 command
700 };
701 command
702 .stdin(std::process::Stdio::null())
703 .stdout(std::process::Stdio::null())
704 .stderr(std::process::Stdio::null());
705 let mut child = command.spawn().map_err(|_| OPEN_FAILED.to_owned())?;
706 // 끝난 자식 프로세스를 거둬 좀비로 남지 않게 함.
707 std::thread::spawn(move || {
708 let _ = child.wait();
709 });
710 Ok(())
711}