team-ljyzipelo

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