team-ljyzipelo

공개
678줄25 KB
1use eframe::egui::{self, Color32, FontId, Stroke, TextStyle};
2
3pub const BACKGROUND: Color32 = Color32::from_rgb(247, 248, 250);
4pub const PANEL: Color32 = Color32::WHITE;
5pub const STRIPE: Color32 = Color32::from_rgb(243, 245, 248);
6pub const BORDER: Color32 = Color32::from_rgb(217, 222, 229);
7pub const TEXT: Color32 = Color32::from_rgb(31, 41, 51);
8pub const MUTED: Color32 = Color32::from_rgb(91, 102, 115);
9pub const BLUE: Color32 = Color32::from_rgb(37, 99, 235);
10pub const BLUE_HOVER: Color32 = Color32::from_rgb(29, 78, 216);
11pub const BLUE_ACTIVE: Color32 = Color32::from_rgb(30, 64, 175);
12pub const SELECTED: Color32 = Color32::from_rgb(232, 240, 254);
13/// 파일 목록에서 선택한 행의 반투명 파란 배경 (BLUE 12%).
14pub const ROW_SELECTED: Color32 = Color32::from_rgba_unmultiplied_const(37, 99, 235, 31);
15/// 파일 목록에서 마우스를 올린 행의 배경. 선택한 행보다 조금 더 투명함 (BLUE 6%).
16pub const ROW_HOVER: Color32 = Color32::from_rgba_unmultiplied_const(37, 99, 235, 15);
17/// 선택한 행에 마우스를 올렸을 때의 배경. 선택 색보다 덜 투명함 (BLUE 18%).
18pub const ROW_SELECTED_HOVER: Color32 = Color32::from_rgba_unmultiplied_const(37, 99, 235, 46);
19pub const DROP: Color32 = Color32::from_rgb(238, 244, 255);
20pub const DASH: Color32 = Color32::from_rgb(170, 180, 192);
21pub const SUCCESS: Color32 = Color32::from_rgb(21, 128, 61);
22pub const SUCCESS_BG: Color32 = Color32::from_rgb(232, 245, 236);
23pub const WARNING: Color32 = Color32::from_rgb(180, 83, 9);
24pub const WARNING_BG: Color32 = Color32::from_rgb(255, 247, 232);
25pub const ERROR: Color32 = Color32::from_rgb(185, 28, 28);
26pub const ERROR_BG: Color32 = Color32::from_rgb(253, 237, 237);
27pub const FOLDER: Color32 = Color32::from_rgb(240, 160, 0);
28pub const FILE: Color32 = Color32::from_rgb(123, 135, 148);
29pub const SPACE: f32 = 8.0;
30pub const PAD: i8 = 16;
31pub const DROP_PAD: i8 = 24;
32pub const DROP_HEIGHT: f32 = 280.0;
33pub const DROP_RADIUS: u8 = 12;
34pub const ROW: f32 = 32.0;
35pub const BUTTON: f32 = 40.0;
36/// 글자 크기 단계. 앱의 모든 글자는 이 세 값 중 하나를 씀.
37/// 기본 16px을 기준으로 보조 글자는 작게, 제목과 강조 글자는 크게 씀.
38pub const FONT_SMALL: f32 = 14.0;
39pub const FONT_BODY: f32 = 16.0;
40pub const FONT_LARGE: f32 = 20.0;
41/// 경로와 검색 입력란의 높이. 위쪽 경로 줄은 이 높이만큼만 차지함.
42pub const FIELD: f32 = 36.0;
43/// 테두리 없는 버튼에 마우스를 올리거나 누를 때의 배경.
44pub const HOVER: Color32 = Color32::from_rgb(229, 233, 239);
45pub const PRESS: Color32 = Color32::from_rgb(214, 220, 229);
46
47/// 앱에 포함한 기본 글꼴 (SIL OFL 1.1, assets/fonts/OFL.txt).
48pub const PRETENDARD: &[u8] = include_bytes!("assets/fonts/Pretendard-Regular.ttf");
49
50/// Pretendard를 기본 글꼴로 쓰고, 없는 글자는 운영체제 한글 글꼴로 대신 그림.
51pub fn fonts(fallback: Option<(Vec<u8>, u32)>) -> egui::FontDefinitions {
52 let mut fonts = egui::FontDefinitions::empty();
53 fonts.font_data.insert(
54 "pretendard".into(),
55 egui::FontData::from_static(PRETENDARD).into(),
56 );
57 let mut family = vec!["pretendard".to_owned()];
58 if let Some((bytes, index)) = fallback {
59 let mut data = egui::FontData::from_owned(bytes);
60 data.index = index;
61 fonts.font_data.insert("system-kr".into(), data.into());
62 family.push("system-kr".into());
63 }
64 fonts
65 .families
66 .insert(egui::FontFamily::Proportional, family.clone());
67 fonts.families.insert(egui::FontFamily::Monospace, family);
68 fonts
69}
70
71pub fn apply(ctx: &egui::Context) {
72 ctx.set_theme(egui::Theme::Light);
73 ctx.set_visuals(egui::Visuals::light());
74 ctx.style_mut_of(egui::Theme::Light, |style| {
75 style
76 .text_styles
77 .insert(TextStyle::Body, FontId::proportional(FONT_BODY));
78 style
79 .text_styles
80 .insert(TextStyle::Button, FontId::proportional(FONT_BODY));
81 style
82 .text_styles
83 .insert(TextStyle::Small, FontId::proportional(FONT_SMALL));
84 style
85 .text_styles
86 .insert(TextStyle::Heading, FontId::proportional(FONT_LARGE));
87 style.visuals.override_text_color = Some(TEXT);
88 style.visuals.panel_fill = BACKGROUND;
89 style.visuals.window_fill = PANEL;
90 style.visuals.extreme_bg_color = PANEL;
91 style.visuals.faint_bg_color = STRIPE;
92 style.visuals.selection.bg_fill = SELECTED;
93 style.visuals.selection.stroke = Stroke::new(2.0, BLUE);
94 style.visuals.widgets.inactive.bg_fill = PANEL;
95 style.visuals.widgets.inactive.weak_bg_fill = PANEL;
96 style.visuals.widgets.inactive.bg_stroke = Stroke::new(1.0, BORDER);
97 style.visuals.widgets.hovered.bg_fill = DROP;
98 style.visuals.widgets.hovered.weak_bg_fill = DROP;
99 style.visuals.widgets.hovered.bg_stroke = Stroke::new(1.0, BLUE);
100 style.visuals.widgets.active.bg_stroke = Stroke::new(2.0, BLUE);
101 for widget in [
102 &mut style.visuals.widgets.inactive,
103 &mut style.visuals.widgets.hovered,
104 &mut style.visuals.widgets.active,
105 &mut style.visuals.widgets.noninteractive,
106 ] {
107 widget.corner_radius = egui::CornerRadius::same(6);
108 widget.fg_stroke = Stroke::new(1.5, TEXT);
109 }
110 style.visuals.window_corner_radius = egui::CornerRadius::same(8);
111 style.spacing.item_spacing = egui::vec2(SPACE, SPACE);
112 style.spacing.button_padding = egui::vec2(16.0, SPACE);
113 style.spacing.interact_size.y = ROW;
114 style.spacing.window_margin = egui::Margin::same(PAD);
115 style.visuals.disabled_alpha = 0.4;
116 // egui 기본 버튼에도 손 모양 커서를 씀.
117 style.visuals.interact_cursor = Some(egui::CursorIcon::PointingHand);
118 // 클릭과 표시가 즉시 바뀌도록 서서히 나타남, 부드러운 스크롤, 커서 깜빡임을 모두 끔.
119 style.animation_time = 0.0;
120 style.scroll_animation = egui::style::ScrollAnimation::none();
121 style.visuals.text_cursor.blink = false;
122 });
123}
124
125/// 누를 수 있는 버튼이나 항목에 마우스를 올리면 손 모양 커서를 보여 줌.
126/// 사용할 수 없거나 누를 수 없는 영역(끌기 전용 등)은 그대로 둠.
127pub fn pointer(response: &egui::Response) {
128 if response.enabled() && response.sense.senses_click() && response.hovered() {
129 response.ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
130 }
131}
132
133pub fn focus(response: &egui::Response) {
134 if response.has_focus() {
135 response.ctx.layer_painter(response.layer_id).rect_stroke(
136 response.rect.expand(2.0),
137 6,
138 Stroke::new(2.0, BLUE),
139 egui::StrokeKind::Outside,
140 );
141 }
142}
143
144pub fn action(ui: &mut egui::Ui, text: &str, primary: bool, enabled: bool) -> egui::Response {
145 let size = egui::vec2(
146 if primary { 112.0 } else { 0.0 },
147 if primary { BUTTON } else { 36.0 },
148 );
149 action_sized(ui, text, primary, enabled, size)
150}
151
152/// 정한 최소 크기로 버튼을 그림. 함께 놓이는 버튼끼리 크기를 맞출 때 씀.
153pub fn action_sized(
154 ui: &mut egui::Ui,
155 text: &str,
156 primary: bool,
157 enabled: bool,
158 size: egui::Vec2,
159) -> egui::Response {
160 let response = ui
161 .scope(|ui| {
162 if primary {
163 let style = ui.style_mut();
164 style.visuals.widgets.inactive.bg_fill = BLUE;
165 style.visuals.widgets.inactive.weak_bg_fill = BLUE;
166 style.visuals.widgets.hovered.bg_fill = BLUE_HOVER;
167 style.visuals.widgets.hovered.weak_bg_fill = BLUE_HOVER;
168 style.visuals.widgets.active.bg_fill = BLUE_ACTIVE;
169 style.visuals.widgets.active.weak_bg_fill = BLUE_ACTIVE;
170 }
171 ui.add_enabled(
172 enabled,
173 egui::Button::new(egui::RichText::new(text).strong().color(if primary {
174 PANEL
175 } else if text == "취소" {
176 ERROR
177 } else {
178 TEXT
179 }))
180 .min_size(size)
181 .stroke(Stroke::new(1.0, if primary { BLUE } else { BORDER })),
182 )
183 })
184 .inner;
185 pointer(&response);
186 focus(&response);
187 response
188}
189
190pub const STATUS_HEIGHT: f32 = 34.0;
191
192/// 파일 목록 행 배경. 선택한 행에 마우스를 올리면 선택 색보다 진하게,
193/// 선택하지 않은 행에 마우스를 올리면 선택 색보다 옅게 칠함.
194pub fn row_background(ui: &egui::Ui, rect: egui::Rect, selected: bool, hovered: bool) {
195 let fill = if selected && hovered {
196 ROW_SELECTED_HOVER
197 } else if selected {
198 ROW_SELECTED
199 } else if hovered {
200 ROW_HOVER
201 } else {
202 return;
203 };
204 ui.painter().rect_filled(rect, 0, fill);
205}
206
207/// 경로 줄 높이를 꽉 채우는 입력란을 그림. 모서리는 각지게 하고,
208/// 위 테두리는 상단 메뉴의 구분선이, 아래 테두리는 경로 줄의 아래 선이 대신해
209/// 선이 겹쳐 보이지 않게 함. 초점이 있으면 파란 테두리.
210pub fn field_frame(ui: &egui::Ui, rect: egui::Rect, focused: bool) {
211 let painter = ui.painter();
212 painter.rect_filled(rect, 0, PANEL);
213 if focused {
214 painter.rect_stroke(rect, 0, Stroke::new(1.0, BLUE), egui::StrokeKind::Inside);
215 return;
216 }
217 let stroke = Stroke::new(1.0, BORDER);
218 painter.vline(rect.left() + 0.5, rect.y_range(), stroke);
219 painter.vline(rect.right() - 0.5, rect.y_range(), stroke);
220}
221
222/// 네 변 테두리가 모두 있는 입력란 모양 (주변에 구분선이 없는 곳에서 씀).
223pub fn boxed_field(ui: &egui::Ui, rect: egui::Rect) {
224 ui.painter().rect(
225 rect,
226 0,
227 PANEL,
228 Stroke::new(1.0, BORDER),
229 egui::StrokeKind::Inside,
230 );
231}
232
233/// 입력란 안에 경로처럼 한 줄 글자를 그림. 넘치면 줄이고 전체 글자는 툴팁으로 보여 줌.
234/// 부모 배치에 영향을 주지 않는 하위 영역을 써서 옆 칸의 위치가 흔들리지 않게 함.
235pub fn field_text(ui: &mut egui::Ui, rect: egui::Rect, text: &str) {
236 let mut child = ui.new_child(
237 egui::UiBuilder::new()
238 .max_rect(rect.shrink2(egui::vec2(10.0, 0.0)))
239 .layout(egui::Layout::left_to_right(egui::Align::Center)),
240 );
241 bounded_text(&mut child, text, (rect.width() - 20.0).max(0.0));
242}
243
244/// 상태 줄 글자를 칸의 세로 가운데에 그림. 넘치면 줄이고 전체 글자는 툴팁으로 보여 줌.
245pub fn status_text(
246 ui: &mut egui::Ui,
247 rect: egui::Rect,
248 text: &str,
249 width: f32,
250 align: egui::Align,
251) {
252 let mut job = egui::text::LayoutJob::simple_singleline(
253 text.into(),
254 FontId::proportional(FONT_BODY),
255 TEXT,
256 );
257 job.wrap = egui::text::TextWrapping {
258 max_width: width.max(0.0),
259 max_rows: 1,
260 ..Default::default()
261 };
262 let galley = ui.fonts_mut(|fonts| fonts.layout_job(job));
263 let size = galley.size();
264 let x = if align == egui::Align::Max {
265 rect.right() - size.x
266 } else {
267 rect.left()
268 };
269 let text_rect = egui::Rect::from_min_size(egui::pos2(x, rect.center().y - size.y / 2.0), size);
270 ui.painter().galley(text_rect.min, galley, TEXT);
271 let response = ui.interact(
272 text_rect,
273 ui.scope_id()
274 .with(("status-text", align == egui::Align::Max)),
275 egui::Sense::hover(),
276 );
277 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text));
278 response.on_hover_text(text);
279}
280
281pub fn panel(fill: Color32) -> egui::Frame {
282 egui::Frame::new()
283 .fill(fill)
284 .inner_margin(egui::Margin::same(PAD))
285 .corner_radius(8)
286}
287
288#[derive(Clone, Copy)]
289pub enum Icon {
290 File,
291 Folder,
292 Archive,
293 Lock,
294 Success,
295 Warning,
296 Error,
297}
298
299pub fn icon(ui: &mut egui::Ui, kind: Icon, size: f32) {
300 let (rect, _) = ui.allocate_exact_size(egui::vec2(size, size), egui::Sense::hover());
301 let p = ui.painter();
302 let color = match kind {
303 Icon::Folder => FOLDER,
304 Icon::Archive => BLUE,
305 Icon::Lock | Icon::Warning => WARNING,
306 Icon::Success => SUCCESS,
307 Icon::Error => ERROR,
308 Icon::File => FILE,
309 };
310 let s = Stroke::new(if size > 32.0 { 2.5 } else { 1.5 }, color);
311 let point = |x, y| rect.min + egui::vec2(x * size, y * size);
312 let box_at = |x, y, w, h| egui::Rect::from_min_max(point(x, y), point(x + w, y + h));
313 match kind {
314 Icon::Folder => {
315 p.rect_filled(box_at(0.08, 0.22, 0.42, 0.22), 2, color);
316 p.rect_filled(box_at(0.08, 0.34, 0.84, 0.50), 2, color);
317 }
318 Icon::File | Icon::Archive => {
319 p.rect_stroke(
320 box_at(0.19, 0.08, 0.62, 0.84),
321 2,
322 s,
323 egui::StrokeKind::Inside,
324 );
325 p.line_segment([point(0.60, 0.08), point(0.60, 0.30)], s);
326 p.line_segment([point(0.60, 0.30), point(0.81, 0.30)], s);
327 if matches!(kind, Icon::Archive) {
328 for y in [0.42, 0.57, 0.72] {
329 p.line_segment([point(0.39, y), point(0.59, y)], s);
330 }
331 }
332 }
333 Icon::Lock => {
334 p.circle_stroke(point(0.50, 0.35), size * 0.23, s);
335 p.rect_filled(box_at(0.18, 0.39, 0.64, 0.47), 2, color);
336 }
337 Icon::Success | Icon::Error => {
338 p.circle_stroke(rect.center(), size * 0.40, s);
339 if matches!(kind, Icon::Success) {
340 p.line_segment([point(0.28, 0.50), point(0.44, 0.66)], s);
341 p.line_segment([point(0.44, 0.66), point(0.74, 0.33)], s);
342 } else {
343 p.line_segment([point(0.34, 0.34), point(0.66, 0.66)], s);
344 p.line_segment([point(0.66, 0.34), point(0.34, 0.66)], s);
345 }
346 }
347 Icon::Warning => {
348 p.add(egui::Shape::closed_line(
349 vec![point(0.50, 0.08), point(0.94, 0.86), point(0.06, 0.86)],
350 s,
351 ));
352 p.line_segment([point(0.50, 0.32), point(0.50, 0.57)], s);
353 p.circle_filled(point(0.50, 0.73), size * 0.035, color);
354 }
355 }
356}
357
358pub fn bounded_text(ui: &mut egui::Ui, text: &str, width: f32) -> egui::Response {
359 bounded_text_hover(ui, text, text, width)
360}
361
362/// 폭에 맞춰 줄인 글자를 그리고, 마우스를 올리면 hover 글자를 보여 줌.
363pub fn bounded_text_hover(
364 ui: &mut egui::Ui,
365 text: &str,
366 hover: &str,
367 width: f32,
368) -> egui::Response {
369 let width = width.max(0.0);
370 ui.allocate_ui_with_layout(
371 egui::vec2(width, ui.text_style_height(&TextStyle::Body)),
372 ui.layout().clone(),
373 |ui| {
374 ui.set_min_width(width);
375 ui.set_max_width(width);
376 ui.add(egui::Label::new(text).truncate())
377 },
378 )
379 .inner
380 .on_hover_text(hover)
381}
382
383pub fn window_title(ui: &egui::Ui, text: &str, width: f32) -> String {
384 let mut job = egui::text::LayoutJob::simple_singleline(
385 text.into(),
386 FontId::proportional(FONT_BODY),
387 TEXT,
388 );
389 job.wrap = egui::text::TextWrapping {
390 max_width: width.max(0.0),
391 max_rows: 1,
392 break_anywhere: true,
393 ..Default::default()
394 };
395 ui.fonts_mut(|fonts| fonts.layout_job(job))
396 .rows
397 .iter()
398 .flat_map(|row| row.glyphs.iter().map(|glyph| glyph.chr))
399 .collect()
400}
401
402pub fn column_label(
403 ui: &mut egui::Ui,
404 text: impl Into<egui::WidgetText>,
405 width: f32,
406 align: egui::Align,
407) -> egui::Response {
408 let layout = if align == egui::Align::Max {
409 egui::Layout::right_to_left(egui::Align::Center)
410 } else {
411 egui::Layout::left_to_right(egui::Align::Center)
412 };
413 ui.allocate_ui_with_layout(egui::vec2(width, ROW), layout, |ui| {
414 ui.set_min_width(width);
415 ui.set_max_width(width);
416 ui.add(egui::Label::new(text).truncate())
417 })
418 .inner
419}
420
421pub fn action_pair(
422 ui: &mut egui::Ui,
423 secondary: &str,
424 primary: Option<(&str, bool)>,
425) -> (bool, bool) {
426 let text_width = |text: &str| {
427 ui.painter()
428 .layout_no_wrap(text.into(), FontId::proportional(FONT_BODY), TEXT)
429 .size()
430 .x
431 };
432 // 두 버튼은 긴 쪽 글자에 맞춘 같은 크기로 그림.
433 let button = egui::vec2(
434 primary
435 .map_or(0.0, |(label, _)| text_width(label))
436 .max(text_width(secondary))
437 + 32.0,
438 BUTTON,
439 )
440 .max(egui::vec2(112.0, BUTTON));
441 let count = if primary.is_some() { 2.0 } else { 1.0 };
442 let width = button.x * count + SPACE * (count - 1.0);
443 ui.horizontal(|ui| {
444 ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
445 ui.add_space((ui.available_width() - width).max(0.0));
446 let secondary = action_sized(ui, secondary, false, true, button).clicked();
447 let primary = primary.is_some_and(|(label, enabled)| {
448 action_sized(ui, label, true, enabled, button)
449 .on_disabled_hover_text(match label {
450 "만들기" => "묶을 파일이나 폴더를 추가하세요",
451 "다른 폴더에 풀기" => "기존 풀 위치 폴더를 먼저 확인하세요",
452 _ => "입력한 내용을 확인하세요",
453 })
454 .clicked()
455 });
456 (secondary, primary)
457 })
458 .inner
459 })
460 .inner
461}
462
463pub fn indeterminate(ui: &mut egui::Ui) {
464 let (rect, response) = ui.allocate_exact_size(
465 egui::vec2(ui.available_width(), SPACE * 2.0),
466 egui::Sense::hover(),
467 );
468 // 움직이는 표시 없이 전체 막대를 옅은 파란색으로 채워 진행 중임을 나타냄.
469 ui.painter()
470 .rect_filled(rect, 8, Color32::from_rgb(191, 211, 248));
471 response.widget_info(|| {
472 egui::WidgetInfo::labeled(
473 egui::Role::ProgressIndicator,
474 ui.is_enabled(),
475 "전체 크기를 알 수 없는 작업 진행 중",
476 )
477 });
478}
479
480pub const OPEN: &str = include_str!("assets/icons/open-archive.svg");
481pub const CREATE: &str = include_str!("assets/icons/create-zip.svg");
482pub const EXTRACT: &str = include_str!("assets/icons/extract-archive.svg");
483pub const UP: &str = include_str!("assets/icons/navigate-up.svg");
484pub const CLOSE: &str = include_str!("assets/icons/close-dialog.svg");
485
486pub fn svg_icon(painter: &egui::Painter, rect: egui::Rect, asset: &str, color: Color32) {
487 for element in asset.split("points=\"").skip(1) {
488 let points = element
489 .split('"')
490 .next()
491 .unwrap_or_default()
492 .split_whitespace()
493 .filter_map(|pair| {
494 let (x, y) = pair.split_once(',')?;
495 Some(
496 rect.min
497 + egui::vec2(x.parse::<f32>().ok()?, y.parse::<f32>().ok()?)
498 * (rect.width() / 24.0),
499 )
500 })
501 .collect::<Vec<_>>();
502 let width = rect.width() / 18.0;
503 // 꼭짓점과 끝점에 원을 더해 둥근 이음과 둥근 끝을 만듦.
504 for point in &points {
505 painter.circle_filled(*point, width / 2.0, color);
506 }
507 painter.add(egui::Shape::line(points, Stroke::new(width, color)));
508 }
509}
510
511/// 가장 긴 이름(압축해제, FONT_SMALL에서 약 48px) 양옆에 12px씩 남는 폭.
512pub const TOOL_SIZE: egui::Vec2 = egui::vec2(72.0, 60.0);
513const TOOL_ICON: f32 = 30.0;
514const TOOL_LABEL: f32 = FONT_SMALL;
515/// 아이콘 그림 아래와 이름 글자 위 사이의 보이는 간격.
516const TOOL_GAP: f32 = 6.0;
517
518/// SVG 폴리라인 점들의 세로 범위(24 단위 좌표).
519fn svg_y_range(asset: &str) -> Option<(f32, f32)> {
520 asset
521 .split("points=\"")
522 .skip(1)
523 .flat_map(|element| {
524 element
525 .split('"')
526 .next()
527 .unwrap_or_default()
528 .split_whitespace()
529 .filter_map(|pair| pair.split_once(',')?.1.parse::<f32>().ok())
530 .collect::<Vec<_>>()
531 })
532 .fold(None, |range: Option<(f32, f32)>, y| {
533 Some(range.map_or((y, y), |(lo, hi)| (lo.min(y), hi.max(y))))
534 })
535}
536
537/// 상단 메뉴 아이콘 세 개를 합친 그림 범위. 모든 버튼이 같은 기준을 써서 이름 높이가 맞음.
538fn tool_icon_ink() -> (f32, f32) {
539 let scale = TOOL_ICON / 24.0;
540 let half_stroke = TOOL_ICON / 18.0 / 2.0;
541 let (lo, hi) = [OPEN, CREATE, EXTRACT]
542 .iter()
543 .filter_map(|asset| svg_y_range(asset))
544 .fold((24.0f32, 0.0f32), |(lo, hi), (a, b)| (lo.min(a), hi.max(b)));
545 (lo * scale - half_stroke, hi * scale + half_stroke)
546}
547
548/// 글자 줄 상자가 아니라 실제로 그려지는 글자 모양의 위아래 범위.
549fn galley_ink(galley: &egui::Galley) -> (f32, f32) {
550 galley
551 .rows
552 .iter()
553 .flat_map(|row| {
554 row.glyphs
555 .iter()
556 .filter(|g| g.uv_rect.size.y > 0.0)
557 .map(move |g| {
558 let top = row.pos.y + g.pos.y + g.uv_rect.offset.y;
559 (top, top + g.uv_rect.size.y)
560 })
561 })
562 .fold(None, |range: Option<(f32, f32)>, (top, bottom)| {
563 Some(range.map_or((top, bottom), |(a, b)| (a.min(top), b.max(bottom))))
564 })
565 .unwrap_or((0.0, galley.size().y))
566}
567
568pub fn tool(
569 ui: &mut egui::Ui,
570 label: &str,
571 asset: &str,
572 enabled: bool,
573 blue: bool,
574) -> egui::Response {
575 let (rect, response) = ui.allocate_exact_size(
576 TOOL_SIZE,
577 if enabled {
578 egui::Sense::click()
579 } else {
580 egui::Sense::hover()
581 },
582 );
583 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label));
584 let color = if enabled {
585 if blue { BLUE } else { TEXT }
586 } else {
587 MUTED
588 };
589 if enabled && (response.hovered() || response.has_focus()) {
590 let fill = if response.is_pointer_button_down_on() {
591 PRESS
592 } else {
593 HOVER
594 };
595 ui.painter().rect_filled(rect, 8, fill);
596 }
597 // 아이콘 그림 위쪽부터 글자 모양 아래쪽까지를 하나로 보고 버튼 가운데에 둠.
598 // 그래서 마우스를 올려 배경이 보일 때 위아래 여백이 같음.
599 let galley =
600 ui.painter()
601 .layout_no_wrap(label.to_owned(), FontId::proportional(TOOL_LABEL), color);
602 let (icon_top, icon_bottom) = tool_icon_ink();
603 let (text_top, text_bottom) = galley_ink(&galley);
604 let block = (icon_bottom - icon_top) + TOOL_GAP + (text_bottom - text_top);
605 let start = rect.top() + (rect.height() - block) / 2.0;
606 let icon_rect = egui::Rect::from_min_size(
607 egui::pos2(rect.center().x - TOOL_ICON / 2.0, start - icon_top),
608 egui::vec2(TOOL_ICON, TOOL_ICON),
609 );
610 svg_icon(ui.painter(), icon_rect, asset, color);
611 let text_y = start + (icon_bottom - icon_top) + TOOL_GAP - text_top;
612 ui.painter().galley(
613 egui::pos2(rect.center().x - galley.size().x / 2.0, text_y).round(),
614 galley,
615 color,
616 );
617 pointer(&response);
618 focus(&response);
619 response
620}
621
622/// 테두리와 배경 없이 아이콘만 그리는 버튼. 사용할 수 있을 때만 마우스를 올리면 배경이 어두워짐.
623pub fn flat_icon_button(
624 ui: &mut egui::Ui,
625 name: &str,
626 asset: &str,
627 enabled: bool,
628 size: egui::Vec2,
629) -> egui::Response {
630 let (rect, response) = ui.allocate_exact_size(
631 size,
632 if enabled {
633 egui::Sense::click()
634 } else {
635 egui::Sense::hover()
636 },
637 );
638 let response = response.on_hover_text(name);
639 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name));
640 if enabled && response.hovered() {
641 let fill = if response.is_pointer_button_down_on() {
642 PRESS
643 } else {
644 HOVER
645 };
646 ui.painter().rect_filled(rect, 6, fill);
647 }
648 svg_icon(
649 ui.painter(),
650 egui::Rect::from_center_size(rect.center(), egui::vec2(20.0, 20.0)),
651 asset,
652 if enabled { TEXT } else { MUTED },
653 );
654 pointer(&response);
655 focus(&response);
656 response
657}
658
659pub const SEARCH: &str = include_str!("assets/icons/search-files.svg");
660
661pub fn icon_button(ui: &mut egui::Ui, name: &str, asset: &str, enabled: bool) -> egui::Response {
662 let response = ui
663 .add_enabled(
664 enabled,
665 egui::Button::new("").min_size(egui::vec2(38.0, 36.0)),
666 )
667 .on_hover_text(name);
668 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name));
669 svg_icon(
670 ui.painter(),
671 egui::Rect::from_center_size(response.rect.center(), egui::vec2(22.0, 22.0)),
672 asset,
673 if enabled { TEXT } else { MUTED },
674 );
675 pointer(&response);
676 focus(&response);
677 response
678}