team-ljyzipelo

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