team-ljyzipelo

공개
1,181줄50 KB
1use super::*;
2use std::ffi::OsString;
3
4#[path = "fake.rs"]
5mod fake;
6use fake::FakeFactory;
7
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct Scenario {
10 pub name: &'static str,
11 pub description: &'static str,
12}
13
14macro_rules! catalog {
15 ($($name:literal => $description:literal),+ $(,)?) => {
16 pub const SCENARIOS: &[Scenario] = &[$(Scenario {
17 name: $name,
18 description: $description,
19 }),+];
20 };
21}
22
23catalog! {
24 "archive-loading" => "목록 로딩 중 최초 작업 창의 표시 순서",
25 "archive-loading-in-parent" => "Wayland의 부모 내부 목록 로딩 창",
26 "recovery-progress" => "ZIP 복구 분석과 저장 확인 전 대기",
27 "recovery-complete" => "전체 항목을 검증한 복구본 저장 완료",
28 "recovery-partial" => "유실 항목이 있는 복구본과 경고",
29 "recovery-unknown" => "전체 목록 불명의 추가 유실 경고",
30 "recovery-impossible" => "복구 가능한 항목 없음과 출력 없음",
31 "recovery-cancelled" => "복구 취소와 출력 없음",
32 "recovery-retained" => "복구 저장 실패 뒤 남은 임시 파일 경로와 정리 경고",
33 "recovery-save-error" => "복구 분석 뒤 저장 실패",
34 "recovery-resource" => "복구 작업의 자원 승인",
35
36 "create-sevenzip" => "7z 형식 선택과 LZMA2 및 암호 미지원 안내",
37 "create-sevenzip-progress" => "7z 만들기 진행과 취소",
38 "create-sevenzip-complete" => "7z 만들기 완료",
39 "create-sevenzip-error" => "7z 만들기 저장 실패",
40 "create-sevenzip-cancelled" => "7z 만들기 취소 완료",
41 "create-sevenzip-resource" => "7z 만들기의 큰 작업 승인",
42 "create-sevenzip-split" => "7z 쪼갤 용량 설정과 볼륨 크기 입력",
43 "create-sevenzip-split-invalid" => "잘못된 쪼갤 용량의 오류와 압축하기 비활성화",
44 "create-sevenzip-split-complete" => "분할 7z 만들기 완료와 첫 볼륨 경로",
45
46 "split-archive" => "분할 7z 목록과 미리보기 비활성화",
47 "split-first-volume" => "첫 조각의 정확한 파일명 안내",
48 "split-missing-volume" => "누락 조각 파일명과 재시도 안내",
49 "split-incomplete" => "누락 이름을 단정하지 않는 불완전 묶음 안내",
50 "split-unsupported" => "분할 ZIP과 RAR 미지원 안내",
51 "split-source-changed" => "목록 이후 분할 조각 변경 안내",
52 "preview-catalog-bytes-approval" => "16 GiB를 넘는 전체 목록의 미리보기 승인",
53 "preview-catalog-approval" => "미리보기의 전체 목록 처리 예산 승인",
54 "preview-loading" => "미리보기 로딩과 취소",
55 "preview-text" => "읽기 전용 텍스트 미리보기",
56 "preview-image" => "정적 이미지 미리보기",
57 "preview-empty" => "빈 텍스트 미리보기",
58 "preview-limit" => "미리보기 한도 초과",
59 "preview-damaged" => "손상된 미리보기 파일",
60 "preview-unsupported" => "미지원 미리보기 형식",
61 "preview-implicit-folder" => "파일 하나를 포함한 가상 폴더의 미리보기 비활성화",
62 "preview-selection" => "폴더와 여러 항목의 미리보기 비활성화",
63 "resource-approval" => "처리 전 큰 작업 승인",
64 "resource-ratio" => "고압축 작업 경고와 미확인 값",
65 "resource-retry" => "주 창 모달에서 출력 없는 한도 실패 후 확대 재시도",
66 "resource-partial" => "주 창 모달에서 일부 출력 후 한도 중단",
67 "gzip-conflict-choice" => "단일 GZ 파일의 충돌 선택",
68 "conflict-choice" => "같은 이름 파일의 세 가지 처리 선택",
69 "conflict-apply" => "남은 충돌에 같은 선택 적용",
70 "extract-skipped" => "모든 파일을 건너뛴 정상 완료",
71 "extract-renamed" => "이름을 바꿔 저장한 완료 결과",
72 "extract-rename-failed" => "새 이름을 정한 뒤 저장 전 I/O 실패",
73 "empty" => "빈 첫 화면",
74 "archive" => "폴더와 파일이 있는 압축파일",
75 "tar-bz2" => "TAR.BZ2 목록과 자동 해제 폴더",
76 "tar-xz" => "TAR.XZ 목록과 자동 해제 폴더",
77 "folder" => "사진 하위 폴더",
78 "many-items" => "500개 항목과 세로 스크롤",
79 "selection" => "여러 파일과 폴더 선택",
80 "marquee" => "반투명 사각형으로 끌어서 선택 중",
81 "search-empty" => "검색 결과 없음",
82 "find-folder" => "Ctrl+F로 연 폴더 아래 이름 찾기 창",
83 "find-all" => "Ctrl+Shift+F로 연 전체 경로 찾기 창",
84 "find-empty" => "찾기 창의 결과 없음 안내",
85 "open-blocked" => "실행 파일을 바로 열지 않는다는 안내",
86 "open-failed" => "기본 프로그램 실행 실패 안내",
87 "open-missing" => "풀린 파일을 찾지 못해 열지 못한 안내",
88 "drag-released" => "Windows에서 다 풀기 전에 버튼을 놓은 끌어 놓기 안내",
89 "password" => "압축 해제 암호 입력",
90 "password-retry" => "암호가 틀린 뒤 다시 입력",
91 "extract-progress" => "압축 해제 진행률 62%",
92 "extract-unknown" => "전체 크기를 모르는 압축 해제",
93 "extract-complete" => "압축 해제 완료",
94 "extract-cancelled" => "압축 해제 취소 완료",
95 "cancelling" => "취소 요청 후 작업 종료 대기",
96 "conflict" => "같은 이름 파일 충돌",
97 "unsupported" => "지원하지 않는 압축 형식",
98 "damaged" => "손상된 압축파일",
99 "create" => "암호 없는 ZIP 만들기 창",
100 "create-encrypted" => "암호 설정이 켜진 ZIP 만들기 창",
101 "create-progress" => "ZIP 만들기 진행률 62%",
102 "create-complete" => "ZIP 만들기 완료",
103 "folder-empty" => "항목이 없는 하위 폴더",
104 "gzip-conflict" => "단일 GZ 파일 이름 충돌",
105 "extract-disk-full" => "압축 해제 중 디스크 공간 또는 할당량 부족",
106 "extract-complete-cleanup-failed" => "압축 해제 완료와 출력 폴더의 임시 파일 정리 실패",
107 "extract-cleanup-failed" => "압축 해제 실패와 출력 폴더의 임시 파일 정리 실패",
108 "extract-partial" => "일부 파일만 풀린 결과",
109 "extract-uncertain" => "저장 여부를 확인할 수 없는 결과",
110 "extract-unsynced" => "완료 뒤 저장 확인 경고의 상세 정보",
111 "source-changed" => "목록을 연 뒤 원본이 바뀐 오류",
112 "dialog-error" => "운영체제 파일 선택 창 실행 실패",
113 "create-error" => "ZIP 만들기 중 디스크 공간 부족",
114 "password-create" => "암호 ZIP 생성의 작업자 암호 요청",
115 "close-confirm" => "진행 중 창 닫기 확인",
116 "uninstall-windows" => "Windows 제거 전 기본 앱 선택 안내",
117 "uninstall-settings-error" => "Windows 기본 앱 설정 실행 실패",
118 "uninstall-ubuntu-missing" => "Ubuntu 이전 기본 앱 복원 불가 안내",
119 "uninstall-ubuntu-unknown-user" => "Ubuntu 제거 사용자 확인 불가 안내",
120}
121
122/// 만들기 창의 쪼갤 용량 입력을 해석한 결과. 잘못된 입력이면 압축하기가 비활성임.
123pub fn split_volume(app: &ArchiveApp) -> Result<Option<u64>, &'static str> {
124 app.split_volume()
125}
126
127pub fn listing() -> String {
128 SCENARIOS
129 .iter()
130 .map(|s| format!("{}\t{}\n", s.name, s.description))
131 .collect()
132}
133
134pub fn parse(name: &str) -> Result<Scenario, String> {
135 SCENARIOS
136 .iter()
137 .copied()
138 .find(|s| s.name == name)
139 .ok_or_else(|| {
140 format!(
141 "알 수 없는 UI 상황: {name}\n사용 가능한 상황:\n{}",
142 listing()
143 )
144 })
145}
146
147#[derive(Debug, PartialEq)]
148pub enum Launch {
149 Normal(Vec<OsString>),
150 Scenario(Scenario),
151 List,
152}
153
154pub fn launch(args: Vec<OsString>) -> Result<Launch, String> {
155 let requested = args
156 .iter()
157 .any(|a| a == "--ui-scenario" || a == "--list-ui-scenarios");
158 if !requested {
159 return Ok(Launch::Normal(args));
160 }
161 if args.len() == 1 && args[0] == "--list-ui-scenarios" {
162 return Ok(Launch::List);
163 }
164 if args.len() == 2 && args[0] == "--ui-scenario" {
165 return args[1]
166 .to_str()
167 .ok_or_else(|| format!("상황 이름은 UTF-8이어야 합니다\n{}", listing()))
168 .and_then(parse)
169 .map(Launch::Scenario);
170 }
171 Err(format!(
172 "사용법: --ui-scenario <이름> 또는 --list-ui-scenarios\n{}",
173 listing()
174 ))
175}
176
177fn sample_root() -> PathBuf {
178 PathBuf::from(if cfg!(target_os = "windows") {
179 "C:\\Samples"
180 } else {
181 "/Samples"
182 })
183}
184
185fn entries(many: bool) -> Vec<Entry> {
186 let mut entries = vec![
187 ("사진", Kind::Directory),
188 ("읽어주세요.txt", Kind::File),
189 ("여행 일정.pdf", Kind::File),
190 ("사진/바다.jpg", Kind::File),
191 ("사진/풍경.jpg", Kind::File),
192 ]
193 .into_iter()
194 .enumerate()
195 .map(|(id, (name, kind))| Entry {
196 id: id as u32,
197 name: name.into(),
198 kind,
199 bytes: Some(if kind == Kind::Directory {
200 0
201 } else {
202 1_287_952
203 }),
204 packed: Some(900_000),
205 encrypted: id == 2,
206 })
207 .collect::<Vec<_>>();
208 if many {
209 entries.extend((5..505).map(|id| Entry {
210 id,
211 name: format!("자료-{id:03}.txt"),
212 kind: Kind::File,
213 bytes: Some(4096),
214 packed: Some(1800),
215 encrypted: false,
216 }));
217 }
218 entries
219}
220
221impl Scenario {
222 /// 제거 안내는 외부 설치 화면의 문구만 재현하며 OS 동작은 실행하지 않음.
223 pub fn show(self, app: &mut ArchiveApp, ui: &mut egui::Ui) {
224 let (title, messages, button): (&str, Vec<&str>, Option<&str>) = match self.name {
225 "uninstall-windows" => (
226 "제거 전 기본 앱 선택",
227 vec![
228 "Zipelo를 기본 앱으로 사용했다면 제거 전에 다른 앱을 선택하세요. [기본 앱 설정 열기]에서 .zip, .7z, .tar, .gz, .tgz를 검색해 사용할 앱을 고를 수 있습니다. 다른 앱이 없으면 먼저 설치하세요.",
229 "직접 고른 기본 앱은 자동으로 바꾸지 않습니다. 제거 후 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [연결 프로그램]에서 다른 앱을 선택하세요.",
230 ],
231 Some("기본 앱 설정 열기"),
232 ),
233 "uninstall-settings-error" => (
234 "기본 앱 설정 실행 실패",
235 vec![
236 "Windows 설정을 열지 못했습니다. 설정 > 앱 > 기본 앱에서 확장자를 검색해 다른 앱을 선택하세요.",
237 ],
238 Some("확인"),
239 ),
240 "uninstall-ubuntu-missing" => (
241 "Ubuntu 제거 안내",
242 vec![
243 "Zipelo를 제거합니다. 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [다른 프로그램으로 열기]에서 다른 앱을 선택하세요.",
244 "이전 앱을 복원할 수 없습니다: application/zip. 파일을 오른쪽 클릭해 [다른 프로그램으로 열기]에서 앱을 선택하세요.",
245 ],
246 None,
247 ),
248 "uninstall-ubuntu-unknown-user" => (
249 "Ubuntu 제거 안내",
250 vec![
251 "Zipelo를 제거합니다. 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [다른 프로그램으로 열기]에서 다른 앱을 선택하세요.",
252 "제거를 요청한 사용자를 확인할 수 없어 사용자 기본 앱 설정은 변경하지 않습니다.",
253 ],
254 None,
255 ),
256 _ => {
257 app.show(ui);
258 return;
259 }
260 };
261 egui::CentralPanel::default().show_inside(ui, |ui| {
262 ui.add_space(16.0);
263 ui.heading(title);
264 ui.add_space(16.0);
265 for message in messages {
266 ui.label(message);
267 ui.add_space(16.0);
268 }
269 if let Some(button) = button {
270 // 미리보기에서는 설정 열기와 제거를 실행하지 않음.
271 let _ = ui.button(button);
272 }
273 });
274 }
275
276 /// 플랫폼 테두리만 적용하고 시나리오가 정한 작업 창 방식은 유지함.
277 pub fn build_with_frame(self, custom_frame: bool) -> ArchiveApp {
278 let mut app = self.build();
279 app.set_custom_frame(custom_frame);
280 app
281 }
282
283 /// 실제 파일과 작업자를 사용하지 않고 기존 화면 상태를 준비함.
284 pub fn build(self) -> ArchiveApp {
285 let factory = FakeFactory::manual();
286 let state = factory.state.clone();
287 let mut app = ArchiveApp::new(Box::new(factory), None, true);
288 let base = sample_root();
289 app.destination = base.join("풀린 자료");
290 app.automatic_destination = false;
291 app.zip_folder = base.clone();
292 app.zip_name = "여행 자료.zip".into();
293 if self.name == "empty" || self.name.starts_with("uninstall-") {
294 return app;
295 }
296 let archive = base.join(match self.name {
297 "gzip-conflict" | "gzip-conflict-choice" => "여행 자료.gz",
298 "tar-bz2" => "여행 자료.TAR.BZ2",
299 "tar-xz" => "여행 자료.TaR.Xz",
300 _ => "여행 자료.zip",
301 });
302 if matches!(self.name, "archive-loading" | "archive-loading-in-parent") {
303 app.set_work_window_in_parent(self.name == "archive-loading-in-parent");
304 app.open_path(archive);
305 {
306 let mut state = state.borrow_mut();
307 state.frame(Event::Accepted { encryption: false });
308 state.frame(Event::Progress {
309 stage: Stage::Read,
310 processed: 38 << 20,
311 total: Some(61 << 20),
312 completed_entries: 0,
313 });
314 }
315 for _ in 0..64 {
316 app.model.poll();
317 }
318 return app;
319 }
320 app.model.archive = Some(archive.clone());
321 app.model.entries = entries(self.name == "many-items");
322 app.model.list_id = Some(ListId {
323 catalog_version: 1,
324 format: Format::Zip,
325 source_object: SourceObject::Unix {
326 device: 1,
327 inode: 1,
328 },
329 archive_bytes: 2_700_000,
330 archive_sha256: [7; 32],
331 });
332 app.model.confirmed = true;
333 if self.name.starts_with("split-") {
334 let archive = base.join(if self.name == "split-unsupported" {
335 "여행.zip.001"
336 } else {
337 "여행.7z.001"
338 });
339 app.model.archive = Some(archive.clone());
340 app.model.list_id = Some(ListId {
341 catalog_version: 2,
342 format: Format::SevenZip,
343 source_object: SourceObject::SplitSevenZip {
344 manifest_sha256: [9; 32],
345 },
346 archive_bytes: 2_700_000,
347 archive_sha256: [7; 32],
348 });
349 if self.name == "split-archive" {
350 app.model.selected.insert(1);
351 return app;
352 }
353 app.start(Start::List { archive });
354 let mut state = state.borrow_mut();
355 state.frame(Event::Accepted { encryption: false });
356 let reason = match self.name {
357 "split-first-volume" => Some(VolumeProblemReason::FirstVolumeRequired),
358 "split-missing-volume" => Some(VolumeProblemReason::MissingVolume),
359 "split-incomplete" => Some(VolumeProblemReason::IncompleteSet),
360 _ => None,
361 };
362 let error = match reason {
363 Some(VolumeProblemReason::FirstVolumeRequired) => ErrorCode::InvalidRequest,
364 Some(VolumeProblemReason::MissingVolume) => ErrorCode::MissingVolume,
365 Some(VolumeProblemReason::IncompleteSet) => ErrorCode::Integrity,
366 None if self.name == "split-source-changed" => ErrorCode::SourceChanged,
367 None => ErrorCode::UnsupportedFeature,
368 };
369 if let Some(reason) = reason {
370 state.frame(Event::VolumeProblem(VolumeProblem {
371 reason,
372 volume: NativePath::Unix(if reason == VolumeProblemReason::MissingVolume {
373 "여행.7z.003".as_bytes().to_vec()
374 } else {
375 "여행.7z.001".as_bytes().to_vec()
376 }),
377 }));
378 }
379 state.frame(Event::Terminal(Terminal {
380 outcome: Outcome::Failed,
381 error: Some(error),
382 publication: Publication::None,
383 created_count: 0,
384 retained_partial_count: 0,
385 durability: Durability::NotApplicable,
386 cleanup: Cleanup::Complete,
387 }));
388 state.queue.push_back(HostEvent::StdoutEof);
389 state.queue.push_back(HostEvent::StderrEof);
390 state.queue.push_back(HostEvent::Exited { success: true });
391 drop(state);
392 for _ in 0..32 {
393 app.model.poll();
394 }
395 return app;
396 }
397 if self.name.starts_with("preview-") {
398 app.model.selected = BTreeSet::from([1]);
399 if self.name == "preview-implicit-folder" {
400 app.model.entries.truncate(1);
401 app.model.entries[0].id = 1;
402 app.model.entries[0].name = "자료/안내.txt".into();
403 app.model.entries[0].kind = Kind::File;
404 return app;
405 }
406 if self.name == "preview-selection" {
407 app.model.selected.insert(0);
408 return app;
409 }
410 if self.name == "preview-catalog-approval" {
411 let template = app.model.entries[1].clone();
412 app.model.entries = (0..10_001)
413 .map(|id| Entry {
414 id,
415 name: if id == 1 {
416 "읽어주세요.txt".into()
417 } else {
418 format!("{id}.bin")
419 },
420 bytes: Some(if id == 1 { 7 } else { 0 }),
421 ..template.clone()
422 })
423 .collect();
424 }
425 if self.name == "preview-catalog-bytes-approval" {
426 app.model.entries.truncate(2);
427 app.model.entries[0].bytes = Some(16 * 1024 * 1024 * 1024);
428 app.model.entries[1].bytes = Some(7);
429 }
430 app.begin_preview(&egui::Context::default());
431 if matches!(
432 self.name,
433 "preview-catalog-approval" | "preview-catalog-bytes-approval"
434 ) {
435 let mut state = state.borrow_mut();
436 state.frame(Event::Accepted { encryption: false });
437 state.frame(Event::ResourceRequired(ResourceChallenge {
438 id: 1,
439 action: ActionKind::Preview,
440 scope: ResourceScope {
441 output: true,
442 entries: true,
443 ..ResourceScope::default()
444 },
445 usage: ResourceUsage::default(),
446 soft_limits: Limits::default(),
447 ceiling: Limits {
448 input: u64::MAX,
449 output: 64 * 1024 * 1024 * 1024,
450 entries: 200_000,
451 },
452 }));
453 drop(state);
454 for _ in 0..32 {
455 app.model.poll();
456 }
457 return app;
458 }
459 {
460 let mut state = state.borrow_mut();
461 state.frame(Event::Accepted { encryption: false });
462 if self.name != "preview-loading" {
463 let error = match self.name {
464 "preview-limit" => Some(ErrorCode::Limit),
465 "preview-damaged" => Some(ErrorCode::Integrity),
466 "preview-unsupported" => Some(ErrorCode::UnsupportedFeature),
467 _ => None,
468 };
469 if error.is_none() {
470 use sha2::{Digest, Sha256};
471 let image = self.name == "preview-image";
472 let data = if image {
473 (0..128 * 96)
474 .flat_map(|i| {
475 if (i / 128 / 16 + i % 128 / 16) % 2 == 0 {
476 [37, 99, 235, 255]
477 } else {
478 [232, 240, 254, 255]
479 }
480 })
481 .collect::<Vec<_>>()
482 } else if self.name == "preview-empty" {
483 Vec::new()
484 } else {
485 "여행 준비 목록\n\n기차표 확인\n카메라 배터리 충전\n"
486 .as_bytes()
487 .to_vec()
488 };
489 let info = PreviewInfo {
490 entry_id: 1,
491 format: if image {
492 PreviewFormat::Rgba8
493 } else {
494 PreviewFormat::Utf8Text
495 },
496 total_bytes: data.len() as u64,
497 width: if image { 128 } else { 0 },
498 height: if image { 96 } else { 0 },
499 };
500 state.frame(Event::PreviewBegin(info));
501 for (offset, chunk) in data.chunks(32768).enumerate() {
502 state.frame(Event::PreviewChunk {
503 entry_id: 1,
504 offset: (offset * 32768) as u64,
505 data: chunk.to_vec(),
506 });
507 }
508 state.frame(Event::PreviewEnd {
509 entry_id: 1,
510 total_bytes: info.total_bytes,
511 sha256: Sha256::digest(&data).into(),
512 });
513 }
514 state.frame(Event::Terminal(Terminal {
515 outcome: if error.is_some() {
516 Outcome::Failed
517 } else {
518 Outcome::Completed
519 },
520 error,
521 publication: Publication::None,
522 created_count: 0,
523 retained_partial_count: 0,
524 durability: Durability::NotApplicable,
525 cleanup: Cleanup::Complete,
526 }));
527 state.queue.push_back(HostEvent::StdoutEof);
528 state.queue.push_back(HostEvent::StderrEof);
529 state.queue.push_back(HostEvent::Exited { success: true });
530 }
531 }
532 for _ in 0..32 {
533 app.model.poll();
534 }
535 return app;
536 }
537 match self.name {
538 "tar-bz2" | "tar-xz" => {
539 app.model.list_id.as_mut().unwrap().format = Format::Tar;
540 for entry in &mut app.model.entries {
541 entry.encrypted = false;
542 }
543 app.destination = present::default_destination(&archive);
544 app.automatic_destination = true;
545 return app;
546 }
547 "archive" | "many-items" => return app,
548 "folder-empty" => {
549 app.browse_folder("빈 폴더");
550 return app;
551 }
552 "dialog-error" => {
553 app.ui_error = Some(DIALOG_UNAVAILABLE.into());
554 return app;
555 }
556 "folder" => {
557 app.browse_folder("사진");
558 return app;
559 }
560 "search-empty" => {
561 app.search = "없는 파일".into();
562 return app;
563 }
564 "find-folder" | "find-all" | "find-empty" => {
565 app.open_find(self.name == "find-all");
566 app.set_find_query(match self.name {
567 "find-folder" => "jpg",
568 "find-all" => "사진",
569 _ => "없는 이름",
570 });
571 return app;
572 }
573 "drag-released" => {
574 app.dismissed = false;
575 app.ui_error = Some(present::DRAG_RELEASED.into());
576 return app;
577 }
578 "open-blocked" | "open-failed" | "open-missing" => {
579 app.dismissed = false;
580 app.ui_error = Some(match self.name {
581 "open-blocked" => present::open_blocked_text("설치 프로그램.exe"),
582 "open-failed" => "파일을 열 프로그램을 실행하지 못했습니다".into(),
583 _ => present::OPEN_MISSING.into(),
584 });
585 return app;
586 }
587 "selection" | "marquee" => {
588 app.model
589 .selected
590 .extend([0, 3, 4, if self.name == "marquee" { 2 } else { 1 }]);
591 if self.name == "marquee" {
592 app.scenario_marquee = Some(egui::Rect::from_min_size(
593 egui::pos2(22.0, 8.0),
594 egui::vec2(360.0, 62.0),
595 ));
596 }
597 return app;
598 }
599 "create"
600 | "create-encrypted"
601 | "create-sevenzip"
602 | "create-sevenzip-split"
603 | "create-sevenzip-split-invalid" => {
604 app.sources = vec![base.join("읽어주세요.txt"), base.join("사진")];
605 app.scenario_sources = Some(std::rc::Rc::new(vec![
606 SourceRow {
607 name: "사진".into(),
608 directory: true,
609 bytes: Some(0),
610 },
611 SourceRow {
612 name: "읽어주세요.txt".into(),
613 directory: false,
614 bytes: Some(4096),
615 },
616 ]));
617 app.show_create(self.name == "create-encrypted");
618 app.set_seven_zip(self.name.starts_with("create-sevenzip"));
619 if self.name.starts_with("create-sevenzip-split") {
620 app.zip_name = "여행 자료.7z".into();
621 app.split = true;
622 app.split_amount = if self.name == "create-sevenzip-split" {
623 "700".into()
624 } else {
625 "0".into()
626 };
627 }
628 return app;
629 }
630 _ => {}
631 }
632 if self.name.starts_with("recovery-") {
633 let request = Start::RecoverZip {
634 archive,
635 output_file: base.join("복구본.zip"),
636 };
637 app.last_request = Some(request.clone());
638 app.model.begin(request, app.factory.as_mut());
639 let mut state = state.borrow_mut();
640 state.frame(Event::Accepted { encryption: false });
641 if self.name == "recovery-resource" {
642 state.frame(Event::ResourceRequired(ResourceChallenge {
643 id: 1,
644 action: ActionKind::RecoverZip,
645 scope: ResourceScope {
646 ratio: true,
647 ..Default::default()
648 },
649 usage: ResourceUsage::default(),
650 soft_limits: Limits::default(),
651 ceiling: Limits::default(),
652 }));
653 } else if self.name == "recovery-progress" {
654 state.frame(Event::Progress {
655 stage: Stage::Scan,
656 processed: 1024,
657 total: None,
658 completed_entries: 1,
659 });
660 } else if self.name == "recovery-cancelled" {
661 state.finish(Outcome::Cancelled, Publication::None);
662 } else {
663 let impossible = self.name == "recovery-impossible";
664 let partial = self.name == "recovery-partial";
665 let unknown = self.name == "recovery-unknown";
666 let retained = self.name == "recovery-retained";
667 let failed = self.name == "recovery-save-error" || retained;
668 state.frame(Event::RecoveryEntry(RecoveryEntry {
669 candidate_id: 0,
670 source_offset: 0,
671 name: Some("읽어주세요.txt".into()),
672 kind: Some(worker_protocol::protocol::EntryKind::File),
673 status: if impossible {
674 RecoveryStatus::Lost
675 } else {
676 RecoveryStatus::Verified
677 },
678 reason: if impossible {
679 RecoveryReason::Truncated
680 } else {
681 RecoveryReason::HeaderRebuilt
682 },
683 declared_size: Some(4),
684 verified_size: (!impossible).then_some(4),
685 sha256: (!impossible).then_some([1; 32]),
686 }));
687 if partial {
688 state.frame(Event::RecoveryEntry(RecoveryEntry {
689 candidate_id: 1,
690 source_offset: 128,
691 name: Some("사진.png".into()),
692 kind: Some(worker_protocol::protocol::EntryKind::File),
693 status: RecoveryStatus::Lost,
694 reason: RecoveryReason::CrcMismatch,
695 declared_size: Some(10),
696 verified_size: None,
697 sha256: None,
698 }));
699 }
700 state.frame(Event::RecoveryEnd(RecoveryEnd {
701 mode: if unknown {
702 RecoveryMode::LocalChain
703 } else {
704 RecoveryMode::CentralDirectory
705 },
706 source_bytes: 256,
707 source_sha256: [2; 32],
708 known_entries: (!unknown).then_some(if partial { 2 } else { 1 }),
709 verified_entries: u32::from(!impossible),
710 lost_entries: u32::from(impossible || partial),
711 unverified_entries: 0,
712 unknown_loss: unknown,
713 }));
714 if !impossible && !failed {
715 state.frame(Event::Output {
716 entry_id: None,
717 relative_name: "복구본.zip".into(),
718 disposition: Disposition::Created,
719 });
720 }
721 if retained {
722 state.frame(Event::Output {
723 entry_id: None,
724 relative_name: ".zipelo-42-1.tmp".into(),
725 disposition: Disposition::PartialRetained,
726 });
727 }
728 state.frame(Event::Terminal(Terminal {
729 outcome: if partial || unknown || impossible || failed {
730 Outcome::Failed
731 } else {
732 Outcome::Completed
733 },
734 error: if failed {
735 Some(ErrorCode::DiskFull)
736 } else if impossible {
737 Some(ErrorCode::RecoveryImpossible)
738 } else if partial || unknown {
739 Some(ErrorCode::RecoveryIncomplete)
740 } else {
741 None
742 },
743 publication: if impossible || failed {
744 Publication::None
745 } else {
746 Publication::Complete
747 },
748 created_count: u64::from(!impossible && !failed),
749 retained_partial_count: u64::from(retained),
750 durability: if impossible || failed {
751 Durability::NotApplicable
752 } else {
753 Durability::Synced
754 },
755 cleanup: if retained {
756 Cleanup::Failed
757 } else {
758 Cleanup::Complete
759 },
760 }));
761 state.queue.extend([
762 HostEvent::StdoutEof,
763 HostEvent::StderrEof,
764 HostEvent::Exited { success: true },
765 ]);
766 }
767 drop(state);
768 for _ in 0..30 {
769 app.model.poll();
770 }
771 return app;
772 }
773 let seven_zip = self.name.starts_with("create-sevenzip");
774 let split_complete = self.name == "create-sevenzip-split-complete";
775 let creating = self.name.starts_with("create-") || self.name == "password-create";
776 let listing_error = matches!(self.name, "unsupported" | "damaged");
777 if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
778 app.model.list_id.as_mut().unwrap().format = Format::Gzip;
779 app.model.entries = vec![Entry {
780 id: 0,
781 name: "여행 자료".into(),
782 kind: Kind::File,
783 bytes: Some(1_287_952),
784 packed: Some(900_000),
785 encrypted: false,
786 }];
787 app.gzip_name = "여행 자료".into();
788 }
789 let request = if seven_zip {
790 Start::CreateSevenZip {
791 sources: vec![(base.join("사진"), "사진".into())],
792 output_file: base.join("여행 자료.7z"),
793 volume_size: split_complete.then_some(700 * 1024 * 1024),
794 }
795 } else if creating {
796 Start::CreateZip {
797 sources: vec![(base.join("사진"), "사진".into())],
798 output_file: base.join("여행 자료.zip"),
799 method: Method::Deflate,
800 aes256: self.name == "password-create",
801 }
802 } else if listing_error {
803 Start::List { archive }
804 } else {
805 Start::Extract {
806 archive,
807 destination: app.destination.clone(),
808 selection: Selection::All,
809 list_id: app.model.list_id.clone().unwrap(),
810 gzip_output_name: (matches!(self.name, "gzip-conflict" | "gzip-conflict-choice"))
811 .then(|| app.gzip_name.clone()),
812 }
813 };
814 app.targets = Some(if split_complete {
815 // 완료 보고와 대조하도록 실제 작업자처럼 볼륨 세 개의 이름을 기대함.
816 (1..=3).map(|n| format!("여행 자료.7z.{n:03}")).collect()
817 } else if creating {
818 BTreeSet::from([if seven_zip {
819 "여행 자료.7z"
820 } else {
821 "여행 자료.zip"
822 }
823 .into()])
824 } else if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
825 BTreeSet::from(["여행 자료".into()])
826 } else {
827 BTreeSet::from([
828 "읽어주세요.txt".into(),
829 "여행 일정.pdf".into(),
830 "사진/바다.jpg".into(),
831 "사진/풍경.jpg".into(),
832 ])
833 });
834 if matches!(
835 self.name,
836 "extract-skipped" | "extract-renamed" | "extract-rename-failed"
837 ) {
838 app.targets = Some(["읽어주세요.txt".into()].into_iter().collect());
839 app.directories.clear();
840 }
841 if self.name == "resource-approval" {
842 app.model.entries[1].bytes = Some(17 * 1024 * 1024 * 1024);
843 }
844 assert!(app.start(request));
845 {
846 let mut state = state.borrow_mut();
847 state.frame(Event::Accepted {
848 encryption: !seven_zip,
849 });
850 match self.name {
851 "resource-approval" | "resource-ratio" | "create-sevenzip-resource" => {
852 let expanded = self.name != "resource-ratio";
853 state.frame(Event::ResourceRequired(ResourceChallenge {
854 id: 1,
855 action: if seven_zip {
856 ActionKind::CreateSevenZip
857 } else {
858 ActionKind::Extract
859 },
860 scope: ResourceScope {
861 output: expanded,
862 entries: expanded,
863 ratio: !expanded,
864 },
865 usage: ResourceUsage {
866 available_bytes: Some(90 * 1024 * 1024 * 1024),
867 actual_bytes: (!expanded).then_some(300 * 1024 * 1024),
868 ratio_output_bytes: (!expanded).then_some(300 * 1024 * 1024),
869 compressed_bytes: (!expanded).then_some(4096),
870 ..ResourceUsage::default()
871 },
872 soft_limits: Limits::default(),
873 ceiling: if expanded {
874 Limits {
875 input: u64::MAX,
876 output: 64 * 1024 * 1024 * 1024,
877 entries: 200_000,
878 }
879 } else {
880 Limits::default()
881 },
882 }));
883 }
884 "resource-retry" | "resource-partial" => {
885 let partial = self.name == "resource-partial";
886 if partial {
887 state.frame(Event::Output {
888 entry_id: Some(1),
889 relative_name: "읽어주세요.txt".into(),
890 disposition: Disposition::Created,
891 });
892 }
893 state.frame(Event::Terminal(Terminal {
894 outcome: Outcome::Failed,
895 error: Some(ErrorCode::Limit),
896 publication: if partial {
897 Publication::Partial
898 } else {
899 Publication::None
900 },
901 created_count: u64::from(partial),
902 retained_partial_count: 0,
903 durability: Durability::Synced,
904 cleanup: Cleanup::Complete,
905 }));
906 state.queue.extend([
907 HostEvent::StdoutEof,
908 HostEvent::StderrEof,
909 HostEvent::Exited { success: true },
910 ]);
911 }
912 "conflict-choice" | "conflict-apply" | "gzip-conflict-choice" => {
913 state.frame(Event::ConflictRequired(Conflict {
914 challenge_id: 29,
915 entry_id: if self.name == "gzip-conflict-choice" {
916 0
917 } else {
918 1
919 },
920 relative_name: if self.name == "gzip-conflict-choice" {
921 "여행 자료"
922 } else {
923 "읽어주세요.txt"
924 }
925 .into(),
926 incoming_size: 1_287_952,
927 existing_size: 2048,
928 }));
929 }
930 "extract-skipped" | "extract-renamed" | "extract-rename-failed" => {
931 let failed = self.name == "extract-rename-failed";
932 let skip = self.name == "extract-skipped";
933 let name = if skip {
934 "읽어주세요.txt"
935 } else {
936 "읽어주세요 (1).txt"
937 };
938 state.frame(Event::ConflictResolved(Resolution {
939 entry_id: 1,
940 relative_name: name.into(),
941 choice: if skip {
942 ConflictChoice::Skip
943 } else {
944 ConflictChoice::Rename
945 },
946 }));
947 if !skip && !failed {
948 state.frame(Event::Output {
949 entry_id: Some(1),
950 relative_name: name.into(),
951 disposition: Disposition::Created,
952 });
953 }
954 state.frame(Event::Terminal(Terminal {
955 outcome: if failed {
956 Outcome::Failed
957 } else {
958 Outcome::Completed
959 },
960 error: failed.then_some(ErrorCode::Io),
961 publication: if skip || failed {
962 Publication::None
963 } else {
964 Publication::Complete
965 },
966 created_count: u64::from(!skip && !failed),
967 retained_partial_count: 0,
968 durability: if skip || failed {
969 Durability::NotApplicable
970 } else {
971 Durability::Synced
972 },
973 cleanup: Cleanup::Complete,
974 }));
975 state.queue.extend([
976 HostEvent::StdoutEof,
977 HostEvent::StderrEof,
978 HostEvent::Exited { success: true },
979 ]);
980 }
981 "password" | "password-retry" | "password-create" => {
982 state.frame(Event::PasswordRequired {
983 challenge_id: 17,
984 attempt: if self.name == "password-retry" { 2 } else { 1 },
985 encrypt: self.name == "password-create",
986 })
987 }
988 "extract-complete"
989 | "create-complete"
990 | "create-sevenzip-complete"
991 | "create-sevenzip-split-complete"
992 | "extract-unsynced"
993 | "extract-complete-cleanup-failed" => {
994 let names = app.targets.as_ref().unwrap();
995 for name in names {
996 state.frame(Event::Output {
997 entry_id: None,
998 relative_name: name.clone(),
999 disposition: Disposition::Created,
1000 });
1001 }
1002 state.frame(Event::Terminal(Terminal {
1003 outcome: Outcome::Completed,
1004 error: None,
1005 publication: Publication::Complete,
1006 created_count: names.len() as u64,
1007 retained_partial_count: 0,
1008 durability: if self.name == "extract-unsynced" {
1009 Durability::Unconfirmed
1010 } else {
1011 Durability::Synced
1012 },
1013 cleanup: if self.name == "extract-complete-cleanup-failed" {
1014 Cleanup::Failed
1015 } else {
1016 Cleanup::Complete
1017 },
1018 }));
1019 state.queue.extend([
1020 HostEvent::StdoutEof,
1021 HostEvent::StderrEof,
1022 HostEvent::Exited { success: true },
1023 ]);
1024 }
1025 "extract-cancelled" | "create-sevenzip-cancelled" => {
1026 state.finish(Outcome::Cancelled, Publication::None)
1027 }
1028 "extract-partial" | "extract-uncertain" => {
1029 let partial = self.name == "extract-partial";
1030 if partial {
1031 state.frame(Event::Output {
1032 entry_id: Some(1),
1033 relative_name: "읽어주세요.txt".into(),
1034 disposition: Disposition::Created,
1035 });
1036 }
1037 state.frame(Event::Terminal(Terminal {
1038 outcome: Outcome::Failed,
1039 error: Some(ErrorCode::Io),
1040 publication: if partial {
1041 Publication::Partial
1042 } else {
1043 Publication::Uncertain
1044 },
1045 created_count: u64::from(partial),
1046 retained_partial_count: 0,
1047 durability: Durability::Synced,
1048 cleanup: Cleanup::Complete,
1049 }));
1050 state.queue.extend([
1051 HostEvent::StdoutEof,
1052 HostEvent::StderrEof,
1053 HostEvent::Exited { success: true },
1054 ]);
1055 }
1056 "extract-disk-full" | "extract-cleanup-failed" => {
1057 state.frame(Event::Terminal(Terminal {
1058 outcome: Outcome::Failed,
1059 error: Some(if self.name == "extract-disk-full" {
1060 ErrorCode::DiskFull
1061 } else {
1062 ErrorCode::Io
1063 }),
1064 publication: Publication::None,
1065 created_count: 0,
1066 retained_partial_count: 0,
1067 durability: Durability::NotApplicable,
1068 cleanup: if self.name == "extract-cleanup-failed" {
1069 Cleanup::Failed
1070 } else {
1071 Cleanup::Complete
1072 },
1073 }));
1074 state.queue.extend([
1075 HostEvent::StdoutEof,
1076 HostEvent::StderrEof,
1077 HostEvent::Exited { success: true },
1078 ]);
1079 }
1080 "conflict"
1081 | "gzip-conflict"
1082 | "unsupported"
1083 | "damaged"
1084 | "source-changed"
1085 | "create-error"
1086 | "create-sevenzip-error" => {
1087 state.frame(Event::Terminal(Terminal {
1088 outcome: Outcome::Failed,
1089 error: Some(match self.name {
1090 "conflict" | "gzip-conflict" => ErrorCode::Conflict,
1091 "source-changed" => ErrorCode::SourceChanged,
1092 "create-error" | "create-sevenzip-error" => ErrorCode::DiskFull,
1093 "unsupported" => ErrorCode::UnsupportedFormat,
1094 _ => ErrorCode::Integrity,
1095 }),
1096 publication: Publication::None,
1097 created_count: 0,
1098 retained_partial_count: 0,
1099 durability: Durability::NotApplicable,
1100 cleanup: Cleanup::Complete,
1101 }));
1102 state.queue.extend([
1103 HostEvent::StdoutEof,
1104 HostEvent::StderrEof,
1105 HostEvent::Exited { success: true },
1106 ]);
1107 }
1108 _ => state.frame(Event::Progress {
1109 stage: if creating {
1110 Stage::Write
1111 } else {
1112 Stage::Decode
1113 },
1114 processed: 38 << 20,
1115 total: (self.name != "extract-unknown").then_some(61 << 20),
1116 completed_entries: 12,
1117 }),
1118 }
1119 }
1120 for _ in 0..64 {
1121 app.model.poll();
1122 }
1123 if self.name == "conflict-apply" {
1124 app.conflict_challenge = Some((app.model.job_id().unwrap(), 29));
1125 app.conflict_apply = true;
1126 }
1127 if self.name == "extract-unsynced" {
1128 app.details = true;
1129 }
1130 if self.name == "cancelling" {
1131 app.model.cancel();
1132 }
1133 if self.name == "close-confirm" {
1134 app.model.request_close();
1135 }
1136 app
1137 }
1138}
1139
1140/// 화면을 고정하고 실제 파일 조작을 막는 미리보기임.
1141pub struct Preview(pub ArchiveApp, Option<Scenario>);
1142impl Preview {
1143 pub fn with_scenario(mut self, scenario: Scenario) -> Self {
1144 self.1 = Some(scenario);
1145 self
1146 }
1147
1148 pub fn show(&mut self, ui: &mut egui::Ui) {
1149 if let Some(scenario) = self.1 {
1150 scenario.show(&mut self.0, ui);
1151 } else {
1152 self.0.show(ui);
1153 }
1154 }
1155
1156 pub fn new(app: ArchiveApp, ctx: &egui::Context) -> Self {
1157 ctx.on_begin_pass(
1158 "ui-scenario-readonly",
1159 std::sync::Arc::new(|ctx| {
1160 ctx.input_mut(|i| {
1161 i.events.clear();
1162 i.pointer = Default::default();
1163 i.keys_down.clear();
1164 i.modifiers = Default::default();
1165 i.raw.dropped_files.clear();
1166 i.raw.hovered_files.clear();
1167 });
1168 }),
1169 );
1170 Self(app, None)
1171 }
1172}
1173impl eframe::App for Preview {
1174 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
1175 if root.ctx().input(|i| i.viewport().close_requested()) {
1176 root.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
1177 return;
1178 }
1179 self.show(root);
1180 }
1181}