team-ljyzipelo

공개

Merge pull request #95 from Team-LJY/fix/linux-dialog-progress-window

Linux 파일 선택 멈춤, 큰 파일 진행률, 작업 진행 창과 Wayland 제목 표시줄 수정
작성자
LeeJunyoung
작성 시각
커밋
185b606521c27dad622e3076aeaef66dee89e252
이 시점의 파일 보기

변경된 파일 10개

+1,281-26
수정experiments/rust-archive-worker/src/runtime.rs+10-2
@@ -198,8 +198,16 @@ impl<W: Write> Job<W> {
198198 let extract = matches!(start.action, Action::Extract { .. });
199199 let path = source.to_path()?;
200200 self.progress(Stage::Read, 0, None, 0)?;
201삭제: let mut snapshot =
202삭제: crate::spool::Snapshot::open(&path, start.limits.input, &mut || self.check())?;
201추가: let mut snapshot = crate::spool::Snapshot::open_reporting(
202추가: &path,
203추가: start.limits.input,
204추가: &mut |step| match step {
205추가: crate::spool::Step::Check => self.check(),
206추가: crate::spool::Step::Read { bytes, total } => {
207추가: self.progress(Stage::Read, bytes, Some(total), 0)
208추가: }
209추가: },
210추가: )?;
203211 if let Action::Extract {
204212 list_id: Some(expected),
205213 ..
수정experiments/rust-archive-worker/src/spool.rs+32-3
@@ -70,6 +70,12 @@ pub(crate) fn temporary() -> Result<File> {
7070 }
7171}
7272
73추가: #[derive(Clone, Copy, Debug)]
74추가: pub(crate) enum Step {
75추가: Check,
76추가: Read { bytes: u64, total: u64 },
77추가: }
78추가:
7379pub(crate) struct Snapshot {
7480 pub file: File,
7581 pub len: u64,
@@ -77,7 +83,12 @@ pub(crate) struct Snapshot {
7783 pub hash: [u8; 32],
7884}
7985impl Snapshot {
80삭제: pub fn open(path: &Path, limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Self> {
86추가: /// 원본을 임시 파일로 복사하는 동안 읽은 바이트와 전체 크기를 함께 알림.
87추가: pub fn open_reporting(
88추가: path: &Path,
89추가: limit: u64,
90추가: step: &mut impl FnMut(Step) -> Result<()>,
91추가: ) -> Result<Self> {
8192 let mut options = OpenOptions::new();
8293 options.read(true);
8394 #[cfg(unix)]
@@ -91,7 +102,7 @@ impl Snapshot {
91102 options.share_mode(1);
92103 }
93104 let mut source = options.open(path).map_err(|_| ErrorCode::Io)?;
94삭제: let snapshot = Self::capture(&mut source, limit, check)?;
105추가: let snapshot = Self::capture_reporting(&mut source, limit, step)?;
95106 let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?;
96107 if filesystem::object(&named)? != snapshot.object
97108 || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file()
@@ -104,6 +115,16 @@ impl Snapshot {
104115 source: &mut File,
105116 limit: u64,
106117 check: &mut impl FnMut() -> Result<()>,
118추가: ) -> Result<Self> {
119추가: Self::capture_reporting(source, limit, &mut |step| match step {
120추가: Step::Check => check(),
121추가: Step::Read { .. } => Ok(()),
122추가: })
123추가: }
124추가: fn capture_reporting(
125추가: source: &mut File,
126추가: limit: u64,
127추가: step: &mut impl FnMut(Step) -> Result<()>,
107128 ) -> Result<Self> {
108129 let before = source.metadata().map_err(|_| ErrorCode::Io)?;
109130 if !before.is_file() {
@@ -119,8 +140,10 @@ impl Snapshot {
119140 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
120141 let mut hash = Sha256::new();
121142 let mut len = 0u64;
143추가: let total = before.len();
144추가: let mut reported = std::time::Instant::now();
122145 loop {
123삭제: check()?;
146추가: step(Step::Check)?;
124147 let n = source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io)?;
125148 if n == 0 {
126149 break;
@@ -132,7 +155,13 @@ impl Snapshot {
132155 file.write_all(&buffer[..n])
133156 .map_err(crate::space::io_error)?;
134157 hash.update(&buffer[..n]);
158추가: // 큰 파일에서도 진행이 보이도록 일정 간격으로만 알림.
159추가: if reported.elapsed() >= std::time::Duration::from_millis(200) {
160추가: step(Step::Read { bytes: len, total })?;
161추가: reported = std::time::Instant::now();
162추가: }
135163 }
164추가: step(Step::Read { bytes: len, total })?;
136165 let after = source.metadata().map_err(|_| ErrorCode::Io)?;
137166 if filesystem::object(&source)? != object
138167 || before.len() != len
수정experiments/rust-ui-memory-app/src/archive_dialog.rs+27-1
@@ -19,8 +19,20 @@ pub struct DialogRequest {
1919 pub file_name: String,
2020}
2121
22추가: pub type DialogAnswer = Result<Option<Vec<PathBuf>>, String>;
23추가:
24추가: pub enum PendingDialog {
25추가: Ready(DialogAnswer),
26추가: Waiting(std::sync::mpsc::Receiver<DialogAnswer>),
27추가: }
28추가:
2229pub trait Dialogs {
23삭제: fn choose(&mut self, request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String>;
30추가: fn choose(&mut self, request: DialogRequest) -> DialogAnswer;
31추가:
32추가: /// 선택 창을 연다. 기본 구현은 응답을 바로 돌려준다.
33추가: fn start(&mut self, request: DialogRequest) -> PendingDialog {
34추가: PendingDialog::Ready(self.choose(request))
35추가: }
2436}
2537
2638pub fn archive_filters() -> Vec<(&'static str, Vec<String>)> {
@@ -62,6 +74,20 @@ impl Dialogs for NativeDialogs {
6274 }))
6375 .unwrap_or_else(|_| Err(DIALOG_UNAVAILABLE.into()))
6476 }
77추가:
78추가: // 포털 응답을 화면 스레드에서 기다리면 창이 이벤트를 처리하지 못해 "응답 없음"으로 표시됨.
79추가: #[cfg(target_os = "linux")]
80추가: fn start(&mut self, request: DialogRequest) -> PendingDialog {
81추가: let (sender, receiver) = std::sync::mpsc::channel();
82추가: match std::thread::Builder::new()
83추가: .name("zipelo-file-dialog".into())
84추가: .spawn(move || {
85추가: let _ = sender.send(NativeDialogs.choose(request));
86추가: }) {
87추가: Ok(_) => PendingDialog::Waiting(receiver),
88추가: Err(_) => PendingDialog::Ready(Err(DIALOG_UNAVAILABLE.into())),
89추가: }
90추가: }
6591}
6692
6793#[cfg(target_os = "linux")]
수정experiments/rust-ui-memory-app/src/archive_screen.rs+305-14
@@ -1,9 +1,13 @@
11use crate::{
22 archive_browser as browser,
3삭제: archive_dialog::{DialogRequest, Dialogs, NativeDialogs, Purpose},
3추가: archive_dialog::{
4추가: DIALOG_UNAVAILABLE, DialogAnswer, DialogRequest, Dialogs, NativeDialogs, PendingDialog,
5추가: Purpose,
6추가: },
47 archive_present as present,
58 archive_theme::{self as theme, Icon},
69 archive_ui::*,
10추가: window_frame,
711};
812use eframe::egui::{self, Align, Layout, RichText};
913use std::{
@@ -11,6 +15,37 @@ use std::{
1115 path::{Path, PathBuf},
1216};
1317
18추가: const WORK_WIDTH: f32 = 480.0;
19추가: const WORK_MIN_HEIGHT: f32 = 96.0;
20추가: const WORK_MAX_HEIGHT: f32 = 520.0;
21추가: const WORK_RESULT_MAX_HEIGHT: f32 = 220.0;
22추가:
23추가: /// 작업 진행·결과를 보여주는 자식 창의 위치 상태.
24추가: /// 부모 창 기준 상대 위치를 기억해 두고, 부모 창이 움직이면 같은 상대 위치로 따라감.
25추가: struct WorkWindow {
26추가: open: bool,
27추가: initial: Option<egui::Pos2>,
28추가: offset: Option<egui::Vec2>,
29추가: parent: Option<egui::Pos2>,
30추가: expected: Option<egui::Pos2>,
31추가: settle_until: f64,
32추가: height: f32,
33추가: }
34추가:
35추가: impl Default for WorkWindow {
36추가: fn default() -> Self {
37추가: Self {
38추가: open: false,
39추가: initial: None,
40추가: offset: None,
41추가: parent: None,
42추가: expected: None,
43추가: settle_until: 0.0,
44추가: height: 168.0,
45추가: }
46추가: }
47추가: }
48추가:
1449struct Marquee {
1550 // 스크롤 중에도 시작점을 목록 좌표로 유지함.
1651 origin: egui::Pos2,
@@ -39,6 +74,10 @@ pub struct ArchiveApp {
3974 selected_only: bool,
4075 method: Method,
4176 dialogs: Box<dyn Dialogs>,
77추가: picker: Option<(Purpose, std::sync::mpsc::Receiver<DialogAnswer>)>,
78추가: work: WorkWindow,
79추가: custom_frame: bool,
80추가: release_after_move: bool,
4281 folder: String,
4382 search: String,
4483 list_anchor: Option<usize>,
@@ -77,6 +116,10 @@ impl ArchiveApp {
77116 selected_only: false,
78117 method: Method::Deflate,
79118 dialogs: Box::new(NativeDialogs),
119추가: picker: None,
120추가: work: WorkWindow::default(),
121추가: custom_frame: false,
122추가: release_after_move: false,
80123 folder: String::new(),
81124 search: String::new(),
82125 list_anchor: None,
@@ -103,6 +146,11 @@ impl ArchiveApp {
103146 self.dialogs = dialogs;
104147 }
105148
149추가: /// 운영체제가 창 테두리를 그려 주지 않을 때(GNOME Wayland) 제목 표시줄을 직접 그림.
150추가: pub fn set_custom_frame(&mut self, custom: bool) {
151추가: self.custom_frame = custom;
152추가: }
153추가:
106154 pub fn browse_folder(&mut self, folder: &str) {
107155 self.folder = folder.trim_matches('/').to_owned();
108156 self.search.clear();
@@ -143,6 +191,10 @@ impl ArchiveApp {
143191 }
144192
145193 fn start(&mut self, request: Start) -> bool {
194추가: // 파일 선택 창이 응답을 기다리는 동안에는 어느 창에서도 새 작업을 시작하지 않음.
195추가: if self.picker.is_some() {
196추가: return false;
197추가: }
146198 self.last_request = Some(request.clone());
147199 self.dismissed = false;
148200 self.details = false;
@@ -306,7 +358,7 @@ impl ArchiveApp {
306358 }
307359
308360 fn open_picker(&mut self, purpose: Purpose) {
309삭제: if self.model.busy() {
361추가: if self.model.busy() || self.picker.is_some() {
310362 return;
311363 }
312364 let gzip = self
@@ -345,10 +397,28 @@ impl ArchiveApp {
345397 self.zip_name.clone()
346398 },
347399 };
348삭제: let answer = self.dialogs.choose(request);
349삭제: if answer.is_ok()
350삭제: && self.ui_error.as_deref() == Some(crate::archive_dialog::DIALOG_UNAVAILABLE)
351삭제: {
400추가: match self.dialogs.start(request) {
401추가: PendingDialog::Ready(answer) => self.apply_picker(purpose, answer),
402추가: PendingDialog::Waiting(receiver) => self.picker = Some((purpose, receiver)),
403추가: }
404추가: }
405추가:
406추가: fn poll_picker(&mut self) {
407추가: let Some((purpose, receiver)) = &self.picker else {
408추가: return;
409추가: };
410추가: let purpose = *purpose;
411추가: let answer = match receiver.try_recv() {
412추가: Ok(answer) => answer,
413추가: Err(std::sync::mpsc::TryRecvError::Empty) => return,
414추가: Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(DIALOG_UNAVAILABLE.into()),
415추가: };
416추가: self.picker = None;
417추가: self.apply_picker(purpose, answer);
418추가: }
419추가:
420추가: fn apply_picker(&mut self, purpose: Purpose, answer: DialogAnswer) {
421추가: if answer.is_ok() && self.ui_error.as_deref() == Some(DIALOG_UNAVAILABLE) {
352422 self.ui_error = None;
353423 }
354424 match answer {
@@ -479,19 +549,23 @@ impl ArchiveApp {
479549 self.initialized = true;
480550 }
481551 self.poll();
552추가: self.poll_picker();
482553 let challenge = self.model.challenge.map(|(id, _, _)| id);
483554 let new_challenge = challenge != self.password_challenge;
484555 if new_challenge || challenge.is_none() {
485556 self.clear_password();
486557 }
487558 self.password_challenge = challenge;
488삭제: self.on_drop(ctx.input(|i| {
559추가: let dropped = ctx.input(|i| {
489560 i.raw
490561 .dropped_files
491562 .iter()
492563 .map(|file| file.path().to_path_buf())
493564 .collect()
494삭제: }));
565추가: });
566추가: if self.picker.is_none() {
567추가: self.on_drop(dropped);
568추가: }
495569 if ctx.input(|i| i.viewport().close_requested()) {
496570 self.model.request_close();
497571 if self.model.close != Close::Allowed {
@@ -523,6 +597,19 @@ impl ArchiveApp {
523597 title.clone()
524598 };
525599 ctx.send_viewport_cmd(egui::ViewportCommand::Title(short_title));
600추가: if self.custom_frame
601추가: && window_frame::title_bar(
602추가: root,
603추가: "main",
604추가: &title,
605추가: window_frame::Buttons {
606추가: minimize: true,
607추가: maximize: true,
608추가: },
609추가: )
610추가: {
611추가: self.release_after_move = true;
612추가: }
526613 egui::Panel::top("archive-actions")
527614 .frame(
528615 theme::panel(theme::PANEL)
@@ -531,7 +618,9 @@ impl ArchiveApp {
531618 )
532619 .show(root, |ui| {
533620 ui.horizontal(|ui| {
534삭제: let idle = !self.model.busy() && self.model.close == Close::Open;
621추가: let idle = !self.model.busy()
622추가: && self.model.close == Close::Open
623추가: && self.picker.is_none();
535624 if theme::tool(ui, "열기", theme::OPEN, idle, false)
536625 .on_hover_text(&title)
537626 .clicked()
@@ -587,7 +676,8 @@ impl ArchiveApp {
587676 });
588677 });
589678 });
590삭제: if self.model.busy() || self.result_visible() || (self.ui_error.is_some() && !self.create) {
679추가: if ctx.embed_viewports() && self.work_visible() {
680추가: // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
591681 egui::Panel::bottom("archive-work")
592682 .frame(theme::panel(theme::PANEL).corner_radius(0))
593683 .show(root, |ui| self.work_area(ui));
@@ -605,6 +695,7 @@ impl ArchiveApp {
605695 self.empty(ui);
606696 }
607697 });
698추가: self.work_window(&ctx);
608699 if self.create && !self.model.busy() {
609700 self.create_dialog(&ctx);
610701 }
@@ -612,11 +703,27 @@ impl ArchiveApp {
612703 self.password_dialog(&ctx, new_challenge);
613704 }
614705 self.close_dialog(&ctx);
706추가: self.picker_notice(&ctx);
707추가: if self.custom_frame {
708추가: window_frame::edges(&ctx, true);
709추가: }
615710 if self.model.busy() {
616711 ctx.request_repaint_after(std::time::Duration::from_millis(30));
617712 }
618713 }
619714
715추가: // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
716추가: fn picker_notice(&mut self, ctx: &egui::Context) {
717추가: if self.picker.is_none() {
718추가: return;
719추가: }
720추가: egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
721추가: ui.set_width(360.0);
722추가: ui.label("파일 선택 창에서 선택을 마쳐 주세요");
723추가: });
724추가: ctx.request_repaint_after(std::time::Duration::from_millis(100));
725추가: }
726추가:
620727 fn empty(&mut self, ui: &mut egui::Ui) {
621728 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
622729 let width = (ui.available_width() * 0.60)
@@ -1122,7 +1229,169 @@ impl ArchiveApp {
11221229 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
11231230 }
11241231
1232추가: fn work_visible(&self) -> bool {
1233추가: self.model.busy() || self.result_visible() || (self.ui_error.is_some() && !self.create)
1234추가: }
1235추가:
1236추가: /// 메인 창 가운데에 모달(ZIP 만들기, 암호 입력, 종료 확인, 파일 선택 안내)이 떠 있는지.
1237추가: /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
1238추가: fn main_modal_open(&self) -> bool {
1239추가: (self.create && !self.model.busy())
1240추가: || self.picker.is_some()
1241추가: || self.model.challenge.is_some()
1242추가: || self.model.close != Close::Open
1243추가: }
1244추가:
1245추가: fn work_window(&mut self, ctx: &egui::Context) {
1246추가: if !self.work_visible() {
1247추가: self.work = WorkWindow::default();
1248추가: return;
1249추가: }
1250추가: if ctx.embed_viewports() {
1251추가: // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1252추가: return;
1253추가: }
1254추가: if self.main_modal_open() {
1255추가: // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
1256추가: // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
1257추가: self.work.open = false;
1258추가: return;
1259추가: }
1260추가: let id = egui::ViewportId::from_hash_of("archive-work");
1261추가: let (parent, parent_focused, now) = ctx.input(|i| {
1262추가: (
1263추가: i.viewport().outer_rect,
1264추가: i.viewport().focused.unwrap_or(false),
1265추가: i.time,
1266추가: )
1267추가: });
1268추가: let (child, child_focused) = ctx.input(|i| {
1269추가: i.raw.viewports.get(&id).map_or((None, false), |v| {
1270추가: (v.outer_rect, v.focused.unwrap_or(false))
1271추가: })
1272추가: });
1273추가: let size = egui::vec2(WORK_WIDTH, self.work.height);
1274추가: if !self.work.open {
1275추가: // 처음 열 때 부모 창 가운데에 둠. 암호 입력 뒤 다시 열 때는 기억한 위치에 둠.
1276추가: // Wayland처럼 위치를 알 수 없으면 창 관리자에 맡김.
1277추가: self.work.open = true;
1278추가: self.work.initial = parent.map(|p| match self.work.offset {
1279추가: Some(offset) => (p.min + offset).round(),
1280추가: None => (p.center() - size / 2.0).round(),
1281추가: });
1282추가: self.work.offset = self.work.initial.zip(parent).map(|(c, p)| c - p.min);
1283추가: self.work.parent = parent.map(|p| p.min);
1284추가: self.work.expected = self.work.initial;
1285추가: self.work.settle_until = now + 0.5;
1286추가: }
1287추가: if let (Some(parent), Some(child)) = (parent, child) {
1288추가: let parent_moved = self
1289추가: .work
1290추가: .parent
1291추가: .is_some_and(|p| (p - parent.min).length() > 0.5);
1292추가: let settled = self
1293추가: .work
1294추가: .expected
1295추가: .is_some_and(|e| (child.min - e).length() <= 2.0);
1296추가: if settled || now >= self.work.settle_until {
1297추가: self.work.settle_until = 0.0;
1298추가: }
1299추가: if parent_moved {
1300추가: if let Some(offset) = self.work.offset {
1301추가: let target = (parent.min + offset).round();
1302추가: ctx.send_viewport_cmd_to(id, egui::ViewportCommand::OuterPosition(target));
1303추가: self.work.expected = Some(target);
1304추가: self.work.settle_until = now + 0.5;
1305추가: }
1306추가: } else if self.work.settle_until == 0.0 && !settled {
1307추가: // 사용자가 자식 창을 옮긴 위치를 부모 기준으로 기억함.
1308추가: self.work.offset = Some(child.min - parent.min);
1309추가: self.work.expected = Some(child.min);
1310추가: }
1311추가: self.work.parent = Some(parent.min);
1312추가: }
1313추가: let title = if self.model.busy() {
1314추가: present::activity_text(
1315추가: &self.model,
1316추가: matches!(self.last_request, Some(Start::CreateZip { .. })),
1317추가: )
1318추가: .to_owned()
1319추가: } else {
1320추가: "작업 결과".to_owned()
1321추가: };
1322추가: let window_title = format!("{title} — Zipelo");
1323추가: let custom_frame = self.custom_frame;
1324추가: let mut builder = egui::ViewportBuilder::default()
1325추가: .with_title(window_title.clone())
1326추가: .with_decorations(!custom_frame)
1327추가: .with_inner_size(size)
1328추가: .with_resizable(false)
1329추가: .with_minimize_button(false)
1330추가: .with_maximize_button(false)
1331추가: .with_taskbar(false)
1332추가: // 앱을 쓰는 동안에만 부모 창 위에 유지함.
1333추가: .with_window_level(if parent_focused || child_focused {
1334추가: egui::WindowLevel::AlwaysOnTop
1335추가: } else {
1336추가: egui::WindowLevel::Normal
1337추가: });
1338추가: if let Some(position) = self.work.initial {
1339추가: builder = builder.with_position(position);
1340추가: }
1341추가: let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1342추가: if ui.ctx().input(|i| i.viewport().close_requested()) {
1343추가: if self.model.busy() {
1344추가: ui.ctx()
1345추가: .send_viewport_cmd(egui::ViewportCommand::CancelClose);
1346추가: } else {
1347추가: self.dismissed = true;
1348추가: self.ui_error = None;
1349추가: self.model.input_error = None;
1350추가: }
1351추가: }
1352추가: if class == egui::ViewportClass::EmbeddedWindow {
1353추가: ui.set_width(WORK_WIDTH);
1354추가: self.work_area(ui);
1355추가: return None;
1356추가: }
1357추가: let mut chrome = 0.0;
1358추가: if custom_frame {
1359추가: window_frame::title_bar(
1360추가: ui,
1361추가: "work",
1362추가: &window_title,
1363추가: window_frame::Buttons {
1364추가: minimize: false,
1365추가: maximize: false,
1366추가: },
1367추가: );
1368추가: window_frame::edges(ui.ctx(), false);
1369추가: chrome = window_frame::TITLE_HEIGHT;
1370추가: }
1371추가: let margin = theme::PAD as f32;
1372추가: egui::CentralPanel::default()
1373추가: .frame(theme::panel(theme::PANEL).corner_radius(0))
1374추가: .show(ui, |ui| {
1375추가: let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
1376추가: Some(content.height() + 2.0 * margin + chrome)
1377추가: })
1378추가: .inner
1379추가: });
1380추가: if let Some(height) = height {
1381추가: let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
1382추가: if (height - self.work.height).abs() > 1.0 {
1383추가: self.work.height = height;
1384추가: }
1385추가: }
1386추가: }
1387추가:
11251388 fn work_area(&mut self, ui: &mut egui::Ui) {
1389추가: // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
1390추가: let enabled = self.picker.is_none();
1391추가: ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
1392추가: }
1393추가:
1394추가: fn work_contents(&mut self, ui: &mut egui::Ui) {
11261395 if self.model.busy() {
11271396 self.progress(ui);
11281397 } else if self.result_visible() {
@@ -1159,7 +1428,13 @@ impl ArchiveApp {
11591428 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
11601429 let title = present::activity_text(&self.model, creating);
11611430 ui.strong(title);
1162삭제: if let Some((_, done, total, count)) = self.model.progress {
1431추가: if let Some((stage, done, total, count)) = self.model.progress {
1432추가: // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
1433추가: let processed = if stage == Stage::Read {
1434추가: String::new()
1435추가: } else {
1436추가: format!("{count}개 처리함, ")
1437추가: };
11631438 if let Some(total) = total.filter(|n| *n > 0) {
11641439 ui.scope(|ui| {
11651440 ui.visuals_mut().extreme_bg_color = theme::BORDER;
@@ -1171,7 +1446,7 @@ impl ArchiveApp {
11711446 });
11721447 ui.horizontal(|ui| {
11731448 ui.label(format!(
1174삭제: "{:.0}% / {count}개 처리함, {} / {}",
1449추가: "{:.0}% / {processed}{} / {}",
11751450 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
11761451 present::bytes_text(done),
11771452 present::bytes_text(total)
@@ -1181,7 +1456,7 @@ impl ArchiveApp {
11811456 } else {
11821457 theme::indeterminate(ui);
11831458 ui.horizontal(|ui| {
1184삭제: ui.label(format!("{count}개 처리함, {}", present::bytes_text(done)));
1459추가: ui.label(format!("{processed}{}", present::bytes_text(done)));
11851460 self.cancel_action(ui, cancelling);
11861461 });
11871462 }
@@ -1272,7 +1547,7 @@ impl ArchiveApp {
12721547 );
12731548 ui.strong(title);
12741549 });
1275삭제: let max_height = (ui.ctx().content_rect().height() * 0.24).max(80.0);
1550추가: let max_height = WORK_RESULT_MAX_HEIGHT;
12761551 egui::ScrollArea::vertical()
12771552 .id_salt("result-message")
12781553 .max_height(max_height)
@@ -1760,6 +2035,22 @@ impl eframe::App for ArchiveApp {
17602035 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
17612036 self.show(root);
17622037 }
2038추가:
2039추가: fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
2040추가: // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
2041추가: if std::mem::take(&mut self.release_after_move) {
2042추가: let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
2043추가: raw_input.events.insert(
2044추가: 0,
2045추가: egui::Event::PointerButton {
2046추가: pos,
2047추가: button: egui::PointerButton::Primary,
2048추가: pressed: false,
2049추가: modifiers: ctx.input(|i| i.modifiers),
2050추가: },
2051추가: );
2052추가: }
2053추가: }
17632054}
17642055impl Drop for ArchiveApp {
17652056 fn drop(&mut self) {
수정experiments/rust-ui-memory-app/src/desktop.rs+8-6
@@ -42,13 +42,15 @@ fn show_startup_error(message: &str) {
4242}
4343
4444fn run() -> eframe::Result {
45추가: let custom_frame = zipelo_ui_memory_app::window_frame::custom_frame_needed();
4546 let font = system_font::load().map_err(|e| eframe::Error::AppCreation(Box::new(e)))?;
4647 renderer::run_native(
4748 "Zipelo",
4849 eframe::NativeOptions {
4950 viewport: egui::ViewportBuilder::default()
5051 .with_inner_size([1060.0, 720.0])
51삭제: .with_min_inner_size([760.0, 540.0]),
52추가: .with_min_inner_size([760.0, 540.0])
53추가: .with_decorations(!custom_frame),
5254 ..Default::default()
5355 },
5456 || {
@@ -86,11 +88,11 @@ fn run() -> eframe::Result {
8688 .map_err(std::io::Error::other)?,
8789 )
8890 };
89삭제: Ok(Box::new(
90삭제: zipelo_ui_memory_app::archive_screen::ArchiveApp::new(
91삭제: factory, startup, fixture,
92삭제: ),
93삭제: ))
91추가: let mut app = zipelo_ui_memory_app::archive_screen::ArchiveApp::new(
92추가: factory, startup, fixture,
93추가: );
94추가: app.set_custom_frame(custom_frame);
95추가: Ok(Box::new(app))
9496 })
9597 },
9698 )
수정experiments/rust-ui-memory-app/src/lib.rs+2-0
@@ -19,5 +19,7 @@ pub mod archive_browser;
1919pub mod archive_dialog;
2020#[cfg(feature = "ui")]
2121pub mod archive_theme;
22추가: #[cfg(feature = "ui")]
23추가: pub mod window_frame;
2224
2325pub mod archive_path;
추가experiments/rust-ui-memory-app/src/window_frame.rs+282-0
@@ -0,0 +1,282 @@
1추가: //! GNOME Wayland는 창 테두리를 그려 주지 않으므로 제목 표시줄과 테두리를 직접 그림.
2추가: //! 앱 글꼴로 그려서 한글 제목도 그대로 표시됨.
3추가:
4추가: use crate::archive_theme as theme;
5추가: use eframe::egui::{
6추가: self, Align2, Color32, CursorIcon, FontId, Rect, ResizeDirection, Sense, Stroke, Vec2,
7추가: ViewportCommand,
8추가: };
9추가:
10추가: pub const TITLE_HEIGHT: f32 = 38.0;
11추가: const BUTTON_SIZE: Vec2 = egui::vec2(34.0, 26.0);
12추가: const RESIZE_EDGE: f32 = 6.0;
13추가: const DRAG_THRESHOLD: f32 = 4.0;
14추가: const TITLE_BG: Color32 = Color32::from_rgb(235, 238, 242);
15추가:
16추가: /// 창 테두리를 직접 그려야 하는지 판단함.
17추가: /// winit은 Linux에서 Wayland 연결 정보가 있으면 Wayland로 창을 만듦.
18추가: pub fn custom_frame_needed() -> bool {
19추가: cfg!(target_os = "linux")
20추가: && ["WAYLAND_DISPLAY", "WAYLAND_SOCKET"]
21추가: .iter()
22추가: .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()))
23추가: }
24추가:
25추가: #[derive(Clone, Copy)]
26추가: pub struct Buttons {
27추가: pub minimize: bool,
28추가: pub maximize: bool,
29추가: }
30추가:
31추가: #[derive(Clone, Copy, PartialEq)]
32추가: enum Glyph {
33추가: Minimize,
34추가: Maximize,
35추가: Restore,
36추가: Close,
37추가: }
38추가:
39추가: /// 위쪽 패널로 제목 표시줄을 그림. 버튼과 끌기 동작은 현재 창에 명령으로 보냄.
40추가: /// 창 이동을 운영체제에 넘긴 프레임이면 true를 돌려줌.
41추가: pub fn title_bar(root: &mut egui::Ui, id: &str, title: &str, buttons: Buttons) -> bool {
42추가: let mut moved = false;
43추가: egui::Panel::top(egui::Id::unique(("window-title", id)))
44추가: .exact_size(TITLE_HEIGHT)
45추가: .resizable(false)
46추가: .show_separator_line(false)
47추가: .frame(egui::Frame::new().fill(TITLE_BG))
48추가: .show(root, |ui| {
49추가: let rect = ui.max_rect();
50추가: let ctx = ui.ctx().clone();
51추가: let bar = ui.interact(
52추가: rect,
53추가: egui::Id::unique(("window-title-drag", id)),
54추가: Sense::click_and_drag(),
55추가: );
56추가: let maximized = ctx.input(|i| i.viewport().maximized.unwrap_or(false));
57추가: if buttons.maximize && bar.double_clicked() {
58추가: ctx.send_viewport_cmd(ViewportCommand::Maximized(!maximized));
59추가: }
60추가:
61추가: let mut glyphs = vec![Glyph::Close];
62추가: if buttons.maximize {
63추가: glyphs.push(if maximized {
64추가: Glyph::Restore
65추가: } else {
66추가: Glyph::Maximize
67추가: });
68추가: }
69추가: if buttons.minimize {
70추가: glyphs.push(Glyph::Minimize);
71추가: }
72추가: let button_count = glyphs.len() as f32;
73추가: let buttons_left = rect.right() - 6.0 - button_count * (BUTTON_SIZE.x + 4.0);
74추가: if start_move(&ctx, id, rect, buttons_left) {
75추가: ctx.send_viewport_cmd(ViewportCommand::StartDrag);
76추가: moved = true;
77추가: }
78추가: let mut right = rect.right() - 6.0;
79추가: for glyph in glyphs {
80추가: let button = Rect::from_center_size(
81추가: egui::pos2(right - BUTTON_SIZE.x / 2.0, rect.center().y),
82추가: BUTTON_SIZE,
83추가: );
84추가: right -= BUTTON_SIZE.x + 4.0;
85추가: if window_button(ui, id, button, glyph).clicked() {
86추가: ctx.send_viewport_cmd(match glyph {
87추가: Glyph::Minimize => ViewportCommand::Minimized(true),
88추가: Glyph::Maximize => ViewportCommand::Maximized(true),
89추가: Glyph::Restore => ViewportCommand::Maximized(false),
90추가: Glyph::Close => ViewportCommand::Close,
91추가: });
92추가: }
93추가: }
94추가:
95추가: // 버튼 영역을 피해 가운데에 제목을 그림.
96추가: let reserved = rect.right() - right;
97추가: let width = (rect.width() - 2.0 * reserved).max(0.0);
98추가: let font = FontId::proportional(theme::BODY - 2.0);
99추가: let text = fit(ui, title, &font, width);
100추가: ui.painter().text(
101추가: rect.center(),
102추가: Align2::CENTER_CENTER,
103추가: text,
104추가: font,
105추가: theme::TEXT,
106추가: );
107추가: ui.painter().hline(
108추가: rect.x_range(),
109추가: rect.bottom() - 0.5,
110추가: Stroke::new(1.0, theme::BORDER),
111추가: );
112추가: });
113추가: moved
114추가: }
115추가:
116추가: /// 제목 표시줄을 누른 채 움직였는지를 원시 입력으로 판단함.
117추가: /// 창 이동 중에는 운영체제가 마우스를 가져가서 버튼 놓기가 앱에 오지 않으므로,
118추가: /// egui의 끌기 상태에 기대면 다음 끌기가 시작되지 않음.
119추가: fn start_move(ctx: &egui::Context, id: &str, bar: Rect, buttons_left: f32) -> bool {
120추가: let key = egui::Id::unique(("window-title-press", id));
121추가: let mut origin: Option<egui::Pos2> = ctx.data(|d| d.get_temp(key)).flatten();
122추가: let latest = ctx.input(|i| {
123추가: for event in &i.raw.events {
124추가: if let egui::Event::PointerButton {
125추가: pos,
126추가: button: egui::PointerButton::Primary,
127추가: pressed,
128추가: ..
129추가: } = event
130추가: {
131추가: origin = (*pressed && bar.contains(*pos) && pos.x < buttons_left).then_some(*pos);
132추가: }
133추가: }
134추가: i.pointer.latest_pos()
135추가: });
136추가: let start = origin
137추가: .zip(latest)
138추가: .is_some_and(|(origin, latest)| (latest - origin).length() >= DRAG_THRESHOLD);
139추가: if start {
140추가: origin = None;
141추가: // 운영체제가 이동을 맡으므로 egui 쪽 끌기는 끝낸 것으로 처리함.
142추가: ctx.stop_dragging();
143추가: }
144추가: ctx.data_mut(|d| d.insert_temp(key, origin));
145추가: start
146추가: }
147추가:
148추가: fn window_button(ui: &mut egui::Ui, id: &str, rect: Rect, glyph: Glyph) -> egui::Response {
149추가: let label = match glyph {
150추가: Glyph::Minimize => "최소화",
151추가: Glyph::Maximize => "최대화",
152추가: Glyph::Restore => "이전 크기로",
153추가: Glyph::Close => "닫기",
154추가: };
155추가: let response = ui
156추가: .interact(
157추가: rect,
158추가: egui::Id::unique(("window-button", id, label)),
159추가: Sense::click(),
160추가: )
161추가: .on_hover_text(label);
162추가: response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
163추가: let painter = ui.painter();
164추가: if response.hovered() || response.is_pointer_button_down_on() {
165추가: let fill = if glyph == Glyph::Close {
166추가: Color32::from_rgb(232, 17, 35)
167추가: } else {
168추가: theme::BORDER
169추가: };
170추가: painter.rect_filled(rect, 6.0, fill);
171추가: }
172추가: let color = if glyph == Glyph::Close && response.hovered() {
173추가: Color32::WHITE
174추가: } else {
175추가: theme::TEXT
176추가: };
177추가: let stroke = Stroke::new(1.4, color);
178추가: let c = rect.center();
179추가: let r = 5.0;
180추가: match glyph {
181추가: Glyph::Minimize => {
182추가: painter.hline(c.x - r..=c.x + r, c.y + r * 0.6, stroke);
183추가: }
184추가: Glyph::Maximize => {
185추가: painter.rect_stroke(
186추가: Rect::from_center_size(c, egui::vec2(2.0 * r, 2.0 * r)),
187추가: 1.0,
188추가: stroke,
189추가: egui::StrokeKind::Middle,
190추가: );
191추가: }
192추가: Glyph::Restore => {
193추가: let back = Rect::from_center_size(c + egui::vec2(1.5, -1.5), egui::vec2(8.0, 8.0));
194추가: let front = Rect::from_center_size(c + egui::vec2(-1.5, 1.5), egui::vec2(8.0, 8.0));
195추가: painter.rect_stroke(back, 1.0, stroke, egui::StrokeKind::Middle);
196추가: painter.rect_filled(front, 1.0, TITLE_BG);
197추가: painter.rect_stroke(front, 1.0, stroke, egui::StrokeKind::Middle);
198추가: }
199추가: Glyph::Close => {
200추가: painter.line_segment([c + egui::vec2(-r, -r), c + egui::vec2(r, r)], stroke);
201추가: painter.line_segment([c + egui::vec2(-r, r), c + egui::vec2(r, -r)], stroke);
202추가: }
203추가: }
204추가: response
205추가: }
206추가:
207추가: /// 폭을 넘는 제목은 앞부분을 줄이고 끝(파일 이름과 앱 이름)을 남김.
208추가: fn fit(ui: &egui::Ui, title: &str, font: &FontId, width: f32) -> String {
209추가: let measure = |text: &str| {
210추가: ui.fonts_mut(|fonts| {
211추가: fonts
212추가: .layout_no_wrap(text.to_owned(), font.clone(), theme::TEXT)
213추가: .size()
214추가: .x
215추가: })
216추가: };
217추가: if measure(title) <= width {
218추가: return title.to_owned();
219추가: }
220추가: let chars: Vec<char> = title.chars().collect();
221추가: for start in 1..chars.len() {
222추가: let candidate = format!("…{}", chars[start..].iter().collect::<String>());
223추가: if measure(&candidate) <= width {
224추가: return candidate;
225추가: }
226추가: }
227추가: String::new()
228추가: }
229추가:
230추가: /// 창 가장자리에서 크기 조절을 시작하고 얇은 테두리를 그림.
231추가: pub fn edges(ctx: &egui::Context, resizable: bool) {
232추가: let rect = ctx.content_rect();
233추가: let maximized = ctx.input(|i| {
234추가: i.viewport().maximized.unwrap_or(false) || i.viewport().fullscreen.unwrap_or(false)
235추가: });
236추가: if !maximized {
237추가: ctx.layer_painter(egui::LayerId::new(
238추가: egui::Order::Foreground,
239추가: egui::Id::unique("window-border"),
240추가: ))
241추가: .rect_stroke(
242추가: rect.shrink(0.5),
243추가: 0.0,
244추가: Stroke::new(1.0, theme::BORDER),
245추가: egui::StrokeKind::Middle,
246추가: );
247추가: }
248추가: if !resizable || maximized {
249추가: return;
250추가: }
251추가: let Some(pointer) = ctx.input(|i| i.pointer.hover_pos()) else {
252추가: return;
253추가: };
254추가: let left = pointer.x - rect.left() <= RESIZE_EDGE;
255추가: let right = rect.right() - pointer.x <= RESIZE_EDGE;
256추가: let top = pointer.y - rect.top() <= RESIZE_EDGE;
257추가: let bottom = rect.bottom() - pointer.y <= RESIZE_EDGE;
258추가: let direction = match (left, right, top, bottom) {
259추가: (true, _, true, _) => ResizeDirection::NorthWest,
260추가: (_, true, true, _) => ResizeDirection::NorthEast,
261추가: (true, _, _, true) => ResizeDirection::SouthWest,
262추가: (_, true, _, true) => ResizeDirection::SouthEast,
263추가: (true, ..) => ResizeDirection::West,
264추가: (_, true, ..) => ResizeDirection::East,
265추가: (_, _, true, _) => ResizeDirection::North,
266추가: (_, _, _, true) => ResizeDirection::South,
267추가: _ => return,
268추가: };
269추가: ctx.set_cursor_icon(match direction {
270추가: ResizeDirection::North => CursorIcon::ResizeNorth,
271추가: ResizeDirection::South => CursorIcon::ResizeSouth,
272추가: ResizeDirection::East => CursorIcon::ResizeEast,
273추가: ResizeDirection::West => CursorIcon::ResizeWest,
274추가: ResizeDirection::NorthEast => CursorIcon::ResizeNorthEast,
275추가: ResizeDirection::NorthWest => CursorIcon::ResizeNorthWest,
276추가: ResizeDirection::SouthEast => CursorIcon::ResizeSouthEast,
277추가: ResizeDirection::SouthWest => CursorIcon::ResizeSouthWest,
278추가: });
279추가: if ctx.input(|i| i.pointer.primary_pressed()) {
280추가: ctx.send_viewport_cmd(ViewportCommand::BeginResize(direction));
281추가: }
282추가: }
수정tests/rust-app-ui/presentation.rs+2-0
@@ -909,6 +909,8 @@ mod widgets {
909909 include!("toolbar.rs");
910910 include!("long_layout.rs");
911911 include!("explorer_selection.rs");
912추가: include!("window_frame.rs");
913추가: include!("work_window.rs");
912914}
913915
914916#[cfg(feature = "ui")]
추가tests/rust-app-ui/window_frame.rs+201-0
@@ -0,0 +1,201 @@
1추가: // GNOME Wayland처럼 운영체제가 창 테두리를 그리지 않을 때 쓰는 자체 제목 표시줄 회귀 시험.
2추가:
3추가: fn frame_output(
4추가: ctx: &egui::Context,
5추가: app: &mut ArchiveApp,
6추가: events: Vec<egui::Event>,
7추가: ) -> egui::FullOutput {
8추가: let mut output = ctx.run_ui(
9추가: egui::RawInput {
10추가: screen_rect: Some(egui::Rect::from_min_size(
11추가: egui::Pos2::ZERO,
12추가: egui::vec2(1060.0, 720.0),
13추가: )),
14추가: events,
15추가: ..Default::default()
16추가: },
17추가: |ui| app.show(ui),
18추가: );
19추가: output.textures_delta.clear();
20추가: output
21추가: }
22추가:
23추가: fn root_commands(output: &egui::FullOutput) -> Vec<egui::ViewportCommand> {
24추가: output
25추가: .viewport_output
26추가: .get(&egui::ViewportId::ROOT)
27추가: .map(|viewport| viewport.commands.clone())
28추가: .unwrap_or_default()
29추가: }
30추가:
31추가: fn press_release(
32추가: ctx: &egui::Context,
33추가: app: &mut ArchiveApp,
34추가: point: egui::Pos2,
35추가: ) -> Vec<egui::ViewportCommand> {
36추가: frame_output(ctx, app, vec![egui::Event::PointerMoved(point)]);
37추가: let mut commands = Vec::new();
38추가: for pressed in [true, false] {
39추가: let output = frame_output(
40추가: ctx,
41추가: app,
42추가: vec![egui::Event::PointerButton {
43추가: pos: point,
44추가: button: egui::PointerButton::Primary,
45추가: pressed,
46추가: modifiers: egui::Modifiers::NONE,
47추가: }],
48추가: );
49추가: commands.extend(root_commands(&output));
50추가: }
51추가: commands
52추가: }
53추가:
54추가: fn window_commands(commands: &[egui::ViewportCommand]) -> Vec<egui::ViewportCommand> {
55추가: // 제목 갱신은 매 프레임 나가므로 창 조작 명령만 비교함.
56추가: commands
57추가: .iter()
58추가: .filter(|command| !matches!(command, egui::ViewportCommand::Title(_)))
59추가: .cloned()
60추가: .collect()
61추가: }
62추가:
63추가: #[test]
64추가: fn custom_window_frame_shows_title_and_sends_window_commands() {
65추가: use zipelo_ui_memory_app::window_frame::TITLE_HEIGHT;
66추가: // 제목 표시줄 버튼 중심: 오른쪽 여백 6, 버튼 폭 34, 간격 4.
67추가: let close = egui::pos2(1060.0 - 6.0 - 17.0, TITLE_HEIGHT / 2.0);
68추가: let maximize = close - egui::vec2(38.0, 0.0);
69추가: let minimize = maximize - egui::vec2(38.0, 0.0);
70추가: for (point, expected) in [
71추가: (close, egui::ViewportCommand::Close),
72추가: (maximize, egui::ViewportCommand::Maximized(true)),
73추가: (minimize, egui::ViewportCommand::Minimized(true)),
74추가: ] {
75추가: let scratch = Folder::new();
76추가: let factory = FakeFactory::default();
77추가: let mut app = loaded(&scratch, &factory);
78추가: app.set_custom_frame(true);
79추가: let ctx = egui::Context::default();
80추가: let shown = labels(&frame_output(&ctx, &mut app, vec![]).shapes);
81추가: assert!(
82추가: shown
83추가: .iter()
84추가: .any(|(text, pos)| text.ends_with("sample.zip — Zipelo") && pos.y < TITLE_HEIGHT),
85추가: "제목 표시줄에 창 제목이 없음: {shown:?}"
86추가: );
87추가: assert_eq!(
88추가: window_commands(&press_release(&ctx, &mut app, point)),
89추가: [expected]
90추가: );
91추가: }
92추가:
93추가: // 제목 표시줄을 끌면 운영체제 창 이동을 시작함.
94추가: let scratch = Folder::new();
95추가: let factory = FakeFactory::default();
96추가: let mut app = loaded(&scratch, &factory);
97추가: app.set_custom_frame(true);
98추가: let ctx = egui::Context::default();
99추가: let start = egui::pos2(300.0, TITLE_HEIGHT / 2.0);
100추가: frame_output(&ctx, &mut app, vec![egui::Event::PointerMoved(start)]);
101추가: let mut commands = root_commands(&frame_output(
102추가: &ctx,
103추가: &mut app,
104추가: vec![egui::Event::PointerButton {
105추가: pos: start,
106추가: button: egui::PointerButton::Primary,
107추가: pressed: true,
108추가: modifiers: egui::Modifiers::NONE,
109추가: }],
110추가: ));
111추가: for step in 1..=4 {
112추가: commands.extend(root_commands(&frame_output(
113추가: &ctx,
114추가: &mut app,
115추가: vec![egui::Event::PointerMoved(
116추가: start + egui::vec2(6.0 * step as f32, 0.0),
117추가: )],
118추가: )));
119추가: }
120추가: assert_eq!(
121추가: window_commands(&commands),
122추가: [egui::ViewportCommand::StartDrag]
123추가: );
124추가: }
125추가:
126추가: #[test]
127추가: fn default_window_frame_draws_no_title_bar_or_window_commands() {
128추가: let scratch = Folder::new();
129추가: let factory = FakeFactory::default();
130추가: let mut app = loaded(&scratch, &factory);
131추가: let ctx = egui::Context::default();
132추가: let shown = labels(&frame_output(&ctx, &mut app, vec![]).shapes);
133추가: assert!(
134추가: !shown
135추가: .iter()
136추가: .any(|(text, _)| text.ends_with(" — Zipelo")),
137추가: "운영체제가 테두리를 그릴 때는 제목 표시줄을 그리지 않아야 함"
138추가: );
139추가: let close = egui::pos2(1060.0 - 6.0 - 17.0, 19.0);
140추가: assert!(window_commands(&press_release(&ctx, &mut app, close)).is_empty());
141추가: }
142추가:
143추가: fn drag_without_release(
144추가: ctx: &egui::Context,
145추가: app: &mut ArchiveApp,
146추가: start: egui::Pos2,
147추가: ) -> Vec<egui::ViewportCommand> {
148추가: frame_output(ctx, app, vec![egui::Event::PointerMoved(start)]);
149추가: let mut commands = root_commands(&frame_output(
150추가: ctx,
151추가: app,
152추가: vec![egui::Event::PointerButton {
153추가: pos: start,
154추가: button: egui::PointerButton::Primary,
155추가: pressed: true,
156추가: modifiers: egui::Modifiers::NONE,
157추가: }],
158추가: ));
159추가: for step in 1..=4 {
160추가: commands.extend(root_commands(&frame_output(
161추가: ctx,
162추가: app,
163추가: vec![egui::Event::PointerMoved(
164추가: start + egui::vec2(6.0 * step as f32, 0.0),
165추가: )],
166추가: )));
167추가: }
168추가: window_commands(&commands)
169추가: }
170추가:
171추가: #[test]
172추가: fn title_bar_drag_starts_again_when_the_system_swallowed_the_release() {
173추가: use zipelo_ui_memory_app::window_frame::TITLE_HEIGHT;
174추가: let scratch = Folder::new();
175추가: let factory = FakeFactory::default();
176추가: let mut app = loaded(&scratch, &factory);
177추가: app.set_custom_frame(true);
178추가: let ctx = egui::Context::default();
179추가: // GNOME Wayland는 창 이동이 끝나도 버튼 놓기를 앱에 보내지 않음.
180추가: let first = drag_without_release(&ctx, &mut app, egui::pos2(300.0, TITLE_HEIGHT / 2.0));
181추가: assert_eq!(first, [egui::ViewportCommand::StartDrag]);
182추가: let second = drag_without_release(&ctx, &mut app, egui::pos2(500.0, TITLE_HEIGHT / 2.0));
183추가: assert_eq!(second, [egui::ViewportCommand::StartDrag]);
184추가:
185추가: // 이동을 넘긴 뒤 다음 프레임 입력에 버튼 놓기를 넣어 눌림 상태를 풀어야 함.
186추가: let mut raw = egui::RawInput::default();
187추가: eframe::App::raw_input_hook(&mut app, &ctx, &mut raw);
188추가: assert!(raw.events.iter().any(|event| matches!(
189추가: event,
190추가: egui::Event::PointerButton {
191추가: button: egui::PointerButton::Primary,
192추가: pressed: false,
193추가: ..
194추가: }
195추가: )));
196추가: frame_output(&ctx, &mut app, raw.events);
197추가: assert!(!ctx.input(|i| i.pointer.any_down()));
198추가: let mut again = egui::RawInput::default();
199추가: eframe::App::raw_input_hook(&mut app, &ctx, &mut again);
200추가: assert!(again.events.is_empty(), "놓기는 이동 한 번에 한 번만 넣어야 함");
201추가: }
추가tests/rust-app-ui/work_window.rs+412-0
@@ -0,0 +1,412 @@
1추가: // 별도 진행 창(실제 즉시 viewport 콜백)에서 파일 선택 대기 중에 작업이 시작되지 않는지 확인함.
2추가:
3추가: #[derive(Default)]
4추가: struct WorkChild {
5추가: events: Vec<egui::Event>,
6추가: labels: Vec<(String, egui::Pos2)>,
7추가: rendered: usize,
8추가: }
9추가:
10추가: std::thread_local! {
11추가: static WORK_CHILD: std::cell::RefCell<WorkChild> = Default::default();
12추가: }
13추가:
14추가: /// eframe처럼 별도 viewport 콜백을 같은 Context에서 실행하고, 그 viewport에만 입력을 넣음.
15추가: fn install_work_child_renderer() {
16추가: // 같은 스레드에서 이어 도는 시험끼리 기록이 섞이지 않게 비움.
17추가: WORK_CHILD.with(|child| *child.borrow_mut() = WorkChild::default());
18추가: egui::Context::set_immediate_viewport_renderer(|ctx, mut viewport| {
19추가: let events = WORK_CHILD.with(|child| std::mem::take(&mut child.borrow_mut().events));
20추가: let mut raw = egui::RawInput {
21추가: viewport_id: viewport.ids.this,
22추가: screen_rect: Some(egui::Rect::from_min_size(
23추가: egui::Pos2::ZERO,
24추가: egui::vec2(480.0, 240.0),
25추가: )),
26추가: events,
27추가: ..Default::default()
28추가: };
29추가: raw.viewports.insert(
30추가: viewport.ids.this,
31추가: egui::ViewportInfo {
32추가: parent: Some(viewport.ids.parent),
33추가: focused: Some(true),
34추가: ..Default::default()
35추가: },
36추가: );
37추가: let mut output = ctx.run_ui(raw, |ui| (viewport.viewport_ui_cb)(ui));
38추가: output.textures_delta.clear();
39추가: WORK_CHILD.with(|child| {
40추가: let mut child = child.borrow_mut();
41추가: child.labels = labels(&output.shapes);
42추가: // 진행·결과 창이 그려진 횟수만 셈(다른 별도 창은 세지 않음).
43추가: if viewport.ids.this == egui::ViewportId::from_hash_of("archive-work") {
44추가: child.rendered += 1;
45추가: }
46추가: });
47추가: });
48추가: }
49추가:
50추가: fn work_child_label(label: &str) -> Option<egui::Pos2> {
51추가: WORK_CHILD.with(|child| {
52추가: child
53추가: .borrow()
54추가: .labels
55추가: .iter()
56추가: .rev()
57추가: .find(|(text, _)| text == label)
58추가: .map(|(_, pos)| *pos)
59추가: })
60추가: }
61추가:
62추가: fn work_child_click(ctx: &egui::Context, app: &mut ArchiveApp, point: egui::Pos2) {
63추가: for pressed in [true, false] {
64추가: WORK_CHILD.with(|child| {
65추가: child.borrow_mut().events = vec![
66추가: egui::Event::PointerMoved(point),
67추가: egui::Event::PointerButton {
68추가: pos: point,
69추가: button: egui::PointerButton::Primary,
70추가: pressed,
71추가: modifiers: egui::Modifiers::NONE,
72추가: },
73추가: ];
74추가: });
75추가: policy_render(ctx, app, vec![]);
76추가: }
77추가: }
78추가:
79추가: /// 열기 선택 창의 응답을 시험이 보낼 때까지 보류함.
80추가: #[derive(Clone, Default)]
81추가: struct HeldDialogs(
82추가: std::rc::Rc<
83추가: std::cell::RefCell<
84추가: Vec<std::sync::mpsc::Sender<zipelo_ui_memory_app::archive_dialog::DialogAnswer>>,
85추가: >,
86추가: >,
87추가: );
88추가:
89추가: impl zipelo_ui_memory_app::archive_dialog::Dialogs for HeldDialogs {
90추가: fn choose(
91추가: &mut self,
92추가: _: zipelo_ui_memory_app::archive_dialog::DialogRequest,
93추가: ) -> zipelo_ui_memory_app::archive_dialog::DialogAnswer {
94추가: Ok(None)
95추가: }
96추가:
97추가: fn start(
98추가: &mut self,
99추가: _: zipelo_ui_memory_app::archive_dialog::DialogRequest,
100추가: ) -> zipelo_ui_memory_app::archive_dialog::PendingDialog {
101추가: let (sender, receiver) = std::sync::mpsc::channel();
102추가: self.0.borrow_mut().push(sender);
103추가: zipelo_ui_memory_app::archive_dialog::PendingDialog::Waiting(receiver)
104추가: }
105추가: }
106추가:
107추가: #[test]
108추가: fn picker_wait_blocks_retry_in_separate_work_window() {
109추가: let scratch = Folder::new();
110추가: let factory = FakeFactory::default();
111추가: let mut app = loaded(&scratch, &factory);
112추가: factory.state.borrow_mut().manual = true;
113추가: assert!(app.begin_extract());
114추가: {
115추가: let mut worker = factory.state.borrow_mut();
116추가: worker.frame(Event::Accepted { encryption: false });
117추가: worker.finish(Outcome::Failed, Publication::None);
118추가: for event in &mut worker.queue {
119추가: if let HostEvent::Frame {
120추가: event: Event::Terminal(t),
121추가: ..
122추가: } = event
123추가: {
124추가: t.error = Some(ErrorCode::Io);
125추가: }
126추가: }
127추가: }
128추가: let ctx = egui::Context::default();
129추가: ctx.set_embed_viewports(false);
130추가: install_work_child_renderer();
131추가: for _ in 0..10 {
132추가: policy_render(&ctx, &mut app, vec![]);
133추가: }
134추가: assert!(
135추가: WORK_CHILD.with(|child| child.borrow().rendered) > 0,
136추가: "결과가 별도 viewport에 그려져야 함"
137추가: );
138추가: let retry = work_child_label("다시 시도").expect("별도 결과 창에 다시 시도 버튼이 있어야 함");
139추가:
140추가: let dialogs = HeldDialogs::default();
141추가: app.set_dialogs(Box::new(dialogs.clone()));
142추가: policy_click(&ctx, &mut app, "열기");
143추가: assert_eq!(
144추가: dialogs.0.borrow().len(),
145추가: 1,
146추가: "열기 선택 창이 응답을 기다려야 함"
147추가: );
148추가: let before = factory.state.borrow().starts.len();
149추가: work_child_click(&ctx, &mut app, retry);
150추가: assert_eq!(
151추가: factory.state.borrow().starts.len(),
152추가: before,
153추가: "파일 선택 창이 열린 동안 별도 결과 창에서 작업이 시작됨"
154추가: );
155추가:
156추가: // 대조: 선택 창을 닫으면 같은 클릭으로 다시 시도가 시작됨.
157추가: dialogs.0.borrow()[0].send(Ok(None)).unwrap();
158추가: for _ in 0..3 {
159추가: policy_render(&ctx, &mut app, vec![]);
160추가: }
161추가: let retry = work_child_label("다시 시도").expect("선택 창을 닫은 뒤에도 결과가 남아야 함");
162추가: work_child_click(&ctx, &mut app, retry);
163추가: assert_eq!(factory.state.borrow().starts.len(), before + 1);
164추가: }
165추가:
166추가: #[test]
167추가: fn password_prompt_is_not_covered_by_separate_work_window() {
168추가: let scratch = Folder::new();
169추가: let factory = FakeFactory::manual();
170추가: let mut app = ArchiveApp::new(Box::new(factory.clone()), None, false);
171추가: assert!(app.model.begin(
172추가: Start::CreateZip {
173추가: sources: vec![(scratch.0.join("source"), "source".into())],
174추가: output_file: scratch.0.join("output.zip"),
175추가: method: Method::Deflate,
176추가: aes256: true
177추가: },
178추가: &mut factory.clone()
179추가: ));
180추가: {
181추가: let mut worker = factory.state.borrow_mut();
182추가: worker.frame(Event::Accepted { encryption: true });
183추가: worker.frame(Event::PasswordRequired {
184추가: challenge_id: 17,
185추가: attempt: 1,
186추가: encrypt: true,
187추가: });
188추가: }
189추가: let ctx = egui::Context::default();
190추가: ctx.set_embed_viewports(false);
191추가: install_work_child_renderer();
192추가: for _ in 0..12 {
193추가: policy_render(&ctx, &mut app, vec![]);
194추가: }
195추가: assert!(app.model.challenge.is_some(), "암호 입력을 기다려야 함");
196추가: // 작업자 사건을 처리하기 전 몇 프레임은 진행 창이 정상으로 그려짐.
197추가: // 암호 입력 창이 뜬 뒤부터 진행 창이 그려지는지만 셈.
198추가: WORK_CHILD.with(|child| child.borrow_mut().rendered = 0);
199추가: for _ in 0..5 {
200추가: policy_render(&ctx, &mut app, vec![]);
201추가: }
202추가: assert!(
203추가: ctx.read_response(egui::Id::unique("archive-password-input"))
204추가: .is_some(),
205추가: "메인 창에 암호 입력란이 있어야 함"
206추가: );
207추가: // 항상 위에 뜨는 진행 창이 메인 창 가운데의 암호 입력란을 가리지 않도록
208추가: // 암호를 기다리는 동안에는 진행 창을 그리지 않음.
209추가: assert_eq!(
210추가: WORK_CHILD.with(|child| child.borrow().rendered),
211추가: 0,
212추가: "암호 입력 중에 별도 진행 창이 떠 있음"
213추가: );
214추가:
215추가: // 암호 입력이 끝나 작업이 이어지면 진행 창이 다시 나타남.
216추가: app.model.challenge = None;
217추가: for _ in 0..3 {
218추가: policy_render(&ctx, &mut app, vec![]);
219추가: }
220추가: assert!(app.model.busy());
221추가: assert!(
222추가: WORK_CHILD.with(|child| child.borrow().rendered) > 0,
223추가: "암호 입력 뒤 진행 창이 다시 나타나야 함"
224추가: );
225추가: }
226추가:
227추가: #[test]
228추가: fn close_confirmation_is_not_covered_by_separate_work_window() {
229추가: let scratch = Folder::new();
230추가: let factory = FakeFactory::default();
231추가: let mut app = loaded(&scratch, &factory);
232추가: factory.state.borrow_mut().manual = true;
233추가: assert!(app.begin_extract());
234추가: factory
235추가: .state
236추가: .borrow_mut()
237추가: .frame(Event::Accepted { encryption: false });
238추가: let ctx = egui::Context::default();
239추가: ctx.set_embed_viewports(false);
240추가: install_work_child_renderer();
241추가: for _ in 0..6 {
242추가: policy_render(&ctx, &mut app, vec![]);
243추가: }
244추가: assert!(app.model.busy());
245추가: assert!(
246추가: WORK_CHILD.with(|child| child.borrow().rendered) > 0,
247추가: "작업 중에는 진행 창이 떠 있어야 함"
248추가: );
249추가:
250추가: // 작업 중 메인 창을 닫으면 메인 창 가운데에 종료 확인 창이 뜸.
251추가: app.model.request_close();
252추가: assert_eq!(app.model.close, Close::Confirm);
253추가: policy_render(&ctx, &mut app, vec![]);
254추가: WORK_CHILD.with(|child| child.borrow_mut().rendered = 0);
255추가: let mut shown = Vec::new();
256추가: for _ in 0..5 {
257추가: shown = policy_render(&ctx, &mut app, vec![]);
258추가: }
259추가: for label in ["작업 중 닫기", "계속 작업", "취소하고 닫기"] {
260추가: assert!(shown.iter().any(|(text, _)| text == label), "{label}");
261추가: }
262추가: // 항상 위에 뜨는 진행 창이 확인 창을 가리지 않도록 그동안 진행 창을 그리지 않음.
263추가: assert_eq!(
264추가: WORK_CHILD.with(|child| child.borrow().rendered),
265추가: 0,
266추가: "종료 확인 중에 별도 진행 창이 떠 있음"
267추가: );
268추가:
269추가: // 계속 작업을 고르면 진행 창이 다시 나타남.
270추가: app.model.keep_open();
271추가: for _ in 0..3 {
272추가: policy_render(&ctx, &mut app, vec![]);
273추가: }
274추가: assert!(app.model.busy());
275추가: assert!(
276추가: WORK_CHILD.with(|child| child.borrow().rendered) > 0,
277추가: "계속 작업을 고르면 진행 창이 다시 나타나야 함"
278추가: );
279추가:
280추가: // 취소하고 닫기 뒤 정리를 기다리는 동안("종료 확인 중")도 가리지 않음.
281추가: app.model.request_close();
282추가: app.model.confirm_close();
283추가: assert_eq!(app.model.close, Close::Waiting);
284추가: policy_render(&ctx, &mut app, vec![]);
285추가: WORK_CHILD.with(|child| child.borrow_mut().rendered = 0);
286추가: for _ in 0..5 {
287추가: shown = policy_render(&ctx, &mut app, vec![]);
288추가: }
289추가: assert!(shown.iter().any(|(text, _)| text == "종료 확인 중"));
290추가: assert_eq!(
291추가: WORK_CHILD.with(|child| child.borrow().rendered),
292추가: 0,
293추가: "종료 확인 중에 별도 진행 창이 떠 있음"
294추가: );
295추가:
296추가: // 정리가 끝나 결과 확인 후 닫기가 뜰 때도 결과 창이 가리지 않음.
297추가: factory
298추가: .state
299추가: .borrow_mut()
300추가: .finish(Outcome::Cancelled, Publication::None);
301추가: for _ in 0..12 {
302추가: shown = policy_render(&ctx, &mut app, vec![]);
303추가: }
304추가: assert_eq!(app.model.close, Close::Review);
305추가: assert!(shown.iter().any(|(text, _)| text == "결과 확인 후 닫기"));
306추가: assert_eq!(
307추가: WORK_CHILD.with(|child| child.borrow().rendered),
308추가: 0,
309추가: "결과 확인 후 닫기에 별도 결과 창이 떠 있음"
310추가: );
311추가: }
312추가:
313추가: /// 추출이 실패해 별도 결과 창이 남아 있는 상태를 만듦.
314추가: fn failed_result(scratch: &Folder, factory: &FakeFactory) -> ArchiveApp {
315추가: let mut app = loaded(scratch, factory);
316추가: factory.state.borrow_mut().manual = true;
317추가: assert!(app.begin_extract());
318추가: let mut worker = factory.state.borrow_mut();
319추가: worker.frame(Event::Accepted { encryption: false });
320추가: worker.finish(Outcome::Failed, Publication::None);
321추가: for event in &mut worker.queue {
322추가: if let HostEvent::Frame {
323추가: event: Event::Terminal(t),
324추가: ..
325추가: } = event
326추가: {
327추가: t.error = Some(ErrorCode::Io);
328추가: }
329추가: }
330추가: drop(worker);
331추가: app
332추가: }
333추가:
334추가: fn work_rendered() -> usize {
335추가: WORK_CHILD.with(|child| child.borrow().rendered)
336추가: }
337추가:
338추가: #[test]
339추가: fn main_modals_are_not_covered_by_separate_result_window() {
340추가: // 암호 입력과 종료 확인은 작업 중에만 뜨므로 위 시험들이 진행 창과의 조합을 봄.
341추가: // 작업이 끝난 뒤 결과 창과 함께 뜰 수 있는 모달(ZIP 만들기, 파일 선택 안내)을 여기서 봄.
342추가: let scratch = Folder::new();
343추가: let factory = FakeFactory::default();
344추가: let mut app = failed_result(&scratch, &factory);
345추가: let ctx = egui::Context::default();
346추가: ctx.set_embed_viewports(false);
347추가: install_work_child_renderer();
348추가: for _ in 0..10 {
349추가: policy_render(&ctx, &mut app, vec![]);
350추가: }
351추가: assert!(!app.model.busy());
352추가: assert!(work_rendered() > 0, "결과가 별도 viewport에 그려져야 함");
353추가:
354추가: // 결과 창을 둔 채 ZIP 만들기를 열면 그동안 결과 창을 그리지 않음.
355추가: app.show_create(false);
356추가: policy_render(&ctx, &mut app, vec![]);
357추가: WORK_CHILD.with(|child| child.borrow_mut().rendered = 0);
358추가: let mut shown = Vec::new();
359추가: for _ in 0..5 {
360추가: shown = policy_render(&ctx, &mut app, vec![]);
361추가: }
362추가: assert!(shown.iter().any(|(text, _)| text == "ZIP 만들기"));
363추가: assert_eq!(
364추가: work_rendered(),
365추가: 0,
366추가: "ZIP 만들기 창 위에 별도 결과 창이 떠 있음"
367추가: );
368추가:
369추가: // ZIP 만들기를 닫으면 결과 창이 다시 나타남.
370추가: policy_click(&ctx, &mut app, "취소");
371추가: for _ in 0..3 {
372추가: policy_render(&ctx, &mut app, vec![]);
373추가: }
374추가: assert!(
375추가: work_rendered() > 0,
376추가: "ZIP 만들기를 닫으면 결과 창이 다시 나타나야 함"
377추가: );
378추가:
379추가: // 파일 선택 창을 기다리는 안내가 뜬 동안에도 결과 창을 그리지 않음.
380추가: let dialogs = HeldDialogs::default();
381추가: app.set_dialogs(Box::new(dialogs.clone()));
382추가: policy_click(&ctx, &mut app, "열기");
383추가: assert_eq!(
384추가: dialogs.0.borrow().len(),
385추가: 1,
386추가: "열기 선택 창이 응답을 기다려야 함"
387추가: );
388추가: policy_render(&ctx, &mut app, vec![]);
389추가: WORK_CHILD.with(|child| child.borrow_mut().rendered = 0);
390추가: for _ in 0..5 {
391추가: shown = policy_render(&ctx, &mut app, vec![]);
392추가: }
393추가: assert!(
394추가: shown
395추가: .iter()
396추가: .any(|(text, _)| text == "파일 선택 창에서 선택을 마쳐 주세요")
397추가: );
398추가: assert_eq!(
399추가: work_rendered(),
400추가: 0,
401추가: "파일 선택 안내 위에 별도 결과 창이 떠 있음"
402추가: );
403추가:
404추가: dialogs.0.borrow()[0].send(Ok(None)).unwrap();
405추가: for _ in 0..3 {
406추가: policy_render(&ctx, &mut app, vec![]);
407추가: }
408추가: assert!(
409추가: work_rendered() > 0,
410추가: "선택 창을 닫으면 결과 창이 다시 나타나야 함"
411추가: );
412추가: }