team-ljyzipelo

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