team-ljyzipelo

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