team-ljyzipelo

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