team-ljyzipelo

공개

Linux 파일 선택 멈춤을 고치고 작업 진행을 별도 창으로 옮김

- Linux 포털 파일 선택 창을 화면 스레드에서 기다려 GNOME이 "응답 없음"을
  표시하던 문제를 고침. 선택 창은 별도 스레드에서 열고 결과를 프레임마다 받음.
- 파일 목록 아래 작업 패널을 없애고 진행과 결과를 작은 별도 창으로 옮김.
  부모 창 가운데에 열고, 옮긴 상대 위치를 유지한 채 부모 창을 따라감.
  Wayland에서는 창 위치를 정할 수 없어 창 관리자가 위치를 정함.
- 원본을 읽는 단계에서는 처리한 항목 수를 표시하지 않음.
- GNOME Wayland는 창 테두리를 그려 주지 않아 한글 제목이 깨지므로 앱 글꼴로
  제목 표시줄을 직접 그림. 창 이동 뒤 버튼 놓기가 오지 않아 다음 끌기가
  시작되지 않던 문제를 원시 입력 판단과 놓기 보충으로 고침.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
작성자
LeeJunyoung
작성 시각
커밋
f3f54eb126b900ce12b6b8f25e051b53c0fc072a
부모
e4faa4c
이 시점의 파일 보기

변경된 파일 7개

+797-21
수정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+276-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();
@@ -306,7 +354,7 @@ impl ArchiveApp {
306354 }
307355
308356 fn open_picker(&mut self, purpose: Purpose) {
309삭제: if self.model.busy() {
357추가: if self.model.busy() || self.picker.is_some() {
310358 return;
311359 }
312360 let gzip = self
@@ -345,10 +393,28 @@ impl ArchiveApp {
345393 self.zip_name.clone()
346394 },
347395 };
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삭제: {
396추가: match self.dialogs.start(request) {
397추가: PendingDialog::Ready(answer) => self.apply_picker(purpose, answer),
398추가: PendingDialog::Waiting(receiver) => self.picker = Some((purpose, receiver)),
399추가: }
400추가: }
401추가:
402추가: fn poll_picker(&mut self) {
403추가: let Some((purpose, receiver)) = &self.picker else {
404추가: return;
405추가: };
406추가: let purpose = *purpose;
407추가: let answer = match receiver.try_recv() {
408추가: Ok(answer) => answer,
409추가: Err(std::sync::mpsc::TryRecvError::Empty) => return,
410추가: Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(DIALOG_UNAVAILABLE.into()),
411추가: };
412추가: self.picker = None;
413추가: self.apply_picker(purpose, answer);
414추가: }
415추가:
416추가: fn apply_picker(&mut self, purpose: Purpose, answer: DialogAnswer) {
417추가: if answer.is_ok() && self.ui_error.as_deref() == Some(DIALOG_UNAVAILABLE) {
352418 self.ui_error = None;
353419 }
354420 match answer {
@@ -479,19 +545,23 @@ impl ArchiveApp {
479545 self.initialized = true;
480546 }
481547 self.poll();
548추가: self.poll_picker();
482549 let challenge = self.model.challenge.map(|(id, _, _)| id);
483550 let new_challenge = challenge != self.password_challenge;
484551 if new_challenge || challenge.is_none() {
485552 self.clear_password();
486553 }
487554 self.password_challenge = challenge;
488삭제: self.on_drop(ctx.input(|i| {
555추가: let dropped = ctx.input(|i| {
489556 i.raw
490557 .dropped_files
491558 .iter()
492559 .map(|file| file.path().to_path_buf())
493560 .collect()
494삭제: }));
561추가: });
562추가: if self.picker.is_none() {
563추가: self.on_drop(dropped);
564추가: }
495565 if ctx.input(|i| i.viewport().close_requested()) {
496566 self.model.request_close();
497567 if self.model.close != Close::Allowed {
@@ -523,6 +593,19 @@ impl ArchiveApp {
523593 title.clone()
524594 };
525595 ctx.send_viewport_cmd(egui::ViewportCommand::Title(short_title));
596추가: if self.custom_frame
597추가: && window_frame::title_bar(
598추가: root,
599추가: "main",
600추가: &title,
601추가: window_frame::Buttons {
602추가: minimize: true,
603추가: maximize: true,
604추가: },
605추가: )
606추가: {
607추가: self.release_after_move = true;
608추가: }
526609 egui::Panel::top("archive-actions")
527610 .frame(
528611 theme::panel(theme::PANEL)
@@ -531,7 +614,9 @@ impl ArchiveApp {
531614 )
532615 .show(root, |ui| {
533616 ui.horizontal(|ui| {
534삭제: let idle = !self.model.busy() && self.model.close == Close::Open;
617추가: let idle = !self.model.busy()
618추가: && self.model.close == Close::Open
619추가: && self.picker.is_none();
535620 if theme::tool(ui, "열기", theme::OPEN, idle, false)
536621 .on_hover_text(&title)
537622 .clicked()
@@ -587,7 +672,8 @@ impl ArchiveApp {
587672 });
588673 });
589674 });
590삭제: if self.model.busy() || self.result_visible() || (self.ui_error.is_some() && !self.create) {
675추가: if ctx.embed_viewports() && self.work_visible() {
676추가: // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
591677 egui::Panel::bottom("archive-work")
592678 .frame(theme::panel(theme::PANEL).corner_radius(0))
593679 .show(root, |ui| self.work_area(ui));
@@ -605,6 +691,7 @@ impl ArchiveApp {
605691 self.empty(ui);
606692 }
607693 });
694추가: self.work_window(&ctx);
608695 if self.create && !self.model.busy() {
609696 self.create_dialog(&ctx);
610697 }
@@ -612,11 +699,27 @@ impl ArchiveApp {
612699 self.password_dialog(&ctx, new_challenge);
613700 }
614701 self.close_dialog(&ctx);
702추가: self.picker_notice(&ctx);
703추가: if self.custom_frame {
704추가: window_frame::edges(&ctx, true);
705추가: }
615706 if self.model.busy() {
616707 ctx.request_repaint_after(std::time::Duration::from_millis(30));
617708 }
618709 }
619710
711추가: // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
712추가: fn picker_notice(&mut self, ctx: &egui::Context) {
713추가: if self.picker.is_none() {
714추가: return;
715추가: }
716추가: egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
717추가: ui.set_width(360.0);
718추가: ui.label("파일 선택 창에서 선택을 마쳐 주세요");
719추가: });
720추가: ctx.request_repaint_after(std::time::Duration::from_millis(100));
721추가: }
722추가:
620723 fn empty(&mut self, ui: &mut egui::Ui) {
621724 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
622725 let width = (ui.available_width() * 0.60)
@@ -1122,6 +1225,143 @@ impl ArchiveApp {
11221225 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
11231226 }
11241227
1228추가: fn work_visible(&self) -> bool {
1229추가: self.model.busy() || self.result_visible() || (self.ui_error.is_some() && !self.create)
1230추가: }
1231추가:
1232추가: fn work_window(&mut self, ctx: &egui::Context) {
1233추가: if !self.work_visible() {
1234추가: self.work = WorkWindow::default();
1235추가: return;
1236추가: }
1237추가: if ctx.embed_viewports() {
1238추가: // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1239추가: return;
1240추가: }
1241추가: let id = egui::ViewportId::from_hash_of("archive-work");
1242추가: let (parent, parent_focused, now) = ctx.input(|i| {
1243추가: (
1244추가: i.viewport().outer_rect,
1245추가: i.viewport().focused.unwrap_or(false),
1246추가: i.time,
1247추가: )
1248추가: });
1249추가: let (child, child_focused) = ctx.input(|i| {
1250추가: i.raw.viewports.get(&id).map_or((None, false), |v| {
1251추가: (v.outer_rect, v.focused.unwrap_or(false))
1252추가: })
1253추가: });
1254추가: let size = egui::vec2(WORK_WIDTH, self.work.height);
1255추가: if !self.work.open {
1256추가: // 처음 열 때 부모 창 가운데에 둠. Wayland처럼 위치를 알 수 없으면 창 관리자에 맡김.
1257추가: self.work.open = true;
1258추가: self.work.initial = parent.map(|p| (p.center() - size / 2.0).round());
1259추가: self.work.offset = self.work.initial.zip(parent).map(|(c, p)| c - p.min);
1260추가: self.work.parent = parent.map(|p| p.min);
1261추가: self.work.expected = self.work.initial;
1262추가: self.work.settle_until = now + 0.5;
1263추가: }
1264추가: if let (Some(parent), Some(child)) = (parent, child) {
1265추가: let parent_moved = self
1266추가: .work
1267추가: .parent
1268추가: .is_some_and(|p| (p - parent.min).length() > 0.5);
1269추가: let settled = self
1270추가: .work
1271추가: .expected
1272추가: .is_some_and(|e| (child.min - e).length() <= 2.0);
1273추가: if settled || now >= self.work.settle_until {
1274추가: self.work.settle_until = 0.0;
1275추가: }
1276추가: if parent_moved {
1277추가: if let Some(offset) = self.work.offset {
1278추가: let target = (parent.min + offset).round();
1279추가: ctx.send_viewport_cmd_to(id, egui::ViewportCommand::OuterPosition(target));
1280추가: self.work.expected = Some(target);
1281추가: self.work.settle_until = now + 0.5;
1282추가: }
1283추가: } else if self.work.settle_until == 0.0 && !settled {
1284추가: // 사용자가 자식 창을 옮긴 위치를 부모 기준으로 기억함.
1285추가: self.work.offset = Some(child.min - parent.min);
1286추가: self.work.expected = Some(child.min);
1287추가: }
1288추가: self.work.parent = Some(parent.min);
1289추가: }
1290추가: let title = if self.model.busy() {
1291추가: present::activity_text(
1292추가: &self.model,
1293추가: matches!(self.last_request, Some(Start::CreateZip { .. })),
1294추가: )
1295추가: .to_owned()
1296추가: } else {
1297추가: "작업 결과".to_owned()
1298추가: };
1299추가: let window_title = format!("{title} — Zipelo");
1300추가: let custom_frame = self.custom_frame;
1301추가: let mut builder = egui::ViewportBuilder::default()
1302추가: .with_title(window_title.clone())
1303추가: .with_decorations(!custom_frame)
1304추가: .with_inner_size(size)
1305추가: .with_resizable(false)
1306추가: .with_minimize_button(false)
1307추가: .with_maximize_button(false)
1308추가: .with_taskbar(false)
1309추가: // 앱을 쓰는 동안에만 부모 창 위에 유지함.
1310추가: .with_window_level(if parent_focused || child_focused {
1311추가: egui::WindowLevel::AlwaysOnTop
1312추가: } else {
1313추가: egui::WindowLevel::Normal
1314추가: });
1315추가: if let Some(position) = self.work.initial {
1316추가: builder = builder.with_position(position);
1317추가: }
1318추가: let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1319추가: if ui.ctx().input(|i| i.viewport().close_requested()) {
1320추가: if self.model.busy() {
1321추가: ui.ctx()
1322추가: .send_viewport_cmd(egui::ViewportCommand::CancelClose);
1323추가: } else {
1324추가: self.dismissed = true;
1325추가: self.ui_error = None;
1326추가: self.model.input_error = None;
1327추가: }
1328추가: }
1329추가: if class == egui::ViewportClass::EmbeddedWindow {
1330추가: ui.set_width(WORK_WIDTH);
1331추가: self.work_area(ui);
1332추가: return None;
1333추가: }
1334추가: let mut chrome = 0.0;
1335추가: if custom_frame {
1336추가: window_frame::title_bar(
1337추가: ui,
1338추가: "work",
1339추가: &window_title,
1340추가: window_frame::Buttons {
1341추가: minimize: false,
1342추가: maximize: false,
1343추가: },
1344추가: );
1345추가: window_frame::edges(ui.ctx(), false);
1346추가: chrome = window_frame::TITLE_HEIGHT;
1347추가: }
1348추가: let margin = theme::PAD as f32;
1349추가: egui::CentralPanel::default()
1350추가: .frame(theme::panel(theme::PANEL).corner_radius(0))
1351추가: .show(ui, |ui| {
1352추가: let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
1353추가: Some(content.height() + 2.0 * margin + chrome)
1354추가: })
1355추가: .inner
1356추가: });
1357추가: if let Some(height) = height {
1358추가: let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
1359추가: if (height - self.work.height).abs() > 1.0 {
1360추가: self.work.height = height;
1361추가: }
1362추가: }
1363추가: }
1364추가:
11251365 fn work_area(&mut self, ui: &mut egui::Ui) {
11261366 if self.model.busy() {
11271367 self.progress(ui);
@@ -1159,7 +1399,13 @@ impl ArchiveApp {
11591399 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
11601400 let title = present::activity_text(&self.model, creating);
11611401 ui.strong(title);
1162삭제: if let Some((_, done, total, count)) = self.model.progress {
1402추가: if let Some((stage, done, total, count)) = self.model.progress {
1403추가: // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
1404추가: let processed = if stage == Stage::Read {
1405추가: String::new()
1406추가: } else {
1407추가: format!("{count}개 처리함, ")
1408추가: };
11631409 if let Some(total) = total.filter(|n| *n > 0) {
11641410 ui.scope(|ui| {
11651411 ui.visuals_mut().extreme_bg_color = theme::BORDER;
@@ -1171,7 +1417,7 @@ impl ArchiveApp {
11711417 });
11721418 ui.horizontal(|ui| {
11731419 ui.label(format!(
1174삭제: "{:.0}% / {count}개 처리함, {} / {}",
1420추가: "{:.0}% / {processed}{} / {}",
11751421 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
11761422 present::bytes_text(done),
11771423 present::bytes_text(total)
@@ -1181,7 +1427,7 @@ impl ArchiveApp {
11811427 } else {
11821428 theme::indeterminate(ui);
11831429 ui.horizontal(|ui| {
1184삭제: ui.label(format!("{count}개 처리함, {}", present::bytes_text(done)));
1430추가: ui.label(format!("{processed}{}", present::bytes_text(done)));
11851431 self.cancel_action(ui, cancelling);
11861432 });
11871433 }
@@ -1272,7 +1518,7 @@ impl ArchiveApp {
12721518 );
12731519 ui.strong(title);
12741520 });
1275삭제: let max_height = (ui.ctx().content_rect().height() * 0.24).max(80.0);
1521추가: let max_height = WORK_RESULT_MAX_HEIGHT;
12761522 egui::ScrollArea::vertical()
12771523 .id_salt("result-message")
12781524 .max_height(max_height)
@@ -1760,6 +2006,22 @@ impl eframe::App for ArchiveApp {
17602006 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
17612007 self.show(root);
17622008 }
2009추가:
2010추가: fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
2011추가: // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
2012추가: if std::mem::take(&mut self.release_after_move) {
2013추가: let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
2014추가: raw_input.events.insert(
2015추가: 0,
2016추가: egui::Event::PointerButton {
2017추가: pos,
2018추가: button: egui::PointerButton::Primary,
2019추가: pressed: false,
2020추가: modifiers: ctx.input(|i| i.modifiers),
2021추가: },
2022추가: );
2023추가: }
2024추가: }
17632025}
17642026impl Drop for ArchiveApp {
17652027 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+1-0
@@ -909,6 +909,7 @@ mod widgets {
909909 include!("toolbar.rs");
910910 include!("long_layout.rs");
911911 include!("explorer_selection.rs");
912추가: include!("window_frame.rs");
912913}
913914
914915#[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추가: }