team-ljyzipelo

공개
1,124줄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_with_frame(self, custom_frame: bool) -> ArchiveApp {
263 let mut app = self.build();
264 app.set_custom_frame(custom_frame);
265 app
266 }
267
268 /// 실제 파일과 작업자를 사용하지 않고 기존 화면 상태를 준비함.
269 pub fn build(self) -> ArchiveApp {
270 let factory = FakeFactory::manual();
271 let state = factory.state.clone();
272 let mut app = ArchiveApp::new(Box::new(factory), None, true);
273 let base = sample_root();
274 app.destination = base.join("풀린 자료");
275 app.automatic_destination = false;
276 app.zip_folder = base.clone();
277 app.zip_name = "여행 자료.zip".into();
278 if self.name == "empty" || self.name.starts_with("uninstall-") {
279 return app;
280 }
281 let archive = base.join(match self.name {
282 "gzip-conflict" | "gzip-conflict-choice" => "여행 자료.gz",
283 "tar-bz2" => "여행 자료.TAR.BZ2",
284 "tar-xz" => "여행 자료.TaR.Xz",
285 _ => "여행 자료.zip",
286 });
287 if matches!(self.name, "archive-loading" | "archive-loading-in-parent") {
288 app.set_work_window_in_parent(self.name == "archive-loading-in-parent");
289 app.open_path(archive);
290 {
291 let mut state = state.borrow_mut();
292 state.frame(Event::Accepted { encryption: false });
293 state.frame(Event::Progress {
294 stage: Stage::Read,
295 processed: 38 << 20,
296 total: Some(61 << 20),
297 completed_entries: 0,
298 });
299 }
300 for _ in 0..64 {
301 app.model.poll();
302 }
303 return app;
304 }
305 app.model.archive = Some(archive.clone());
306 app.model.entries = entries(self.name == "many-items");
307 app.model.list_id = Some(ListId {
308 catalog_version: 1,
309 format: Format::Zip,
310 source_object: SourceObject::Unix {
311 device: 1,
312 inode: 1,
313 },
314 archive_bytes: 2_700_000,
315 archive_sha256: [7; 32],
316 });
317 app.model.confirmed = true;
318 if self.name.starts_with("split-") {
319 let archive = base.join(if self.name == "split-unsupported" {
320 "여행.zip.001"
321 } else {
322 "여행.7z.001"
323 });
324 app.model.archive = Some(archive.clone());
325 app.model.list_id = Some(ListId {
326 catalog_version: 2,
327 format: Format::SevenZip,
328 source_object: SourceObject::SplitSevenZip {
329 manifest_sha256: [9; 32],
330 },
331 archive_bytes: 2_700_000,
332 archive_sha256: [7; 32],
333 });
334 if self.name == "split-archive" {
335 app.model.selected.insert(1);
336 return app;
337 }
338 app.start(Start::List { archive });
339 let mut state = state.borrow_mut();
340 state.frame(Event::Accepted { encryption: false });
341 let reason = match self.name {
342 "split-first-volume" => Some(VolumeProblemReason::FirstVolumeRequired),
343 "split-missing-volume" => Some(VolumeProblemReason::MissingVolume),
344 "split-incomplete" => Some(VolumeProblemReason::IncompleteSet),
345 _ => None,
346 };
347 let error = match reason {
348 Some(VolumeProblemReason::FirstVolumeRequired) => ErrorCode::InvalidRequest,
349 Some(VolumeProblemReason::MissingVolume) => ErrorCode::MissingVolume,
350 Some(VolumeProblemReason::IncompleteSet) => ErrorCode::Integrity,
351 None if self.name == "split-source-changed" => ErrorCode::SourceChanged,
352 None => ErrorCode::UnsupportedFeature,
353 };
354 if let Some(reason) = reason {
355 state.frame(Event::VolumeProblem(VolumeProblem {
356 reason,
357 volume: NativePath::Unix(if reason == VolumeProblemReason::MissingVolume {
358 "여행.7z.003".as_bytes().to_vec()
359 } else {
360 "여행.7z.001".as_bytes().to_vec()
361 }),
362 }));
363 }
364 state.frame(Event::Terminal(Terminal {
365 outcome: Outcome::Failed,
366 error: Some(error),
367 publication: Publication::None,
368 created_count: 0,
369 retained_partial_count: 0,
370 durability: Durability::NotApplicable,
371 cleanup: Cleanup::Complete,
372 }));
373 state.queue.push_back(HostEvent::StdoutEof);
374 state.queue.push_back(HostEvent::StderrEof);
375 state.queue.push_back(HostEvent::Exited { success: true });
376 drop(state);
377 for _ in 0..32 {
378 app.model.poll();
379 }
380 return app;
381 }
382 if self.name.starts_with("preview-") {
383 app.model.selected = BTreeSet::from([1]);
384 if self.name == "preview-implicit-folder" {
385 app.model.entries.truncate(1);
386 app.model.entries[0].id = 1;
387 app.model.entries[0].name = "자료/안내.txt".into();
388 app.model.entries[0].kind = Kind::File;
389 return app;
390 }
391 if self.name == "preview-selection" {
392 app.model.selected.insert(0);
393 return app;
394 }
395 if self.name == "preview-catalog-approval" {
396 let template = app.model.entries[1].clone();
397 app.model.entries = (0..10_001)
398 .map(|id| Entry {
399 id,
400 name: if id == 1 {
401 "읽어주세요.txt".into()
402 } else {
403 format!("{id}.bin")
404 },
405 bytes: Some(if id == 1 { 7 } else { 0 }),
406 ..template.clone()
407 })
408 .collect();
409 }
410 if self.name == "preview-catalog-bytes-approval" {
411 app.model.entries.truncate(2);
412 app.model.entries[0].bytes = Some(16 * 1024 * 1024 * 1024);
413 app.model.entries[1].bytes = Some(7);
414 }
415 app.begin_preview(&egui::Context::default());
416 if matches!(
417 self.name,
418 "preview-catalog-approval" | "preview-catalog-bytes-approval"
419 ) {
420 let mut state = state.borrow_mut();
421 state.frame(Event::Accepted { encryption: false });
422 state.frame(Event::ResourceRequired(ResourceChallenge {
423 id: 1,
424 action: ActionKind::Preview,
425 scope: ResourceScope {
426 output: true,
427 entries: true,
428 ..ResourceScope::default()
429 },
430 usage: ResourceUsage::default(),
431 soft_limits: Limits::default(),
432 ceiling: Limits {
433 input: u64::MAX,
434 output: 64 * 1024 * 1024 * 1024,
435 entries: 200_000,
436 },
437 }));
438 drop(state);
439 for _ in 0..32 {
440 app.model.poll();
441 }
442 return app;
443 }
444 {
445 let mut state = state.borrow_mut();
446 state.frame(Event::Accepted { encryption: false });
447 if self.name != "preview-loading" {
448 let error = match self.name {
449 "preview-limit" => Some(ErrorCode::Limit),
450 "preview-damaged" => Some(ErrorCode::Integrity),
451 "preview-unsupported" => Some(ErrorCode::UnsupportedFeature),
452 _ => None,
453 };
454 if error.is_none() {
455 use sha2::{Digest, Sha256};
456 let image = self.name == "preview-image";
457 let data = if image {
458 (0..128 * 96)
459 .flat_map(|i| {
460 if (i / 128 / 16 + i % 128 / 16) % 2 == 0 {
461 [37, 99, 235, 255]
462 } else {
463 [232, 240, 254, 255]
464 }
465 })
466 .collect::<Vec<_>>()
467 } else if self.name == "preview-empty" {
468 Vec::new()
469 } else {
470 "여행 준비 목록\n\n기차표 확인\n카메라 배터리 충전\n"
471 .as_bytes()
472 .to_vec()
473 };
474 let info = PreviewInfo {
475 entry_id: 1,
476 format: if image {
477 PreviewFormat::Rgba8
478 } else {
479 PreviewFormat::Utf8Text
480 },
481 total_bytes: data.len() as u64,
482 width: if image { 128 } else { 0 },
483 height: if image { 96 } else { 0 },
484 };
485 state.frame(Event::PreviewBegin(info));
486 for (offset, chunk) in data.chunks(32768).enumerate() {
487 state.frame(Event::PreviewChunk {
488 entry_id: 1,
489 offset: (offset * 32768) as u64,
490 data: chunk.to_vec(),
491 });
492 }
493 state.frame(Event::PreviewEnd {
494 entry_id: 1,
495 total_bytes: info.total_bytes,
496 sha256: Sha256::digest(&data).into(),
497 });
498 }
499 state.frame(Event::Terminal(Terminal {
500 outcome: if error.is_some() {
501 Outcome::Failed
502 } else {
503 Outcome::Completed
504 },
505 error,
506 publication: Publication::None,
507 created_count: 0,
508 retained_partial_count: 0,
509 durability: Durability::NotApplicable,
510 cleanup: Cleanup::Complete,
511 }));
512 state.queue.push_back(HostEvent::StdoutEof);
513 state.queue.push_back(HostEvent::StderrEof);
514 state.queue.push_back(HostEvent::Exited { success: true });
515 }
516 }
517 for _ in 0..32 {
518 app.model.poll();
519 }
520 return app;
521 }
522 match self.name {
523 "tar-bz2" | "tar-xz" => {
524 app.model.list_id.as_mut().unwrap().format = Format::Tar;
525 for entry in &mut app.model.entries {
526 entry.encrypted = false;
527 }
528 app.destination = present::default_destination(&archive);
529 app.automatic_destination = true;
530 return app;
531 }
532 "archive" | "many-items" => return app,
533 "folder-empty" => {
534 app.browse_folder("빈 폴더");
535 return app;
536 }
537 "dialog-error" => {
538 app.ui_error = Some(DIALOG_UNAVAILABLE.into());
539 return app;
540 }
541 "folder" => {
542 app.browse_folder("사진");
543 return app;
544 }
545 "search-empty" => {
546 app.search = "없는 파일".into();
547 return app;
548 }
549 "selection" | "marquee" => {
550 app.model
551 .selected
552 .extend([0, 3, 4, if self.name == "marquee" { 2 } else { 1 }]);
553 if self.name == "marquee" {
554 app.scenario_marquee = Some(egui::Rect::from_min_size(
555 egui::pos2(22.0, 8.0),
556 egui::vec2(360.0, 62.0),
557 ));
558 }
559 return app;
560 }
561 "create" | "create-encrypted" | "create-sevenzip" => {
562 app.sources = vec![base.join("읽어주세요.txt"), base.join("사진")];
563 app.scenario_sources = Some(std::rc::Rc::new(vec![
564 SourceRow {
565 name: "사진".into(),
566 directory: true,
567 bytes: Some(0),
568 },
569 SourceRow {
570 name: "읽어주세요.txt".into(),
571 directory: false,
572 bytes: Some(4096),
573 },
574 ]));
575 app.show_create(self.name == "create-encrypted");
576 app.set_seven_zip(self.name == "create-sevenzip");
577 return app;
578 }
579 _ => {}
580 }
581 if self.name.starts_with("recovery-") {
582 let request = Start::RecoverZip {
583 archive,
584 output_file: base.join("복구본.zip"),
585 };
586 app.last_request = Some(request.clone());
587 app.model.begin(request, app.factory.as_mut());
588 let mut state = state.borrow_mut();
589 state.frame(Event::Accepted { encryption: false });
590 if self.name == "recovery-resource" {
591 state.frame(Event::ResourceRequired(ResourceChallenge {
592 id: 1,
593 action: ActionKind::RecoverZip,
594 scope: ResourceScope {
595 ratio: true,
596 ..Default::default()
597 },
598 usage: ResourceUsage::default(),
599 soft_limits: Limits::default(),
600 ceiling: Limits::default(),
601 }));
602 } else if self.name == "recovery-progress" {
603 state.frame(Event::Progress {
604 stage: Stage::Scan,
605 processed: 1024,
606 total: None,
607 completed_entries: 1,
608 });
609 } else if self.name == "recovery-cancelled" {
610 state.finish(Outcome::Cancelled, Publication::None);
611 } else {
612 let impossible = self.name == "recovery-impossible";
613 let partial = self.name == "recovery-partial";
614 let unknown = self.name == "recovery-unknown";
615 let retained = self.name == "recovery-retained";
616 let failed = self.name == "recovery-save-error" || retained;
617 state.frame(Event::RecoveryEntry(RecoveryEntry {
618 candidate_id: 0,
619 source_offset: 0,
620 name: Some("읽어주세요.txt".into()),
621 kind: Some(worker_protocol::protocol::EntryKind::File),
622 status: if impossible {
623 RecoveryStatus::Lost
624 } else {
625 RecoveryStatus::Verified
626 },
627 reason: if impossible {
628 RecoveryReason::Truncated
629 } else {
630 RecoveryReason::HeaderRebuilt
631 },
632 declared_size: Some(4),
633 verified_size: (!impossible).then_some(4),
634 sha256: (!impossible).then_some([1; 32]),
635 }));
636 if partial {
637 state.frame(Event::RecoveryEntry(RecoveryEntry {
638 candidate_id: 1,
639 source_offset: 128,
640 name: Some("사진.png".into()),
641 kind: Some(worker_protocol::protocol::EntryKind::File),
642 status: RecoveryStatus::Lost,
643 reason: RecoveryReason::CrcMismatch,
644 declared_size: Some(10),
645 verified_size: None,
646 sha256: None,
647 }));
648 }
649 state.frame(Event::RecoveryEnd(RecoveryEnd {
650 mode: if unknown {
651 RecoveryMode::LocalChain
652 } else {
653 RecoveryMode::CentralDirectory
654 },
655 source_bytes: 256,
656 source_sha256: [2; 32],
657 known_entries: (!unknown).then_some(if partial { 2 } else { 1 }),
658 verified_entries: u32::from(!impossible),
659 lost_entries: u32::from(impossible || partial),
660 unverified_entries: 0,
661 unknown_loss: unknown,
662 }));
663 if !impossible && !failed {
664 state.frame(Event::Output {
665 entry_id: None,
666 relative_name: "복구본.zip".into(),
667 disposition: Disposition::Created,
668 });
669 }
670 if retained {
671 state.frame(Event::Output {
672 entry_id: None,
673 relative_name: ".zipelo-42-1.tmp".into(),
674 disposition: Disposition::PartialRetained,
675 });
676 }
677 state.frame(Event::Terminal(Terminal {
678 outcome: if partial || unknown || impossible || failed {
679 Outcome::Failed
680 } else {
681 Outcome::Completed
682 },
683 error: if failed {
684 Some(ErrorCode::DiskFull)
685 } else if impossible {
686 Some(ErrorCode::RecoveryImpossible)
687 } else if partial || unknown {
688 Some(ErrorCode::RecoveryIncomplete)
689 } else {
690 None
691 },
692 publication: if impossible || failed {
693 Publication::None
694 } else {
695 Publication::Complete
696 },
697 created_count: u64::from(!impossible && !failed),
698 retained_partial_count: u64::from(retained),
699 durability: if impossible || failed {
700 Durability::NotApplicable
701 } else {
702 Durability::Synced
703 },
704 cleanup: if retained {
705 Cleanup::Failed
706 } else {
707 Cleanup::Complete
708 },
709 }));
710 state.queue.extend([
711 HostEvent::StdoutEof,
712 HostEvent::StderrEof,
713 HostEvent::Exited { success: true },
714 ]);
715 }
716 drop(state);
717 for _ in 0..30 {
718 app.model.poll();
719 }
720 return app;
721 }
722 let seven_zip = self.name.starts_with("create-sevenzip");
723 let creating = self.name.starts_with("create-") || self.name == "password-create";
724 let listing_error = matches!(self.name, "unsupported" | "damaged");
725 if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
726 app.model.list_id.as_mut().unwrap().format = Format::Gzip;
727 app.model.entries = vec![Entry {
728 id: 0,
729 name: "여행 자료".into(),
730 kind: Kind::File,
731 bytes: Some(1_287_952),
732 packed: Some(900_000),
733 encrypted: false,
734 }];
735 app.gzip_name = "여행 자료".into();
736 }
737 let request = if seven_zip {
738 Start::CreateSevenZip {
739 sources: vec![(base.join("사진"), "사진".into())],
740 output_file: base.join("여행 자료.7z"),
741 }
742 } else if creating {
743 Start::CreateZip {
744 sources: vec![(base.join("사진"), "사진".into())],
745 output_file: base.join("여행 자료.zip"),
746 method: Method::Deflate,
747 aes256: self.name == "password-create",
748 }
749 } else if listing_error {
750 Start::List { archive }
751 } else {
752 Start::Extract {
753 archive,
754 destination: app.destination.clone(),
755 selection: Selection::All,
756 list_id: app.model.list_id.clone().unwrap(),
757 gzip_output_name: (matches!(self.name, "gzip-conflict" | "gzip-conflict-choice"))
758 .then(|| app.gzip_name.clone()),
759 }
760 };
761 app.targets = Some(if creating {
762 BTreeSet::from([if seven_zip {
763 "여행 자료.7z"
764 } else {
765 "여행 자료.zip"
766 }
767 .into()])
768 } else if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
769 BTreeSet::from(["여행 자료".into()])
770 } else {
771 BTreeSet::from([
772 "읽어주세요.txt".into(),
773 "여행 일정.pdf".into(),
774 "사진/바다.jpg".into(),
775 "사진/풍경.jpg".into(),
776 ])
777 });
778 if matches!(
779 self.name,
780 "extract-skipped" | "extract-renamed" | "extract-rename-failed"
781 ) {
782 app.targets = Some(["읽어주세요.txt".into()].into_iter().collect());
783 app.directories.clear();
784 }
785 if self.name == "resource-approval" {
786 app.model.entries[1].bytes = Some(17 * 1024 * 1024 * 1024);
787 }
788 assert!(app.start(request));
789 {
790 let mut state = state.borrow_mut();
791 state.frame(Event::Accepted {
792 encryption: !seven_zip,
793 });
794 match self.name {
795 "resource-approval" | "resource-ratio" | "create-sevenzip-resource" => {
796 let expanded = self.name != "resource-ratio";
797 state.frame(Event::ResourceRequired(ResourceChallenge {
798 id: 1,
799 action: if seven_zip {
800 ActionKind::CreateSevenZip
801 } else {
802 ActionKind::Extract
803 },
804 scope: ResourceScope {
805 output: expanded,
806 entries: expanded,
807 ratio: !expanded,
808 },
809 usage: ResourceUsage {
810 available_bytes: Some(90 * 1024 * 1024 * 1024),
811 actual_bytes: (!expanded).then_some(300 * 1024 * 1024),
812 ratio_output_bytes: (!expanded).then_some(300 * 1024 * 1024),
813 compressed_bytes: (!expanded).then_some(4096),
814 ..ResourceUsage::default()
815 },
816 soft_limits: Limits::default(),
817 ceiling: if expanded {
818 Limits {
819 input: u64::MAX,
820 output: 64 * 1024 * 1024 * 1024,
821 entries: 200_000,
822 }
823 } else {
824 Limits::default()
825 },
826 }));
827 }
828 "resource-retry" | "resource-partial" => {
829 let partial = self.name == "resource-partial";
830 if partial {
831 state.frame(Event::Output {
832 entry_id: Some(1),
833 relative_name: "읽어주세요.txt".into(),
834 disposition: Disposition::Created,
835 });
836 }
837 state.frame(Event::Terminal(Terminal {
838 outcome: Outcome::Failed,
839 error: Some(ErrorCode::Limit),
840 publication: if partial {
841 Publication::Partial
842 } else {
843 Publication::None
844 },
845 created_count: u64::from(partial),
846 retained_partial_count: 0,
847 durability: Durability::Synced,
848 cleanup: Cleanup::Complete,
849 }));
850 state.queue.extend([
851 HostEvent::StdoutEof,
852 HostEvent::StderrEof,
853 HostEvent::Exited { success: true },
854 ]);
855 }
856 "conflict-choice" | "conflict-apply" | "gzip-conflict-choice" => {
857 state.frame(Event::ConflictRequired(Conflict {
858 challenge_id: 29,
859 entry_id: if self.name == "gzip-conflict-choice" {
860 0
861 } else {
862 1
863 },
864 relative_name: if self.name == "gzip-conflict-choice" {
865 "여행 자료"
866 } else {
867 "읽어주세요.txt"
868 }
869 .into(),
870 incoming_size: 1_287_952,
871 existing_size: 2048,
872 }));
873 }
874 "extract-skipped" | "extract-renamed" | "extract-rename-failed" => {
875 let failed = self.name == "extract-rename-failed";
876 let skip = self.name == "extract-skipped";
877 let name = if skip {
878 "읽어주세요.txt"
879 } else {
880 "읽어주세요 (1).txt"
881 };
882 state.frame(Event::ConflictResolved(Resolution {
883 entry_id: 1,
884 relative_name: name.into(),
885 choice: if skip {
886 ConflictChoice::Skip
887 } else {
888 ConflictChoice::Rename
889 },
890 }));
891 if !skip && !failed {
892 state.frame(Event::Output {
893 entry_id: Some(1),
894 relative_name: name.into(),
895 disposition: Disposition::Created,
896 });
897 }
898 state.frame(Event::Terminal(Terminal {
899 outcome: if failed {
900 Outcome::Failed
901 } else {
902 Outcome::Completed
903 },
904 error: failed.then_some(ErrorCode::Io),
905 publication: if skip || failed {
906 Publication::None
907 } else {
908 Publication::Complete
909 },
910 created_count: u64::from(!skip && !failed),
911 retained_partial_count: 0,
912 durability: if skip || failed {
913 Durability::NotApplicable
914 } else {
915 Durability::Synced
916 },
917 cleanup: Cleanup::Complete,
918 }));
919 state.queue.extend([
920 HostEvent::StdoutEof,
921 HostEvent::StderrEof,
922 HostEvent::Exited { success: true },
923 ]);
924 }
925 "password" | "password-retry" | "password-create" => {
926 state.frame(Event::PasswordRequired {
927 challenge_id: 17,
928 attempt: if self.name == "password-retry" { 2 } else { 1 },
929 encrypt: self.name == "password-create",
930 })
931 }
932 "extract-complete"
933 | "create-complete"
934 | "create-sevenzip-complete"
935 | "extract-unsynced"
936 | "extract-complete-cleanup-failed" => {
937 let names = app.targets.as_ref().unwrap();
938 for name in names {
939 state.frame(Event::Output {
940 entry_id: None,
941 relative_name: name.clone(),
942 disposition: Disposition::Created,
943 });
944 }
945 state.frame(Event::Terminal(Terminal {
946 outcome: Outcome::Completed,
947 error: None,
948 publication: Publication::Complete,
949 created_count: names.len() as u64,
950 retained_partial_count: 0,
951 durability: if self.name == "extract-unsynced" {
952 Durability::Unconfirmed
953 } else {
954 Durability::Synced
955 },
956 cleanup: if self.name == "extract-complete-cleanup-failed" {
957 Cleanup::Failed
958 } else {
959 Cleanup::Complete
960 },
961 }));
962 state.queue.extend([
963 HostEvent::StdoutEof,
964 HostEvent::StderrEof,
965 HostEvent::Exited { success: true },
966 ]);
967 }
968 "extract-cancelled" | "create-sevenzip-cancelled" => {
969 state.finish(Outcome::Cancelled, Publication::None)
970 }
971 "extract-partial" | "extract-uncertain" => {
972 let partial = self.name == "extract-partial";
973 if partial {
974 state.frame(Event::Output {
975 entry_id: Some(1),
976 relative_name: "읽어주세요.txt".into(),
977 disposition: Disposition::Created,
978 });
979 }
980 state.frame(Event::Terminal(Terminal {
981 outcome: Outcome::Failed,
982 error: Some(ErrorCode::Io),
983 publication: if partial {
984 Publication::Partial
985 } else {
986 Publication::Uncertain
987 },
988 created_count: u64::from(partial),
989 retained_partial_count: 0,
990 durability: Durability::Synced,
991 cleanup: Cleanup::Complete,
992 }));
993 state.queue.extend([
994 HostEvent::StdoutEof,
995 HostEvent::StderrEof,
996 HostEvent::Exited { success: true },
997 ]);
998 }
999 "extract-disk-full" | "extract-cleanup-failed" => {
1000 state.frame(Event::Terminal(Terminal {
1001 outcome: Outcome::Failed,
1002 error: Some(if self.name == "extract-disk-full" {
1003 ErrorCode::DiskFull
1004 } else {
1005 ErrorCode::Io
1006 }),
1007 publication: Publication::None,
1008 created_count: 0,
1009 retained_partial_count: 0,
1010 durability: Durability::NotApplicable,
1011 cleanup: if self.name == "extract-cleanup-failed" {
1012 Cleanup::Failed
1013 } else {
1014 Cleanup::Complete
1015 },
1016 }));
1017 state.queue.extend([
1018 HostEvent::StdoutEof,
1019 HostEvent::StderrEof,
1020 HostEvent::Exited { success: true },
1021 ]);
1022 }
1023 "conflict"
1024 | "gzip-conflict"
1025 | "unsupported"
1026 | "damaged"
1027 | "source-changed"
1028 | "create-error"
1029 | "create-sevenzip-error" => {
1030 state.frame(Event::Terminal(Terminal {
1031 outcome: Outcome::Failed,
1032 error: Some(match self.name {
1033 "conflict" | "gzip-conflict" => ErrorCode::Conflict,
1034 "source-changed" => ErrorCode::SourceChanged,
1035 "create-error" | "create-sevenzip-error" => ErrorCode::DiskFull,
1036 "unsupported" => ErrorCode::UnsupportedFormat,
1037 _ => ErrorCode::Integrity,
1038 }),
1039 publication: Publication::None,
1040 created_count: 0,
1041 retained_partial_count: 0,
1042 durability: Durability::NotApplicable,
1043 cleanup: Cleanup::Complete,
1044 }));
1045 state.queue.extend([
1046 HostEvent::StdoutEof,
1047 HostEvent::StderrEof,
1048 HostEvent::Exited { success: true },
1049 ]);
1050 }
1051 _ => state.frame(Event::Progress {
1052 stage: if creating {
1053 Stage::Write
1054 } else {
1055 Stage::Decode
1056 },
1057 processed: 38 << 20,
1058 total: (self.name != "extract-unknown").then_some(61 << 20),
1059 completed_entries: 12,
1060 }),
1061 }
1062 }
1063 for _ in 0..64 {
1064 app.model.poll();
1065 }
1066 if self.name == "conflict-apply" {
1067 app.conflict_challenge = Some((app.model.job_id().unwrap(), 29));
1068 app.conflict_apply = true;
1069 }
1070 if self.name == "extract-unsynced" {
1071 app.details = true;
1072 }
1073 if self.name == "cancelling" {
1074 app.model.cancel();
1075 }
1076 if self.name == "close-confirm" {
1077 app.model.request_close();
1078 }
1079 app
1080 }
1081}
1082
1083/// 화면을 고정하고 실제 파일 조작을 막는 미리보기임.
1084pub struct Preview(pub ArchiveApp, Option<Scenario>);
1085impl Preview {
1086 pub fn with_scenario(mut self, scenario: Scenario) -> Self {
1087 self.1 = Some(scenario);
1088 self
1089 }
1090
1091 pub fn show(&mut self, ui: &mut egui::Ui) {
1092 if let Some(scenario) = self.1 {
1093 scenario.show(&mut self.0, ui);
1094 } else {
1095 self.0.show(ui);
1096 }
1097 }
1098
1099 pub fn new(app: ArchiveApp, ctx: &egui::Context) -> Self {
1100 ctx.on_begin_pass(
1101 "ui-scenario-readonly",
1102 std::sync::Arc::new(|ctx| {
1103 ctx.input_mut(|i| {
1104 i.events.clear();
1105 i.pointer = Default::default();
1106 i.keys_down.clear();
1107 i.modifiers = Default::default();
1108 i.raw.dropped_files.clear();
1109 i.raw.hovered_files.clear();
1110 });
1111 }),
1112 );
1113 Self(app, None)
1114 }
1115}
1116impl eframe::App for Preview {
1117 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
1118 if root.ctx().input(|i| i.viewport().close_requested()) {
1119 root.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
1120 return;
1121 }
1122 self.show(root);
1123 }
1124}