team-ljyzipelo

공개
507줄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 "empty" => "빈 첫 화면",
25 "archive" => "폴더와 파일이 있는 압축파일",
26 "tar-bz2" => "TAR.BZ2 목록과 자동 해제 폴더",
27 "tar-xz" => "TAR.XZ 목록과 자동 해제 폴더",
28 "folder" => "사진 하위 폴더",
29 "many-items" => "500개 항목과 세로 스크롤",
30 "selection" => "여러 파일과 폴더 선택",
31 "marquee" => "반투명 사각형으로 끌어서 선택 중",
32 "search-empty" => "검색 결과 없음",
33 "password" => "압축 해제 암호 입력",
34 "password-retry" => "암호가 틀린 뒤 다시 입력",
35 "extract-progress" => "압축 해제 진행률 62%",
36 "extract-unknown" => "전체 크기를 모르는 압축 해제",
37 "extract-complete" => "압축 해제 완료",
38 "extract-cancelled" => "압축 해제 취소 완료",
39 "cancelling" => "취소 요청 후 작업 종료 대기",
40 "conflict" => "같은 이름 파일 충돌",
41 "unsupported" => "지원하지 않는 압축 형식",
42 "damaged" => "손상된 압축파일",
43 "create" => "암호 없는 ZIP 만들기 창",
44 "create-encrypted" => "암호 설정이 켜진 ZIP 만들기 창",
45 "create-progress" => "ZIP 만들기 진행률 62%",
46 "create-complete" => "ZIP 만들기 완료",
47 "folder-empty" => "항목이 없는 하위 폴더",
48 "gzip-conflict" => "단일 GZ 파일 이름 충돌",
49 "extract-partial" => "일부 파일만 풀린 결과",
50 "extract-uncertain" => "저장 여부를 확인할 수 없는 결과",
51 "extract-unsynced" => "완료 뒤 저장 확인 경고의 상세 정보",
52 "source-changed" => "목록을 연 뒤 원본이 바뀐 오류",
53 "dialog-error" => "운영체제 파일 선택 창 실행 실패",
54 "create-error" => "ZIP 만들기 중 디스크 공간 부족",
55 "password-create" => "암호 ZIP 생성의 작업자 암호 요청",
56 "close-confirm" => "진행 중 창 닫기 확인",
57 "uninstall-windows" => "Windows 제거 전 기본 앱 선택 안내",
58 "uninstall-settings-error" => "Windows 기본 앱 설정 실행 실패",
59 "uninstall-ubuntu-missing" => "Ubuntu 이전 기본 앱 복원 불가 안내",
60 "uninstall-ubuntu-unknown-user" => "Ubuntu 제거 사용자 확인 불가 안내",
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 /// 제거 안내는 외부 설치 화면의 문구만 재현하며 OS 동작은 실행하지 않음.
159 pub fn show(self, app: &mut ArchiveApp, ui: &mut egui::Ui) {
160 let (title, messages, button): (&str, Vec<&str>, Option<&str>) = match self.name {
161 "uninstall-windows" => (
162 "제거 전 기본 앱 선택",
163 vec![
164 "Zipelo를 기본 앱으로 사용했다면 제거 전에 다른 앱을 선택하세요. [기본 앱 설정 열기]에서 .zip, .7z, .tar, .gz, .tgz를 검색해 사용할 앱을 고를 수 있습니다. 다른 앱이 없으면 먼저 설치하세요.",
165 "직접 고른 기본 앱은 자동으로 바꾸지 않습니다. 제거 후 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [연결 프로그램]에서 다른 앱을 선택하세요.",
166 ],
167 Some("기본 앱 설정 열기"),
168 ),
169 "uninstall-settings-error" => (
170 "기본 앱 설정 실행 실패",
171 vec![
172 "Windows 설정을 열지 못했습니다. 설정 > 앱 > 기본 앱에서 확장자를 검색해 다른 앱을 선택하세요.",
173 ],
174 Some("확인"),
175 ),
176 "uninstall-ubuntu-missing" => (
177 "Ubuntu 제거 안내",
178 vec![
179 "Zipelo를 제거합니다. 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [다른 프로그램으로 열기]에서 다른 앱을 선택하세요.",
180 "이전 앱을 복원할 수 없습니다: application/zip. 파일을 오른쪽 클릭해 [다른 프로그램으로 열기]에서 앱을 선택하세요.",
181 ],
182 None,
183 ),
184 "uninstall-ubuntu-unknown-user" => (
185 "Ubuntu 제거 안내",
186 vec![
187 "Zipelo를 제거합니다. 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [다른 프로그램으로 열기]에서 다른 앱을 선택하세요.",
188 "제거를 요청한 사용자를 확인할 수 없어 사용자 기본 앱 설정은 변경하지 않습니다.",
189 ],
190 None,
191 ),
192 _ => {
193 app.show(ui);
194 return;
195 }
196 };
197 egui::CentralPanel::default().show_inside(ui, |ui| {
198 ui.add_space(16.0);
199 ui.heading(title);
200 ui.add_space(16.0);
201 for message in messages {
202 ui.label(message);
203 ui.add_space(16.0);
204 }
205 if let Some(button) = button {
206 // 미리보기에서는 설정 열기와 제거를 실행하지 않음.
207 let _ = ui.button(button);
208 }
209 });
210 }
211
212 /// 실제 파일과 작업자를 사용하지 않고 기존 화면 상태를 준비함.
213 pub fn build(self) -> ArchiveApp {
214 let factory = FakeFactory::manual();
215 let state = factory.state.clone();
216 let mut app = ArchiveApp::new(Box::new(factory), None, true);
217 let base = sample_root();
218 app.destination = base.join("풀린 자료");
219 app.automatic_destination = false;
220 app.zip_folder = base.clone();
221 app.zip_name = "여행 자료.zip".into();
222 if self.name == "empty" || self.name.starts_with("uninstall-") {
223 return app;
224 }
225 let archive = base.join(match self.name {
226 "gzip-conflict" => "여행 자료.gz",
227 "tar-bz2" => "여행 자료.TAR.BZ2",
228 "tar-xz" => "여행 자료.TaR.Xz",
229 _ => "여행 자료.zip",
230 });
231 app.model.archive = Some(archive.clone());
232 app.model.entries = entries(self.name == "many-items");
233 app.model.list_id = Some(ListId {
234 catalog_version: 1,
235 format: Format::Zip,
236 source_object: SourceObject::Unix {
237 device: 1,
238 inode: 1,
239 },
240 archive_bytes: 2_700_000,
241 archive_sha256: [7; 32],
242 });
243 app.model.confirmed = true;
244 match self.name {
245 "tar-bz2" | "tar-xz" => {
246 app.model.list_id.as_mut().unwrap().format = Format::Tar;
247 for entry in &mut app.model.entries {
248 entry.encrypted = false;
249 }
250 app.destination = present::default_destination(&archive);
251 app.automatic_destination = true;
252 return app;
253 }
254 "archive" | "many-items" => return app,
255 "folder-empty" => {
256 app.browse_folder("빈 폴더");
257 return app;
258 }
259 "dialog-error" => {
260 app.ui_error = Some(DIALOG_UNAVAILABLE.into());
261 return app;
262 }
263 "folder" => {
264 app.browse_folder("사진");
265 return app;
266 }
267 "search-empty" => {
268 app.search = "없는 파일".into();
269 return app;
270 }
271 "selection" | "marquee" => {
272 app.model
273 .selected
274 .extend([0, 3, 4, if self.name == "marquee" { 2 } else { 1 }]);
275 if self.name == "marquee" {
276 app.scenario_marquee = Some(egui::Rect::from_min_size(
277 egui::pos2(22.0, 8.0),
278 egui::vec2(360.0, 62.0),
279 ));
280 }
281 return app;
282 }
283 "create" | "create-encrypted" => {
284 app.sources = vec![base.join("읽어주세요.txt"), base.join("사진")];
285 app.scenario_sources = Some(std::rc::Rc::new(vec![
286 SourceRow {
287 name: "사진".into(),
288 directory: true,
289 bytes: Some(0),
290 },
291 SourceRow {
292 name: "읽어주세요.txt".into(),
293 directory: false,
294 bytes: Some(4096),
295 },
296 ]));
297 app.show_create(self.name == "create-encrypted");
298 return app;
299 }
300 _ => {}
301 }
302 let creating = self.name.starts_with("create-") || self.name == "password-create";
303 let listing_error = matches!(self.name, "unsupported" | "damaged");
304 if self.name == "gzip-conflict" {
305 app.model.list_id.as_mut().unwrap().format = Format::Gzip;
306 app.model.entries = vec![Entry {
307 id: 0,
308 name: "여행 자료".into(),
309 kind: Kind::File,
310 bytes: Some(1_287_952),
311 packed: Some(900_000),
312 encrypted: false,
313 }];
314 app.gzip_name = "여행 자료".into();
315 }
316 let request = if creating {
317 Start::CreateZip {
318 sources: vec![(base.join("사진"), "사진".into())],
319 output_file: base.join("여행 자료.zip"),
320 method: Method::Deflate,
321 aes256: self.name == "password-create",
322 }
323 } else if listing_error {
324 Start::List { archive }
325 } else {
326 Start::Extract {
327 archive,
328 destination: app.destination.clone(),
329 selection: Selection::All,
330 list_id: app.model.list_id.clone().unwrap(),
331 gzip_output_name: (self.name == "gzip-conflict").then(|| app.gzip_name.clone()),
332 }
333 };
334 app.targets = Some(if creating {
335 BTreeSet::from(["여행 자료.zip".into()])
336 } else if self.name == "gzip-conflict" {
337 BTreeSet::from(["여행 자료".into()])
338 } else {
339 BTreeSet::from([
340 "읽어주세요.txt".into(),
341 "여행 일정.pdf".into(),
342 "사진/바다.jpg".into(),
343 "사진/풍경.jpg".into(),
344 ])
345 });
346 assert!(app.start(request));
347 {
348 let mut state = state.borrow_mut();
349 state.frame(Event::Accepted { encryption: true });
350 match self.name {
351 "password" | "password-retry" | "password-create" => {
352 state.frame(Event::PasswordRequired {
353 challenge_id: 17,
354 attempt: if self.name == "password-retry" { 2 } else { 1 },
355 encrypt: self.name == "password-create",
356 })
357 }
358 "extract-complete" | "create-complete" | "extract-unsynced" => {
359 let names = app.targets.as_ref().unwrap();
360 for name in names {
361 state.frame(Event::Output {
362 entry_id: None,
363 relative_name: name.clone(),
364 disposition: Disposition::Created,
365 });
366 }
367 state.frame(Event::Terminal(Terminal {
368 outcome: Outcome::Completed,
369 error: None,
370 publication: Publication::Complete,
371 created_count: names.len() as u64,
372 retained_partial_count: 0,
373 durability: if self.name == "extract-unsynced" {
374 Durability::Unconfirmed
375 } else {
376 Durability::Synced
377 },
378 cleanup: Cleanup::Complete,
379 }));
380 state.queue.extend([
381 HostEvent::StdoutEof,
382 HostEvent::StderrEof,
383 HostEvent::Exited { success: true },
384 ]);
385 }
386 "extract-cancelled" => state.finish(Outcome::Cancelled, Publication::None),
387 "extract-partial" | "extract-uncertain" => {
388 let partial = self.name == "extract-partial";
389 if partial {
390 state.frame(Event::Output {
391 entry_id: Some(1),
392 relative_name: "읽어주세요.txt".into(),
393 disposition: Disposition::Created,
394 });
395 }
396 state.frame(Event::Terminal(Terminal {
397 outcome: Outcome::Failed,
398 error: Some(ErrorCode::Io),
399 publication: if partial {
400 Publication::Partial
401 } else {
402 Publication::Uncertain
403 },
404 created_count: u64::from(partial),
405 retained_partial_count: 0,
406 durability: Durability::Synced,
407 cleanup: Cleanup::Complete,
408 }));
409 state.queue.extend([
410 HostEvent::StdoutEof,
411 HostEvent::StderrEof,
412 HostEvent::Exited { success: true },
413 ]);
414 }
415 "conflict" | "gzip-conflict" | "unsupported" | "damaged" | "source-changed"
416 | "create-error" => {
417 state.frame(Event::Terminal(Terminal {
418 outcome: Outcome::Failed,
419 error: Some(match self.name {
420 "conflict" | "gzip-conflict" => ErrorCode::Conflict,
421 "source-changed" => ErrorCode::SourceChanged,
422 "create-error" => ErrorCode::DiskFull,
423 "unsupported" => ErrorCode::UnsupportedFormat,
424 _ => ErrorCode::Integrity,
425 }),
426 publication: Publication::None,
427 created_count: 0,
428 retained_partial_count: 0,
429 durability: Durability::NotApplicable,
430 cleanup: Cleanup::Complete,
431 }));
432 state.queue.extend([
433 HostEvent::StdoutEof,
434 HostEvent::StderrEof,
435 HostEvent::Exited { success: true },
436 ]);
437 }
438 _ => state.frame(Event::Progress {
439 stage: if creating {
440 Stage::Write
441 } else {
442 Stage::Decode
443 },
444 processed: 38 << 20,
445 total: (self.name != "extract-unknown").then_some(61 << 20),
446 completed_entries: 12,
447 }),
448 }
449 }
450 for _ in 0..64 {
451 app.model.poll();
452 }
453 if self.name == "extract-unsynced" {
454 app.details = true;
455 }
456 if self.name == "cancelling" {
457 app.model.cancel();
458 }
459 if self.name == "close-confirm" {
460 app.model.request_close();
461 }
462 app
463 }
464}
465
466/// 화면을 고정하고 실제 파일 조작을 막는 미리보기임.
467pub struct Preview(pub ArchiveApp, Option<Scenario>);
468impl Preview {
469 pub fn with_scenario(mut self, scenario: Scenario) -> Self {
470 self.1 = Some(scenario);
471 self
472 }
473
474 pub fn show(&mut self, ui: &mut egui::Ui) {
475 if let Some(scenario) = self.1 {
476 scenario.show(&mut self.0, ui);
477 } else {
478 self.0.show(ui);
479 }
480 }
481
482 pub fn new(app: ArchiveApp, ctx: &egui::Context) -> Self {
483 ctx.on_begin_pass(
484 "ui-scenario-readonly",
485 std::sync::Arc::new(|ctx| {
486 ctx.input_mut(|i| {
487 i.events.clear();
488 i.pointer = Default::default();
489 i.keys_down.clear();
490 i.modifiers = Default::default();
491 i.raw.dropped_files.clear();
492 i.raw.hovered_files.clear();
493 });
494 }),
495 );
496 Self(app, None)
497 }
498}
499impl eframe::App for Preview {
500 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
501 if root.ctx().input(|i| i.viewport().close_requested()) {
502 root.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
503 return;
504 }
505 self.show(root);
506 }
507}