Skip to main content

mgui_core/
theme.rs

1//! 阶段 4-A:Theme + Direction — 第一个 InheritedWidget 用例
2//!
3//! 设计文档 § 6 + § 19.Theme:全局视觉风格沿树向下传递。
4//!
5//! ```ignore
6//! ThemeWidget::new(ThemeData::dark())
7//!     .direction(Direction::Ltr)
8//!     .child(MyApp())
9//! ```
10//!
11//! 任何后代 widget 在 `state.build(ctx)` 中调 `ctx.depend_on::<ThemeWidget>()` 或
12//! 便捷的 `ctx.theme()` / `ctx.direction()` 拿当前主题。
13
14use crate::inherited::InheritedWidget;
15use crate::widget::{Widget, WidgetNode};
16use crate::{Color, Point, Size};
17use std::any::Any;
18use std::rc::Rc;
19
20// =================================================================
21// ThemeData — 纯数据,无 Widget 概念
22// =================================================================
23
24/// Text style defaults (theme-level).
25/// Individual TextWidget can override via TextStyle.
26#[derive(Debug, Clone, PartialEq)]
27pub struct TextTheme {
28    pub headline: TextStyleTheme,
29    pub title: TextStyleTheme,
30    pub body: TextStyleTheme,
31    pub caption: TextStyleTheme,
32}
33
34#[derive(Debug, Clone, PartialEq)]
35pub struct TextStyleTheme {
36    pub font_size: f32,
37    pub color: Color,
38}
39
40/// Button style defaults.
41#[derive(Debug, Clone, PartialEq)]
42pub struct ButtonStyle {
43    pub background: Color,
44    pub foreground: Color,
45    pub radius: f32,
46    pub focus_ring_color: Color,
47    pub focus_ring_width: f32,
48}
49
50/// Scrollbar style defaults (ListView + ScrollView).
51#[derive(Debug, Clone, PartialEq)]
52pub struct ScrollbarStyle {
53    pub thumb_color: Color,
54    /// 指针悬停(或拖拽中)在 thumb 上时的高亮色
55    pub thumb_hover_color: Color,
56    pub thumb_radius: f32,
57    pub thumb_width: f32,       // paint width (hit area is +2px)
58    pub hit_width: f32,         // hit test area width
59    pub thumb_min_size: f32,    // min thumb size in main axis px
60    pub thumb_track_ratio: f32, // thumb_main = viewport_main * ratio
61}
62
63/// TextField / 输入框样式(IDEA 风格:无边框底色 + 焦点蓝边)。
64#[derive(Debug, Clone, PartialEq)]
65pub struct InputStyle {
66    pub background: Color,
67    pub border: Color,
68    pub focused_border: Color,
69    pub text_color: Color,
70    pub placeholder_color: Color,
71    pub radius: f32,
72}
73
74/// Tooltip 浮层样式。
75#[derive(Debug, Clone, PartialEq)]
76pub struct TooltipStyle {
77    pub background: Color,
78    pub foreground: Color,
79    pub border: Color,
80    pub radius: f32,
81}
82
83/// 菜单 / 右键 ContextMenu / 下拉列表样式。
84#[derive(Debug, Clone, PartialEq)]
85pub struct MenuStyle {
86    pub background: Color,
87    pub foreground: Color,
88    pub hover_background: Color,
89    pub border: Color,
90    pub radius: f32,
91}
92
93/// TabBar / TabView / TabbedPane 样式。
94#[derive(Debug, Clone, PartialEq)]
95pub struct TabStyle {
96    pub background: Color,
97    pub active_foreground: Color,
98    pub inactive_foreground: Color,
99    pub hover_background: Color,
100    pub indicator_color: Color,
101}
102
103/// NavigationMenu 样式。
104#[derive(Debug, Clone, PartialEq)]
105pub struct NavStyle {
106    pub active_background: Color,
107    pub active_foreground: Color,
108    pub foreground: Color,
109    pub hover_background: Color,
110    pub indicator_color: Color,
111}
112
113/// 反馈类组件样式(进度条 / Toast 等)。
114#[derive(Debug, Clone, PartialEq)]
115pub struct FeedbackStyle {
116    pub progress_track: Color,
117    pub progress_value: Color,
118    pub success: Color,
119    pub warning: Color,
120}
121
122/// Dropdown 触发器 + 弹出面板样式。
123#[derive(Debug, Clone, PartialEq)]
124pub struct DropdownStyle {
125    pub background: Color,
126    pub foreground: Color,
127    pub placeholder: Color,
128    pub border: Color,
129    pub open_border: Color,
130    pub hover: Color,
131    pub selected_background: Color,
132    pub disabled: Color,
133}
134
135/// Dialog 遮罩 + 对话框样式。
136#[derive(Debug, Clone, PartialEq)]
137pub struct DialogStyle {
138    pub barrier: Color,
139    pub background: Color,
140    pub radius: f32,
141}
142
143/// ListView / 列表类样式。
144#[derive(Debug, Clone, PartialEq)]
145pub struct ListStyle {
146    pub hover_background: Color,
147    pub selected_background: Color,
148    pub foreground: Color,
149}
150
151/// 主题色板 + 子主题。
152///
153/// 所有 `update_should_notify` 走 `PartialEq` 派生自动比较。
154///
155/// 风格基准:**JetBrains IDEA New UI**(`idea_dark()` / `idea_light()`),
156/// `dark()` / `light()` 为同名别名。通用令牌(border / divider / hover)
157/// 供全部组件共享,做到"一次改主题、全局换肤"。
158#[derive(Debug, Clone, PartialEq)]
159pub struct ThemeData {
160    // --- ColorScheme (core) ---
161    pub background: Color,
162    pub foreground: Color,
163    pub primary: Color,
164    pub accent: Color,
165    pub surface: Color,
166    pub error: Color,
167
168    // --- 通用令牌(全组件共享) ---
169    pub border: Color,    // 组件描边
170    pub divider: Color,   // Divider / 分隔线
171    pub hover: Color,     // hover 覆盖层(带 alpha)
172    pub disabled: Color,  // 禁用态前景(或带 alpha 覆盖)
173    pub selection: Color, // 文本/列表选中背景(primary 系 alpha)
174    pub icon: Color,      // 图标默认 tint
175
176    // --- Radius ---
177    pub radius_sm: f32, // 2.0 — checkbox / small pill
178    pub radius_md: f32, // 4.0 — button / input(IDEA 小圆角)
179    pub radius_lg: f32, // 8.0 — dialog / menu / large card
180
181    // --- Spacing ---
182    pub spacing: f32, // 8.0 — default widget spacing
183
184    // --- Sub-themes ---
185    pub text: TextTheme,
186    pub button: ButtonStyle,
187    pub scrollbar: ScrollbarStyle,
188    pub input: InputStyle,
189    pub tooltip: TooltipStyle,
190    pub menu: MenuStyle,
191    pub tab: TabStyle,
192    pub nav: NavStyle,
193    pub feedback: FeedbackStyle,
194    pub dropdown: DropdownStyle,
195    pub dialog: DialogStyle,
196    pub list: ListStyle,
197}
198
199impl Default for ThemeData {
200    fn default() -> Self {
201        Self::idea_dark()
202    }
203}
204
205impl ThemeData {
206    /// JetBrains IDEA New UI — 深色(Darcula 系新 UI)。
207    pub fn idea_dark() -> Self {
208        let bg = Color::from_rgb8(43, 45, 48); // #2B2D30 主背景
209        let fg = Color::from_rgb8(223, 225, 229); // #DFE1E5 前景文字
210        let primary = Color::from_rgb8(84, 138, 247); // #548AF7 主强调蓝
211        let accent = Color::from_rgb8(242, 197, 92); // #F2C55C 次强调(警告黄系)
212        let surface = Color::from_rgb8(57, 59, 64); // #393B40 面板/浮层底
213        let error = Color::from_rgb8(229, 87, 101); // #E55765
214        let border = Color::from_rgb8(78, 81, 87); // #4E5157 描边
215        let caption = Color::from_rgb8(157, 160, 168); // #9DA0A8 次要文字
216        let text = TextTheme {
217            headline: TextStyleTheme { font_size: 20.0, color: fg },
218            title: TextStyleTheme { font_size: 15.0, color: fg },
219            body: TextStyleTheme { font_size: 13.0, color: fg },
220            caption: TextStyleTheme { font_size: 12.0, color: caption },
221        };
222        let button = ButtonStyle {
223            background: primary,
224            foreground: Color::WHITE,
225            radius: 4.0,
226            focus_ring_color: primary,
227            focus_ring_width: 2.0,
228        };
229        let scrollbar = ScrollbarStyle {
230            thumb_color: Color::rgba(0.55, 0.58, 0.63, 0.60),
231            thumb_hover_color: Color::rgba(0.72, 0.75, 0.80, 0.90),
232            thumb_radius: 4.0,
233            thumb_width: 8.0,
234            hit_width: 10.0,
235            thumb_min_size: 24.0,
236            thumb_track_ratio: 0.32,
237        };
238        let input = InputStyle {
239            background: Color::from_rgb8(67, 69, 74), // #43454A
240            border,
241            focused_border: primary,
242            text_color: fg,
243            placeholder_color: Color::from_rgb8(126, 131, 140), // #7E838C
244            radius: 4.0,
245        };
246        let tooltip = TooltipStyle { background: surface, foreground: fg, border, radius: 4.0 };
247        let menu = MenuStyle {
248            background: surface,
249            foreground: fg,
250            hover_background: Color::from_rgb8(74, 77, 82), // #4A4D52
251            border,
252            radius: 6.0,
253        };
254        let tab = TabStyle {
255            background: bg,
256            active_foreground: fg,
257            inactive_foreground: caption,
258            hover_background: Color::from_rgb8(62, 65, 70), // #3E4146
259            indicator_color: primary,
260        };
261        let nav = NavStyle {
262            active_background: Color::rgba(0.33, 0.54, 0.97, 0.18),
263            active_foreground: primary,
264            foreground: fg,
265            hover_background: Color::from_rgb8(74, 77, 82),
266            indicator_color: primary,
267        };
268        let feedback = FeedbackStyle {
269            progress_track: Color::rgba(1.0, 1.0, 1.0, 0.15),
270            progress_value: primary,
271            success: Color::from_rgb8(54, 150, 86), // #369656
272            warning: accent,
273        };
274        let dropdown = DropdownStyle {
275            background: surface,
276            foreground: fg,
277            placeholder: Color::from_rgb8(126, 131, 140), // #7E838C
278            border,
279            open_border: primary,
280            hover: Color::from_rgb8(74, 77, 82), // #4A4D52
281            selected_background: Color::rgba(0.33, 0.54, 0.97, 0.22),
282            disabled: Color::rgba(1.0, 1.0, 1.0, 0.35),
283        };
284        let dialog = DialogStyle { barrier: Color::rgba(0.0, 0.0, 0.0, 0.45), background: surface, radius: 8.0 };
285        let list = ListStyle {
286            hover_background: Color::rgba(1.0, 1.0, 1.0, 0.06),
287            selected_background: Color::rgba(0.33, 0.54, 0.97, 0.22),
288            foreground: fg,
289        };
290        Self {
291            background: bg,
292            foreground: fg,
293            primary,
294            accent,
295            surface,
296            error,
297            border,
298            divider: Color::from_rgb8(62, 65, 70), // #3E4146 — 在 #2B2D30 上清晰可辨
299            hover: Color::rgba(1.0, 1.0, 1.0, 0.08),
300            disabled: Color::rgba(1.0, 1.0, 1.0, 0.35),
301            selection: Color::rgba(0.33, 0.54, 0.97, 0.28),
302            icon: fg,
303            radius_sm: 2.0,
304            radius_md: 4.0,
305            radius_lg: 8.0,
306            spacing: 8.0,
307            text,
308            button,
309            scrollbar,
310            input,
311            tooltip,
312            menu,
313            tab,
314            nav,
315            feedback,
316            dropdown,
317            dialog,
318            list,
319        }
320    }
321
322    /// JetBrains IDEA New UI — 浅色。
323    pub fn idea_light() -> Self {
324        let bg = Color::from_rgb8(255, 255, 255); // #FFFFFF
325        let fg = Color::from_rgb8(31, 31, 31); // #1F1F1F
326        let primary = Color::from_rgb8(53, 116, 240); // #3574F0
327        let accent = Color::from_rgb8(232, 163, 61); // #E8A33D
328        let surface = Color::from_rgb8(247, 248, 250); // #F7F8FA 面板底
329        let error = Color::from_rgb8(229, 87, 101); // #E55765
330        let border = Color::from_rgb8(201, 204, 214); // #C9CCD6
331        let caption = Color::from_rgb8(140, 140, 140); // #8C8C8C
332        let text = TextTheme {
333            headline: TextStyleTheme { font_size: 20.0, color: fg },
334            title: TextStyleTheme { font_size: 15.0, color: fg },
335            body: TextStyleTheme { font_size: 13.0, color: fg },
336            caption: TextStyleTheme { font_size: 12.0, color: caption },
337        };
338        let button = ButtonStyle {
339            background: primary,
340            foreground: Color::WHITE,
341            radius: 4.0,
342            focus_ring_color: primary,
343            focus_ring_width: 2.0,
344        };
345        let scrollbar = ScrollbarStyle {
346            thumb_color: Color::rgba(0.5, 0.55, 0.65, 0.55),
347            thumb_hover_color: Color::rgba(0.35, 0.40, 0.50, 0.80),
348            thumb_radius: 4.0,
349            thumb_width: 8.0,
350            hit_width: 10.0,
351            thumb_min_size: 24.0,
352            thumb_track_ratio: 0.32,
353        };
354        let input = InputStyle {
355            background: Color::WHITE,
356            border,
357            focused_border: primary,
358            text_color: fg,
359            placeholder_color: Color::from_rgb8(154, 160, 166), // #9AA0A6
360            radius: 4.0,
361        };
362        let tooltip = TooltipStyle { background: Color::from_rgb8(250, 251, 252), foreground: fg, border, radius: 4.0 };
363        let menu = MenuStyle {
364            background: Color::WHITE,
365            foreground: fg,
366            hover_background: Color::from_rgb8(235, 239, 245), // #EBEFF5
367            border,
368            radius: 6.0,
369        };
370        let tab = TabStyle {
371            background: bg,
372            active_foreground: fg,
373            inactive_foreground: caption,
374            hover_background: Color::from_rgb8(240, 242, 246), // #F0F2F6
375            indicator_color: primary,
376        };
377        let nav = NavStyle {
378            active_background: Color::rgba(0.21, 0.46, 0.94, 0.12),
379            active_foreground: primary,
380            foreground: fg,
381            hover_background: Color::from_rgb8(240, 242, 246),
382            indicator_color: primary,
383        };
384        let feedback = FeedbackStyle {
385            progress_track: Color::rgba(0.0, 0.0, 0.0, 0.10),
386            progress_value: primary,
387            success: Color::from_rgb8(54, 150, 86),
388            warning: Color::from_rgb8(237, 162, 0), // #EDA200
389        };
390        let dropdown = DropdownStyle {
391            background: Color::WHITE,
392            foreground: fg,
393            placeholder: Color::from_rgb8(154, 160, 166), // #9AA0A6
394            border,
395            open_border: primary,
396            hover: Color::from_rgb8(235, 239, 245), // #EBEFF5
397            selected_background: Color::rgba(0.21, 0.46, 0.94, 0.12),
398            disabled: Color::rgba(0.0, 0.0, 0.0, 0.35),
399        };
400        let dialog = DialogStyle { barrier: Color::rgba(0.0, 0.0, 0.0, 0.45), background: Color::WHITE, radius: 8.0 };
401        let list = ListStyle {
402            hover_background: Color::rgba(0.0, 0.0, 0.0, 0.04),
403            selected_background: Color::rgba(0.21, 0.46, 0.94, 0.12),
404            foreground: fg,
405        };
406        Self {
407            background: bg,
408            foreground: fg,
409            primary,
410            accent,
411            surface,
412            error,
413            border,
414            divider: Color::from_rgb8(213, 216, 222), // #D5D8DE — 在 #FFFFFF 上清晰可辨
415            hover: Color::rgba(0.0, 0.0, 0.0, 0.05),
416            disabled: Color::rgba(0.0, 0.0, 0.0, 0.35),
417            selection: Color::rgba(0.21, 0.46, 0.94, 0.18),
418            icon: fg,
419            radius_sm: 2.0,
420            radius_md: 4.0,
421            radius_lg: 8.0,
422            spacing: 8.0,
423            text,
424            button,
425            scrollbar,
426            input,
427            tooltip,
428            menu,
429            tab,
430            nav,
431            feedback,
432            dropdown,
433            dialog,
434            list,
435        }
436    }
437
438    /// 深色主题 — IDEA New UI 风格(`idea_dark()` 别名)。
439    pub fn dark() -> Self {
440        Self::idea_dark()
441    }
442
443    /// 浅色主题 — IDEA New UI 风格(`idea_light()` 别名)。
444    pub fn light() -> Self {
445        Self::idea_light()
446    }
447}
448
449// =================================================================
450// Direction — 文本方向(Ltr / Rtl)
451// =================================================================
452
453#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
454pub enum Direction {
455    #[default]
456    Ltr,
457    Rtl,
458}
459
460// =================================================================
461// ThemeWidget + InheritedWidget impl
462// =================================================================
463
464/// 用户显式颜色优先,否则回退到主题/token 值。
465///
466/// P1-8:用 `Option` 表达"未覆盖",不再依赖与默认色相等的 sentinel 判断
467/// (用户显式选择与哨兵相同的颜色时也能正确覆盖)。
468pub const fn resolve_color(explicit: Option<Color>, themed: Color) -> Color {
469    match explicit {
470        Some(color) => color,
471        None => themed,
472    }
473}
474
475/// 数值版 `resolve_color`:显式尺寸/宽度优先,否则用主题/回退值。
476pub const fn resolve_f32(explicit: Option<f32>, themed: f32) -> f32 {
477    match explicit {
478        Some(value) => value,
479        None => themed,
480    }
481}
482
483/// Theme 提供者 widget。挂到树中,所有后代可通过 `ctx.theme()` 访问。
484///
485/// `theme` 用 `Rc` 共享:State 缓存主题时只 clone 引用,不再复制整份 ThemeData。
486#[derive(Debug)]
487pub struct ThemeWidget {
488    pub theme: Rc<ThemeData>,
489    pub direction: Direction,
490    pub child: Option<WidgetNode>,
491}
492
493impl ThemeWidget {
494    pub fn new(theme: ThemeData) -> Self {
495        Self::from_rc(Rc::new(theme))
496    }
497
498    pub fn from_rc(theme: Rc<ThemeData>) -> Self {
499        Self { theme, direction: Direction::Ltr, child: None }
500    }
501
502    pub fn dark() -> Self {
503        Self::new(ThemeData::dark())
504    }
505
506    pub fn light() -> Self {
507        Self::new(ThemeData::light())
508    }
509
510    pub fn with_direction(mut self, d: Direction) -> Self {
511        self.direction = d;
512        self
513    }
514
515    pub fn child(mut self, c: impl Widget) -> Self {
516        self.child = Some(WidgetNode::new(c));
517        self
518    }
519
520    pub fn child_node(mut self, c: WidgetNode) -> Self {
521        self.child = Some(c);
522        self
523    }
524}
525
526impl InheritedWidget for ThemeWidget {
527    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
528        // downcast old 到 ThemeWidget 比较 theme + direction
529        if let Some(old_theme) = old.as_any().downcast_ref::<ThemeWidget>() {
530            if Rc::ptr_eq(&self.theme, &old_theme.theme) {
531                return self.direction != old_theme.direction;
532            }
533            *self.theme != *old_theme.theme || self.direction != old_theme.direction
534        } else {
535            true
536        }
537    }
538
539    fn as_any(&self) -> &dyn Any {
540        self
541    }
542}
543
544impl ThemeWidget {
545    pub fn theme(&self) -> &ThemeData {
546        &self.theme
547    }
548
549    pub fn direction(&self) -> Direction {
550        self.direction
551    }
552}
553
554impl Widget for ThemeWidget {
555    fn as_any(&self) -> &dyn Any {
556        self
557    }
558
559    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
560        Some(self)
561    }
562
563    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
564        // 透传 child RO,但必须**包一层 ProxyRenderObject**:
565        // 直接把 child widget 的 RO 树当自己的 RO,会让 element 树(1 个 child)
566        // 与 RO 树(child 的整棵子树)不同构;propagate 只能按索引替换前 N 个 slot,
567        // 其余 slot 成为陈旧副本(Theme 根节点会重复绘制 nested boundary)。
568        match &self.child {
569            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
570            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
571        }
572    }
573
574    fn children(&self) -> Vec<WidgetNode> {
575        self.child.clone().into_iter().collect()
576    }
577
578    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
579        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
580    }
581}
582
583// =================================================================
584// DirectionWidget — 单独暴露 direction(如果只想用 Direction 不想用 Theme)
585// =================================================================
586
587/// 单独的 Direction 提供者,方便只想换方向不换主题的场景。
588#[derive(Debug)]
589pub struct DirectionWidget {
590    pub direction: Direction,
591    pub child: Option<WidgetNode>,
592}
593
594impl DirectionWidget {
595    pub fn new(d: Direction) -> Self {
596        Self { direction: d, child: None }
597    }
598
599    pub fn child(mut self, c: impl Widget) -> Self {
600        self.child = Some(WidgetNode::new(c));
601        self
602    }
603}
604
605impl InheritedWidget for DirectionWidget {
606    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
607        if let Some(old_dir) = old.as_any().downcast_ref::<DirectionWidget>() {
608            self.direction != old_dir.direction
609        } else {
610            true
611        }
612    }
613
614    fn as_any(&self) -> &dyn Any {
615        self
616    }
617}
618
619impl DirectionWidget {
620    pub fn direction(&self) -> Direction {
621        self.direction
622    }
623}
624
625impl Widget for DirectionWidget {
626    fn as_any(&self) -> &dyn Any {
627        self
628    }
629
630    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
631        Some(self)
632    }
633
634    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
635        // 与 ThemeWidget 相同:透传 child 必须包 Proxy,保证 element/RO 同构。
636        match &self.child {
637            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
638            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
639        }
640    }
641
642    fn children(&self) -> Vec<WidgetNode> {
643        self.child.clone().into_iter().collect()
644    }
645
646    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
647        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
648    }
649}