team-ljyzipelo

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