team-ljyzipelo

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