team-ljyzipelo

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