team-ljyzipelo

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