team-ljyzipelo

공개
282줄10 KB
1//! GNOME Wayland는 창 테두리를 그려 주지 않으므로 제목 표시줄과 테두리를 직접 그림.
2//! 앱 글꼴로 그려서 한글 제목도 그대로 표시됨.
3
4use crate::archive_theme as theme;
5use eframe::egui::{
6 self, Align2, Color32, CursorIcon, FontId, Rect, ResizeDirection, Sense, Stroke, Vec2,
7 ViewportCommand,
8};
9
10pub const TITLE_HEIGHT: f32 = 38.0;
11const BUTTON_SIZE: Vec2 = egui::vec2(34.0, 26.0);
12const RESIZE_EDGE: f32 = 6.0;
13const DRAG_THRESHOLD: f32 = 4.0;
14const TITLE_BG: Color32 = Color32::from_rgb(235, 238, 242);
15
16/// 창 테두리를 직접 그려야 하는지 판단함.
17/// winit은 Linux에서 Wayland 연결 정보가 있으면 Wayland로 창을 만듦.
18pub 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)]
26pub struct Buttons {
27 pub minimize: bool,
28 pub maximize: bool,
29}
30
31#[derive(Clone, Copy, PartialEq)]
32enum Glyph {
33 Minimize,
34 Maximize,
35 Restore,
36 Close,
37}
38
39/// 위쪽 패널로 제목 표시줄을 그림. 버튼과 끌기 동작은 현재 창에 명령으로 보냄.
40/// 창 이동을 운영체제에 넘긴 프레임이면 true를 돌려줌.
41pub 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의 끌기 상태에 기대면 다음 끌기가 시작되지 않음.
119fn 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
148fn 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/// 폭을 넘는 제목은 앞부분을 줄이고 끝(파일 이름과 앱 이름)을 남김.
208fn 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/// 창 가장자리에서 크기 조절을 시작하고 얇은 테두리를 그림.
231pub 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}