team-ljyzipelo

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