team-ljyzipelo

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