team-ljyzipelo

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