team-ljyzipelo

공개
587줄23 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 "resource-approval" => "처리 전 큰 작업 승인",
25 "resource-ratio" => "고압축 작업 경고와 미확인 값",
26 "resource-retry" => "주 창 모달에서 출력 없는 한도 실패 후 확대 재시도",
27 "resource-partial" => "주 창 모달에서 일부 출력 후 한도 중단",
28 "gzip-conflict-choice" => "단일 GZ 파일의 충돌 선택",
29 "conflict-choice" => "같은 이름 파일의 세 가지 처리 선택",
30 "conflict-apply" => "남은 충돌에 같은 선택 적용",
31 "extract-skipped" => "모든 파일을 건너뛴 정상 완료",
32 "extract-renamed" => "이름을 바꿔 저장한 완료 결과",
33 "extract-rename-failed" => "새 이름을 정한 뒤 저장 전 I/O 실패",
34 "empty" => "빈 첫 화면",
35 "archive" => "폴더와 파일이 있는 압축파일",
36 "tar-bz2" => "TAR.BZ2 목록과 자동 해제 폴더",
37 "tar-xz" => "TAR.XZ 목록과 자동 해제 폴더",
38 "folder" => "사진 하위 폴더",
39 "many-items" => "500개 항목과 세로 스크롤",
40 "selection" => "여러 파일과 폴더 선택",
41 "marquee" => "반투명 사각형으로 끌어서 선택 중",
42 "search-empty" => "검색 결과 없음",
43 "password" => "압축 해제 암호 입력",
44 "password-retry" => "암호가 틀린 뒤 다시 입력",
45 "extract-progress" => "압축 해제 진행률 62%",
46 "extract-unknown" => "전체 크기를 모르는 압축 해제",
47 "extract-complete" => "압축 해제 완료",
48 "extract-cancelled" => "압축 해제 취소 완료",
49 "cancelling" => "취소 요청 후 작업 종료 대기",
50 "conflict" => "같은 이름 파일 충돌",
51 "unsupported" => "지원하지 않는 압축 형식",
52 "damaged" => "손상된 압축파일",
53 "create" => "암호 없는 ZIP 만들기 창",
54 "create-encrypted" => "암호 설정이 켜진 ZIP 만들기 창",
55 "create-progress" => "ZIP 만들기 진행률 62%",
56 "create-complete" => "ZIP 만들기 완료",
57 "folder-empty" => "항목이 없는 하위 폴더",
58 "gzip-conflict" => "단일 GZ 파일 이름 충돌",
59 "extract-partial" => "일부 파일만 풀린 결과",
60 "extract-uncertain" => "저장 여부를 확인할 수 없는 결과",
61 "extract-unsynced" => "완료 뒤 저장 확인 경고의 상세 정보",
62 "source-changed" => "목록을 연 뒤 원본이 바뀐 오류",
63 "dialog-error" => "운영체제 파일 선택 창 실행 실패",
64 "create-error" => "ZIP 만들기 중 디스크 공간 부족",
65 "password-create" => "암호 ZIP 생성의 작업자 암호 요청",
66 "close-confirm" => "진행 중 창 닫기 확인",
67}
68
69pub fn listing() -> String {
70 SCENARIOS
71 .iter()
72 .map(|s| format!("{}\t{}\n", s.name, s.description))
73 .collect()
74}
75
76pub fn parse(name: &str) -> Result<Scenario, String> {
77 SCENARIOS
78 .iter()
79 .copied()
80 .find(|s| s.name == name)
81 .ok_or_else(|| {
82 format!(
83 "알 수 없는 UI 상황: {name}\n사용 가능한 상황:\n{}",
84 listing()
85 )
86 })
87}
88
89#[derive(Debug, PartialEq)]
90pub enum Launch {
91 Normal(Vec<OsString>),
92 Scenario(Scenario),
93 List,
94}
95
96pub fn launch(args: Vec<OsString>) -> Result<Launch, String> {
97 let requested = args
98 .iter()
99 .any(|a| a == "--ui-scenario" || a == "--list-ui-scenarios");
100 if !requested {
101 return Ok(Launch::Normal(args));
102 }
103 if args.len() == 1 && args[0] == "--list-ui-scenarios" {
104 return Ok(Launch::List);
105 }
106 if args.len() == 2 && args[0] == "--ui-scenario" {
107 return args[1]
108 .to_str()
109 .ok_or_else(|| format!("상황 이름은 UTF-8이어야 합니다\n{}", listing()))
110 .and_then(parse)
111 .map(Launch::Scenario);
112 }
113 Err(format!(
114 "사용법: --ui-scenario <이름> 또는 --list-ui-scenarios\n{}",
115 listing()
116 ))
117}
118
119fn sample_root() -> PathBuf {
120 PathBuf::from(if cfg!(target_os = "windows") {
121 "C:\\Samples"
122 } else {
123 "/Samples"
124 })
125}
126
127fn entries(many: bool) -> Vec<Entry> {
128 let mut entries = vec![
129 ("사진", Kind::Directory),
130 ("읽어주세요.txt", Kind::File),
131 ("여행 일정.pdf", Kind::File),
132 ("사진/바다.jpg", Kind::File),
133 ("사진/풍경.jpg", Kind::File),
134 ]
135 .into_iter()
136 .enumerate()
137 .map(|(id, (name, kind))| Entry {
138 id: id as u32,
139 name: name.into(),
140 kind,
141 bytes: Some(if kind == Kind::Directory {
142 0
143 } else {
144 1_287_952
145 }),
146 packed: Some(900_000),
147 encrypted: id == 2,
148 })
149 .collect::<Vec<_>>();
150 if many {
151 entries.extend((5..505).map(|id| Entry {
152 id,
153 name: format!("자료-{id:03}.txt"),
154 kind: Kind::File,
155 bytes: Some(4096),
156 packed: Some(1800),
157 encrypted: false,
158 }));
159 }
160 entries
161}
162
163impl Scenario {
164 /// 실제 파일과 작업자를 사용하지 않고 기존 화면 상태를 준비함.
165 pub fn build(self) -> ArchiveApp {
166 let factory = FakeFactory::manual();
167 let state = factory.state.clone();
168 let mut app = ArchiveApp::new(Box::new(factory), None, true);
169 let base = sample_root();
170 app.destination = base.join("풀린 자료");
171 app.automatic_destination = false;
172 app.zip_folder = base.clone();
173 app.zip_name = "여행 자료.zip".into();
174 if self.name == "empty" {
175 return app;
176 }
177 let archive = base.join(match self.name {
178 "gzip-conflict" | "gzip-conflict-choice" => "여행 자료.gz",
179 "tar-bz2" => "여행 자료.TAR.BZ2",
180 "tar-xz" => "여행 자료.TaR.Xz",
181 _ => "여행 자료.zip",
182 });
183 app.model.archive = Some(archive.clone());
184 app.model.entries = entries(self.name == "many-items");
185 app.model.list_id = Some(ListId {
186 catalog_version: 1,
187 format: Format::Zip,
188 source_object: SourceObject::Unix {
189 device: 1,
190 inode: 1,
191 },
192 archive_bytes: 2_700_000,
193 archive_sha256: [7; 32],
194 });
195 app.model.confirmed = true;
196 match self.name {
197 "tar-bz2" | "tar-xz" => {
198 app.model.list_id.as_mut().unwrap().format = Format::Tar;
199 for entry in &mut app.model.entries {
200 entry.encrypted = false;
201 }
202 app.destination = present::default_destination(&archive);
203 app.automatic_destination = true;
204 return app;
205 }
206 "archive" | "many-items" => return app,
207 "folder-empty" => {
208 app.browse_folder("빈 폴더");
209 return app;
210 }
211 "dialog-error" => {
212 app.ui_error = Some(DIALOG_UNAVAILABLE.into());
213 return app;
214 }
215 "folder" => {
216 app.browse_folder("사진");
217 return app;
218 }
219 "search-empty" => {
220 app.search = "없는 파일".into();
221 return app;
222 }
223 "selection" | "marquee" => {
224 app.model
225 .selected
226 .extend([0, 3, 4, if self.name == "marquee" { 2 } else { 1 }]);
227 if self.name == "marquee" {
228 app.scenario_marquee = Some(egui::Rect::from_min_size(
229 egui::pos2(22.0, 8.0),
230 egui::vec2(360.0, 62.0),
231 ));
232 }
233 return app;
234 }
235 "create" | "create-encrypted" => {
236 app.sources = vec![base.join("읽어주세요.txt"), base.join("사진")];
237 app.scenario_sources = Some(std::rc::Rc::new(vec![
238 SourceRow {
239 name: "사진".into(),
240 directory: true,
241 bytes: Some(0),
242 },
243 SourceRow {
244 name: "읽어주세요.txt".into(),
245 directory: false,
246 bytes: Some(4096),
247 },
248 ]));
249 app.show_create(self.name == "create-encrypted");
250 return app;
251 }
252 _ => {}
253 }
254 let creating = self.name.starts_with("create-") || self.name == "password-create";
255 let listing_error = matches!(self.name, "unsupported" | "damaged");
256 if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
257 app.model.list_id.as_mut().unwrap().format = Format::Gzip;
258 app.model.entries = vec![Entry {
259 id: 0,
260 name: "여행 자료".into(),
261 kind: Kind::File,
262 bytes: Some(1_287_952),
263 packed: Some(900_000),
264 encrypted: false,
265 }];
266 app.gzip_name = "여행 자료".into();
267 }
268 let request = if creating {
269 Start::CreateZip {
270 sources: vec![(base.join("사진"), "사진".into())],
271 output_file: base.join("여행 자료.zip"),
272 method: Method::Deflate,
273 aes256: self.name == "password-create",
274 }
275 } else if listing_error {
276 Start::List { archive }
277 } else {
278 Start::Extract {
279 archive,
280 destination: app.destination.clone(),
281 selection: Selection::All,
282 list_id: app.model.list_id.clone().unwrap(),
283 gzip_output_name: (matches!(self.name, "gzip-conflict" | "gzip-conflict-choice"))
284 .then(|| app.gzip_name.clone()),
285 }
286 };
287 app.targets = Some(if creating {
288 BTreeSet::from(["여행 자료.zip".into()])
289 } else if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
290 BTreeSet::from(["여행 자료".into()])
291 } else {
292 BTreeSet::from([
293 "읽어주세요.txt".into(),
294 "여행 일정.pdf".into(),
295 "사진/바다.jpg".into(),
296 "사진/풍경.jpg".into(),
297 ])
298 });
299 if matches!(
300 self.name,
301 "extract-skipped" | "extract-renamed" | "extract-rename-failed"
302 ) {
303 app.targets = Some(["읽어주세요.txt".into()].into_iter().collect());
304 app.directories.clear();
305 }
306 if self.name == "resource-approval" {
307 app.model.entries[1].bytes = Some(17 * 1024 * 1024 * 1024);
308 }
309 assert!(app.start(request));
310 {
311 let mut state = state.borrow_mut();
312 state.frame(Event::Accepted { encryption: true });
313 match self.name {
314 "resource-approval" | "resource-ratio" => {
315 let expanded = self.name == "resource-approval";
316 state.frame(Event::ResourceRequired(ResourceChallenge {
317 id: 1,
318 action: ActionKind::Extract,
319 scope: ResourceScope {
320 output: expanded,
321 entries: expanded,
322 ratio: !expanded,
323 },
324 usage: ResourceUsage {
325 available_bytes: Some(90 * 1024 * 1024 * 1024),
326 actual_bytes: (!expanded).then_some(300 * 1024 * 1024),
327 ratio_output_bytes: (!expanded).then_some(300 * 1024 * 1024),
328 compressed_bytes: (!expanded).then_some(4096),
329 ..ResourceUsage::default()
330 },
331 soft_limits: Limits::default(),
332 ceiling: if expanded {
333 Limits {
334 input: u64::MAX,
335 output: 64 * 1024 * 1024 * 1024,
336 entries: 200_000,
337 }
338 } else {
339 Limits::default()
340 },
341 }));
342 }
343 "resource-retry" | "resource-partial" => {
344 let partial = self.name == "resource-partial";
345 if partial {
346 state.frame(Event::Output {
347 entry_id: Some(1),
348 relative_name: "읽어주세요.txt".into(),
349 disposition: Disposition::Created,
350 });
351 }
352 state.frame(Event::Terminal(Terminal {
353 outcome: Outcome::Failed,
354 error: Some(ErrorCode::Limit),
355 publication: if partial {
356 Publication::Partial
357 } else {
358 Publication::None
359 },
360 created_count: u64::from(partial),
361 retained_partial_count: 0,
362 durability: Durability::Synced,
363 cleanup: Cleanup::Complete,
364 }));
365 state.queue.extend([
366 HostEvent::StdoutEof,
367 HostEvent::StderrEof,
368 HostEvent::Exited { success: true },
369 ]);
370 }
371 "conflict-choice" | "conflict-apply" | "gzip-conflict-choice" => {
372 state.frame(Event::ConflictRequired(Conflict {
373 challenge_id: 29,
374 entry_id: if self.name == "gzip-conflict-choice" {
375 0
376 } else {
377 1
378 },
379 relative_name: if self.name == "gzip-conflict-choice" {
380 "여행 자료"
381 } else {
382 "읽어주세요.txt"
383 }
384 .into(),
385 incoming_size: 1_287_952,
386 existing_size: 2048,
387 }));
388 }
389 "extract-skipped" | "extract-renamed" | "extract-rename-failed" => {
390 let failed = self.name == "extract-rename-failed";
391 let skip = self.name == "extract-skipped";
392 let name = if skip {
393 "읽어주세요.txt"
394 } else {
395 "읽어주세요 (1).txt"
396 };
397 state.frame(Event::ConflictResolved(Resolution {
398 entry_id: 1,
399 relative_name: name.into(),
400 choice: if skip {
401 ConflictChoice::Skip
402 } else {
403 ConflictChoice::Rename
404 },
405 }));
406 if !skip && !failed {
407 state.frame(Event::Output {
408 entry_id: Some(1),
409 relative_name: name.into(),
410 disposition: Disposition::Created,
411 });
412 }
413 state.frame(Event::Terminal(Terminal {
414 outcome: if failed {
415 Outcome::Failed
416 } else {
417 Outcome::Completed
418 },
419 error: failed.then_some(ErrorCode::Io),
420 publication: if skip || failed {
421 Publication::None
422 } else {
423 Publication::Complete
424 },
425 created_count: u64::from(!skip && !failed),
426 retained_partial_count: 0,
427 durability: if skip || failed {
428 Durability::NotApplicable
429 } else {
430 Durability::Synced
431 },
432 cleanup: Cleanup::Complete,
433 }));
434 state.queue.extend([
435 HostEvent::StdoutEof,
436 HostEvent::StderrEof,
437 HostEvent::Exited { success: true },
438 ]);
439 }
440 "password" | "password-retry" | "password-create" => {
441 state.frame(Event::PasswordRequired {
442 challenge_id: 17,
443 attempt: if self.name == "password-retry" { 2 } else { 1 },
444 encrypt: self.name == "password-create",
445 })
446 }
447 "extract-complete" | "create-complete" | "extract-unsynced" => {
448 let names = app.targets.as_ref().unwrap();
449 for name in names {
450 state.frame(Event::Output {
451 entry_id: None,
452 relative_name: name.clone(),
453 disposition: Disposition::Created,
454 });
455 }
456 state.frame(Event::Terminal(Terminal {
457 outcome: Outcome::Completed,
458 error: None,
459 publication: Publication::Complete,
460 created_count: names.len() as u64,
461 retained_partial_count: 0,
462 durability: if self.name == "extract-unsynced" {
463 Durability::Unconfirmed
464 } else {
465 Durability::Synced
466 },
467 cleanup: Cleanup::Complete,
468 }));
469 state.queue.extend([
470 HostEvent::StdoutEof,
471 HostEvent::StderrEof,
472 HostEvent::Exited { success: true },
473 ]);
474 }
475 "extract-cancelled" => state.finish(Outcome::Cancelled, Publication::None),
476 "extract-partial" | "extract-uncertain" => {
477 let partial = self.name == "extract-partial";
478 if partial {
479 state.frame(Event::Output {
480 entry_id: Some(1),
481 relative_name: "읽어주세요.txt".into(),
482 disposition: Disposition::Created,
483 });
484 }
485 state.frame(Event::Terminal(Terminal {
486 outcome: Outcome::Failed,
487 error: Some(ErrorCode::Io),
488 publication: if partial {
489 Publication::Partial
490 } else {
491 Publication::Uncertain
492 },
493 created_count: u64::from(partial),
494 retained_partial_count: 0,
495 durability: Durability::Synced,
496 cleanup: Cleanup::Complete,
497 }));
498 state.queue.extend([
499 HostEvent::StdoutEof,
500 HostEvent::StderrEof,
501 HostEvent::Exited { success: true },
502 ]);
503 }
504 "conflict" | "gzip-conflict" | "unsupported" | "damaged" | "source-changed"
505 | "create-error" => {
506 state.frame(Event::Terminal(Terminal {
507 outcome: Outcome::Failed,
508 error: Some(match self.name {
509 "conflict" | "gzip-conflict" => ErrorCode::Conflict,
510 "source-changed" => ErrorCode::SourceChanged,
511 "create-error" => ErrorCode::DiskFull,
512 "unsupported" => ErrorCode::UnsupportedFormat,
513 _ => ErrorCode::Integrity,
514 }),
515 publication: Publication::None,
516 created_count: 0,
517 retained_partial_count: 0,
518 durability: Durability::NotApplicable,
519 cleanup: Cleanup::Complete,
520 }));
521 state.queue.extend([
522 HostEvent::StdoutEof,
523 HostEvent::StderrEof,
524 HostEvent::Exited { success: true },
525 ]);
526 }
527 _ => state.frame(Event::Progress {
528 stage: if creating {
529 Stage::Write
530 } else {
531 Stage::Decode
532 },
533 processed: 38 << 20,
534 total: (self.name != "extract-unknown").then_some(61 << 20),
535 completed_entries: 12,
536 }),
537 }
538 }
539 for _ in 0..64 {
540 app.model.poll();
541 }
542 if self.name == "conflict-apply" {
543 app.conflict_challenge = Some((app.model.job_id().unwrap(), 29));
544 app.conflict_apply = true;
545 }
546 if self.name == "extract-unsynced" {
547 app.details = true;
548 }
549 if self.name == "cancelling" {
550 app.model.cancel();
551 }
552 if self.name == "close-confirm" {
553 app.model.request_close();
554 }
555 app
556 }
557}
558
559/// 화면을 고정하고 실제 파일 조작을 막는 미리보기임.
560pub struct Preview(pub ArchiveApp);
561impl Preview {
562 pub fn new(app: ArchiveApp, ctx: &egui::Context) -> Self {
563 ctx.on_begin_pass(
564 "ui-scenario-readonly",
565 std::sync::Arc::new(|ctx| {
566 ctx.input_mut(|i| {
567 i.events.clear();
568 i.pointer = Default::default();
569 i.keys_down.clear();
570 i.modifiers = Default::default();
571 i.raw.dropped_files.clear();
572 i.raw.hovered_files.clear();
573 });
574 }),
575 );
576 Self(app)
577 }
578}
579impl eframe::App for Preview {
580 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
581 if root.ctx().input(|i| i.viewport().close_requested()) {
582 root.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
583 return;
584 }
585 self.0.show(root);
586 }
587}