rust_constructor/lib.rs
1//! # Rust Constructor V2
2//!
3//! A cross-platform `GUI` framework built on `egui`, the simplest way to develop `GUI` projects with `Rust`
4//!
5//! 基于`egui`构建的跨平台`GUI`框架, 用`Rust`开发`GUI`项目最简单的方式
6//!
7//! ## Overview 概述
8//!
9//! `Rust Constructor` is a fully functional GUI framework that leverages the power of `egui` to provide
10//! a simple and intuitive instrument for building cross-platform applications.
11//!
12//! `Rust Constructor`是一个功能全面的GUI框架,它利用了`egui`的强大功能,为构建跨平台应用程序提供了一个简单直观的工具。
13//!
14//! ## Quick Start 快速入门
15//!
16//! ```rust
17//! pub struct RcApp {
18//! pub inner: rust_constructor::app::App,
19//! }
20//!
21//! impl eframe::App for RcApp {
22//! fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
23//! egui::CentralPanel::default().show(ctx, |ui| {
24//! ui.label("Hello world");
25//! });
26//! }
27//! }
28//!
29//!
30//! eframe::run_native(
31//! "Example App",
32//! eframe::NativeOptions::default(),
33//! Box::new(|_| {
34//! Ok(Box::new(RcApp {
35//! inner: rust_constructor::app::App::default(),
36//! }))
37//! }),
38//! )
39//! .unwrap();
40//! ```
41//!
42//! ## Documentation 文档
43//!
44//! - [Rust Constructor Guide](https://github.com/ChepleBob30/Rust-Constructor-Guide)
45//! - [GitHub Repository](https://github.com/ChepleBob30/Rust-Constructor)
46//! - [Binder 必达](https://github.com/Binder-organize) - Other projects from our organization 我们组织的其他项目
47pub mod advance_front;
48pub mod app;
49pub mod background;
50pub mod basic_front;
51use std::{
52 any::Any,
53 error::Error,
54 fmt::{Debug, Display, Formatter},
55 time::Instant,
56 vec::Vec,
57};
58
59/// Core trait for managing Rust Constructor resources uniformly.
60///
61/// 统一管理Rust Constructor资源的核心特性。
62///
63/// This trait provides a common interface for all GUI resources in the framework,
64/// allowing for the acquisition and modification of specific resources and their details.
65///
66/// 此特征为框架中的所有GUI资源提供了一个公共接口,允许获取具体资源及其细节并对其进行修改。
67pub trait RustConstructorResource: Debug {
68 /// Returns a reference to the resource as `Any` for extract the specific type.
69 ///
70 /// 以`Any`返回对资源的引用,用于取出具体类型。
71 ///
72 /// This allows downcasting to the concrete type when the actual type is known.
73 ///
74 /// 当实际类型已知时,允许向下转换到具体类型。
75 fn as_any(&self) -> &dyn Any;
76
77 /// Returns a mutable reference to the resource as `Any` for extract the specific type.
78 ///
79 /// 以`Any`返回对资源的可变引用,用于取出具体类型。
80 ///
81 /// This allows mutable downcasting when the actual type is known.
82 ///
83 /// 当实际类型已知时,允许向下可变转换到具体类型。
84 fn as_any_mut(&mut self) -> &mut dyn Any;
85
86 /// Retrieves the display info field for this resource.
87 ///
88 /// 取出此资源的显示信息字段。
89 ///
90 /// Returns `Some(DisplayInfo)` if the resource has display info field,
91 /// or `None` if it doesn't have display info field.
92 ///
93 /// 如果资源具有显示信息字段则返回`Some(DisplayInfo)`,如果资源没有显示信息字段则返回`None`。
94 fn display_display_info(&self) -> Option<DisplayInfo>;
95
96 /// Updates the display info field for this resource.
97 ///
98 /// 更新此资源的显示信息字段。
99 fn modify_display_info(&mut self, display_info: DisplayInfo);
100
101 /// Returns all tags associated with this resource.
102 ///
103 /// 返回与此资源关联的所有标签。
104 ///
105 /// Tags are stored as key-value pairs (`[String; 2]`) and can be used
106 /// for categorization, filtering, or metadata storage.
107 ///
108 /// 标签以键值对(`[String; 2]`)的形式存储,可用于分类、过滤或元数据存储。
109 fn display_tags(&self) -> Vec<[String; 2]>;
110
111 /// Updates the tags for this resource.
112 ///
113 /// 更新此资源的标签。
114 ///
115 /// # Arguments
116 ///
117 /// * `replace` - If `true`, replaces all existing tags;
118 /// if `false`, merges with existing tags.
119 ///
120 /// # 参数
121 ///
122 /// * `replace` - 若为`true`,则替换所有现有的标签;
123 /// 若为`false`,则与现有标签合并。
124 fn modify_tags(&mut self, tags: &[[String; 2]], replace: bool);
125}
126
127/// Trait for managing basic front resources that are displayed to the user.
128///
129/// 用于管理显示给用户的基本前端资源的特征。
130///
131/// This trait extends `RustConstructorResource` with additional methods specific
132/// to visual elements.
133///
134/// 此特征扩展了`RustConstructorResource`,添加了特定视觉元素的方法。
135pub trait BasicFrontResource: RustConstructorResource {
136 /// Returns the complete basic resource config.
137 ///
138 /// 返回完整的基本前端资源配置。
139 ///
140 /// This includes both position/size config and clipping information.
141 ///
142 /// 包括位置/大小配置和裁剪信息。
143 fn display_basic_front_resource_config(&self) -> BasicFrontResourceConfig;
144
145 /// Returns the position and size config for this resource.
146 ///
147 /// 返回此资源的位置和大小配置。
148 ///
149 /// Includes grid-based positioning, alignment settings, and offset values.
150 ///
151 /// 包括基于网格的定位、对齐设置和偏移值。
152 fn display_position_size_config(&self) -> PositionSizeConfig;
153
154 /// Returns the clipping rectangle config if this resource has one.
155 ///
156 /// 返回裁剪矩形配置(如果此资源有的话)。
157 ///
158 /// Clipping rectangles define the visible area of the resource.
159 ///
160 /// 裁剪矩形定义资源的可见区域。
161 ///
162 /// Returns `None` if no clipping is applied.
163 ///
164 /// 如果没有应用裁剪矩形,则返回`None`。
165 fn display_clip_rect(&self) -> Option<PositionSizeConfig>;
166
167 /// Returns the current display position of the resource.
168 ///
169 /// 返回资源的当前显示位置。
170 ///
171 /// The position is returned as `[x, y]` coordinates.
172 ///
173 /// 位置以`[x, y]`坐标返回。
174 fn display_position(&self) -> [f32; 2];
175
176 /// Returns the current display size of the resource.
177 ///
178 /// 返回资源的当前显示大小。
179 ///
180 /// The size is returned as `[width, height]`.
181 ///
182 /// 大小以`[width, height]`返回。
183 fn display_size(&self) -> [f32; 2];
184
185 /// Updates the complete basic resource config.
186 ///
187 /// 更新完整的前端资源配置。
188 fn modify_basic_front_resource_config(
189 &mut self,
190 basic_front_resource_config: BasicFrontResourceConfig,
191 );
192
193 /// Updates the position and size config.
194 ///
195 /// 更新位置和大小配置。
196 fn modify_position_size_config(&mut self, position_size_config: PositionSizeConfig);
197
198 /// Updates the clipping rectangle config.
199 ///
200 /// 更新裁剪矩形配置。
201 fn modify_clip_rect(&mut self, clip_rect: Option<PositionSizeConfig>);
202}
203
204/// Unique identifier for Rust Constructor resources.
205///
206/// Rust Constructor资源的唯一标识符。
207///
208/// This struct combines a resource name and type to create a unique identifier
209/// that can be used to reference resources throughout the application.
210///
211/// 这个结构体结合了资源名称和类型来创建一个唯一的标识符,可以在整个应用程序中用来引用资源。
212#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
213pub struct RustConstructorId {
214 /// Unique name identifying the resource instance, Resources of different
215 /// types can have the same name.
216 ///
217 /// 标识资源实例的唯一名称,不同类型的资源可以重名。
218 pub name: String,
219
220 /// Type of the resource (e.g., `Image`).
221 ///
222 /// 资源的类型(例如`Image`)。
223 pub discern_type: String,
224}
225
226/// Container for Rust Constructor resources with type-erased storage.
227///
228/// 具有类型擦除存储的Rust Constructor资源的容器。
229///
230/// This struct pairs a resource identifier with the actual resource content,
231/// allowing for heterogeneous storage of different resource types while
232/// maintaining the ability to identify and manage them individually.
233///
234/// 这个结构体将资源标识符与实际资源内容配对,允许不同资源类型的异构存储,同时保持单独识别和管理它们的能力。
235///
236/// # Type Erasure 类型擦除
237///
238/// The `content` field uses a `Box<dyn RustConstructorResource>` to store
239/// any type that implements the `RustConstructorResource` trait, enabling
240/// polymorphic behavior and storage.
241///
242/// `content`字段使用`Box<dyn RustConstructorResource>`来存储任何实现`RustConstructorResource`
243/// 特征的类型,从而启用多态行为和存储。
244#[derive(Debug)]
245pub struct RustConstructorResourceBox {
246 /// Unique identifier for the contained resource.
247 ///
248 /// 所包含资源的唯一标识符。
249 pub id: RustConstructorId,
250
251 /// Type-erased resource content.
252 ///
253 /// 类型擦除的资源内容。
254 pub content: Box<dyn RustConstructorResource>,
255}
256
257impl RustConstructorResourceBox {
258 pub fn new(name: &str, discern_type: &str, content: Box<dyn RustConstructorResource>) -> Self {
259 Self {
260 id: RustConstructorId {
261 name: name.to_string(),
262 discern_type: discern_type.to_string(),
263 },
264 content,
265 }
266 }
267}
268
269/// Config for basic front resources.
270///
271/// 基本前端资源的配置。
272///
273/// This struct contains all the essential config needed for positioning,
274/// sizing, and clipping visual elements in the GUI.
275///
276/// 这个结构体包含了在GUI中定位、调整大小和裁剪可视元素所需的所有配置。
277#[derive(Debug, Default, Clone, PartialEq, PartialOrd)]
278pub struct BasicFrontResourceConfig {
279 /// Config for position, size, and layout properties.
280 ///
281 /// 位置、大小和布局属性的配置。
282 pub position_size_config: PositionSizeConfig,
283
284 /// Optional clipping rectangle that defines the visible area.
285 /// If `None`, the resource is rendered without clipping.
286 ///
287 /// 可选的裁剪矩形,用于定义可见区域。如果为`None`,则渲染资源时不进行裁剪。
288 pub clip_rect: Option<PositionSizeConfig>,
289}
290
291impl BasicFrontResourceConfig {
292 #[inline]
293 pub fn position_size_config(mut self, position_size_config: PositionSizeConfig) -> Self {
294 self.position_size_config = position_size_config;
295 self
296 }
297
298 #[inline]
299 pub fn clip_rect(mut self, clip_rect: Option<PositionSizeConfig>) -> Self {
300 self.clip_rect = clip_rect;
301 self
302 }
303}
304
305/// Config for positioning and sizing resources in a flexible grid system.
306///
307/// 用于在灵活的网格系统中定位和调整资源大小的配置。
308///
309/// This struct provides comprehensive control over how resources are positioned
310/// and sized within the GUI, supporting grid-based layouts with multiple alignment options.
311///
312/// 这个结构体提供了对GUI中资源如何定位和大小的全面控制,支持具有多种对齐选项的基于网格的布局。
313///
314/// # Grid System 网格系统
315///
316/// The grid system allows for relative positioning and sizing using fractions of
317/// the available space, making layouts responsive and adaptable to different screen sizes.
318///
319/// 网格系统允许使用可用空间的一部分进行相对定位和大小调整,使布局响应并适应不同的屏幕尺寸。
320#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
321pub struct PositionSizeConfig {
322 /// Absolute position coordinates in pixels (`[x, y]`).
323 ///
324 /// 以像素为单位的绝对位置坐标(`[x, y]`)。
325 pub origin_position: [f32; 2],
326
327 /// Absolute size dimensions in pixels (`[width, height]`).
328 ///
329 /// 以像素为单位的绝对尺寸(`[width, height]`)。
330 pub origin_size: [f32; 2],
331
332 /// Grid-based X-axis positioning (`[numerator, denominator]`).
333 ///
334 /// 基于网格的x轴定位(`[numerator, denominator]`)。
335 ///
336 /// Position = (total_width * numerator / denominator)
337 ///
338 /// 位置 = (总宽度 * 分子 / 分母)
339 pub x_location_grid: [f32; 2],
340
341 /// Grid-based Y-axis positioning (`[numerator, denominator]`).
342 ///
343 /// 基于网格的y轴定位(`[numerator, denominator]`)。
344 ///
345 /// Position = (total_height * numerator / denominator)
346 ///
347 /// 位置 = (总高度 * 分子 / 分母)
348 pub y_location_grid: [f32; 2],
349
350 /// Grid-based X-axis sizing (`[numerator, denominator]`).
351 ///
352 /// 基于网格的x轴缩放(`[numerator, denominator]`)。
353 ///
354 /// Width = (total_width * numerator / denominator)
355 ///
356 /// 宽度 = (总宽度 * 分子 / 分母)
357 pub x_size_grid: [f32; 2],
358
359 /// Grid-based Y-axis sizing (`[numerator, denominator]`).
360 ///
361 /// 基于网格的y轴缩放(`[numerator, denominator]`)。
362 ///
363 /// Height = (total_height * numerator / denominator)
364 ///
365 /// 高度 = (总高度 * 分子 / 分母)
366 pub y_size_grid: [f32; 2],
367
368 /// Horizontal and vertical alignment methods.
369 ///
370 /// 水平和垂直对齐方法。
371 pub display_method: (HorizontalAlign, VerticalAlign),
372
373 /// Additional offset in pixels (`[x_offset, y_offset]`).
374 ///
375 /// 额外的像素偏移量(`[x_offset, y_offset]`)。
376 pub offset: [f32; 2],
377}
378
379impl Default for PositionSizeConfig {
380 fn default() -> Self {
381 PositionSizeConfig {
382 origin_position: [0_f32, 0_f32],
383 origin_size: [0_f32, 0_f32],
384 x_location_grid: [0_f32, 0_f32],
385 y_location_grid: [0_f32, 0_f32],
386 x_size_grid: [0_f32, 0_f32],
387 y_size_grid: [0_f32, 0_f32],
388 display_method: (HorizontalAlign::default(), VerticalAlign::default()),
389 offset: [0_f32, 0_f32],
390 }
391 }
392}
393
394impl PositionSizeConfig {
395 #[inline]
396 pub fn origin_position(mut self, x: f32, y: f32) -> Self {
397 self.origin_position = [x, y];
398 self
399 }
400
401 #[inline]
402 pub fn origin_size(mut self, width: f32, height: f32) -> Self {
403 self.origin_size = [width, height];
404 self
405 }
406
407 #[inline]
408 pub fn x_size_grid(mut self, fetch: f32, total: f32) -> Self {
409 self.x_size_grid = [fetch, total];
410 self
411 }
412
413 #[inline]
414 pub fn y_size_grid(mut self, fetch: f32, total: f32) -> Self {
415 self.y_size_grid = [fetch, total];
416 self
417 }
418
419 #[inline]
420 pub fn x_location_grid(mut self, fetch: f32, total: f32) -> Self {
421 self.x_location_grid = [fetch, total];
422 self
423 }
424
425 #[inline]
426 pub fn y_location_grid(mut self, fetch: f32, total: f32) -> Self {
427 self.y_location_grid = [fetch, total];
428 self
429 }
430
431 #[inline]
432 pub fn display_method(
433 mut self,
434 horizontal_align: HorizontalAlign,
435 vertical_align: VerticalAlign,
436 ) -> Self {
437 self.display_method = (horizontal_align, vertical_align);
438 self
439 }
440
441 #[inline]
442 pub fn offset(mut self, x: f32, y: f32) -> Self {
443 self.offset = [x, y];
444 self
445 }
446}
447
448/// Timer for tracking application and page runtimes.
449///
450/// 用于跟踪应用程序和页面运行时间的计时器。
451#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
452pub struct Timer {
453 /// Time when the current page was entered, in seconds.
454 ///
455 /// 进入当前页面的时间(秒)。
456 pub start_time: f32,
457
458 /// Total runtime of the application since start, in seconds.
459 ///
460 /// 应用程序自启动以来的总运行时间(秒)。
461 pub total_time: f32,
462
463 /// Core timer instance for precise timing.
464 ///
465 /// 用于精确计时的核心计时器实例。
466 pub timer: Instant,
467
468 /// Runtime of the current page, in seconds.
469 ///
470 /// 当前页面的运行时间(秒)。
471 pub now_time: f32,
472}
473
474impl Default for Timer {
475 fn default() -> Self {
476 Timer {
477 start_time: 0_f32,
478 total_time: 0_f32,
479 timer: Instant::now(),
480 now_time: 0_f32,
481 }
482 }
483}
484
485/// Error type for Rust Constructor framework.
486///
487/// Rust Constructor框架的错误类型。
488#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
489pub struct RustConstructorError {
490 /// Identifier for the error type.
491 ///
492 /// 错误类型的标识符。
493 pub error_id: String,
494
495 /// Description of the error.
496 ///
497 /// 对此错误的描述。
498 pub description: String,
499}
500
501impl Display for RustConstructorError {
502 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
503 Debug::fmt(self, f)
504 }
505}
506
507impl Error for RustConstructorError {}
508
509/// Horizontal alignment options for UI elements.
510///
511/// UI元素的水平对齐选项。
512#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
513pub enum HorizontalAlign {
514 /// Align to the left.
515 ///
516 /// 左对齐。
517 #[default]
518 Left,
519 /// Center align horizontally.
520 ///
521 /// 居中对齐。
522 Center,
523 /// Align to the right.
524 ///
525 /// 右对齐。
526 Right,
527}
528
529/// Vertical alignment options for UI elements.
530///
531/// UI元素的垂直对齐选项。
532#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
533pub enum VerticalAlign {
534 /// Align to the top.
535 ///
536 /// 顶部对齐。
537 #[default]
538 Top,
539 /// Center align vertically.
540 ///
541 /// 居中对齐。
542 Center,
543 /// Align to the bottom.
544 ///
545 /// 底部对齐。
546 Bottom,
547}
548
549/// Defines the placement of borders relative to the element's bounds.
550///
551/// 定义边框相对于元素边界的放置方式。
552#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
553pub enum BorderKind {
554 /// Border is drawn inside the element's bounds, reducing the content area.
555 ///
556 /// 边框在元素边界内部绘制,减少内容区域。
557 #[default]
558 Inside,
559 /// Border is centered on the element's bounds, half inside and half outside.
560 ///
561 /// 边框以元素边界为中心,一半在内部一半在外部。
562 Middle,
563 /// Border is drawn outside the element's bounds, preserving the content area.
564 ///
565 /// 边框在元素边界外部绘制,保持内容区域不变。
566 Outside,
567}
568
569/// Config for rendering.
570///
571/// 渲染的配置。
572#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
573pub enum RenderConfig {
574 /// Line with width and color.
575 ///
576 /// 线段,包含宽度和颜色。
577 Line(f32, [u8; 4]),
578 /// Rectangle with corner radius, fill color, border color, border width, and border kind.
579 ///
580 /// 矩形,包含圆角半径,填充颜色,边框颜色,边框宽度,边框类型。
581 Rect([u8; 4], [u8; 4], [u8; 4], f32, BorderKind),
582}
583
584/// Display config for resources, controlling visibility and rendering behavior.
585///
586/// 资源的显示配置,控制可见性和渲染行为。
587#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
588pub struct DisplayInfo {
589 /// Enables or disables the resource. If false, the resource is not processed.
590 ///
591 /// 启用或禁用资源。如果为false,资源不会被处理。
592 pub enable: bool,
593
594 /// Hides the resource visually but keeps it active for event handling.
595 ///
596 /// 隐藏资源视觉显示但保持其事件处理活性。
597 pub hidden: bool,
598
599 /// If true, the resource ignores the rendering layer and does not occupy the mouse focus.
600 ///
601 /// 如果为true,资源忽略渲染层,不占用鼠标焦点。
602 pub ignore_render_layer: bool,
603}
604
605/// The lookup method for requesting resources to skip the rendering queue.
606///
607/// 请求资源跳过渲染队列的查找方法。
608#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
609pub enum RequestMethod {
610 /// Request by resource identifier.
611 ///
612 /// 按资源标识符请求。
613 Id(RustConstructorId),
614 /// Request by resource reference.
615 ///
616 /// 通过资源引用请求。
617 Citer(RustConstructorId),
618}
619
620/// Types of rendering layer requests.
621///
622/// 渲染层请求类型。
623#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
624pub enum RequestType {
625 /// Move resource to the top layer.
626 ///
627 /// 移动资源到顶层。
628 Top,
629 /// Move resource up by specified number of layers.
630 ///
631 /// 按指定层数向上移动资源。
632 Up(usize),
633}
634
635/// Methods for displaying list information.
636///
637/// 用于显示列表信息的方法。
638#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
639pub enum ListInfoMethod {
640 /// Detailed display including resource and ID (with optional formatting).
641 ///
642 /// 详细显示,包括资源和ID(可选格式)。
643 Detailed(bool),
644 /// Simple display showing only resource IDs.
645 ///
646 /// 简单显示,只显示资源ID。
647 #[default]
648 Simple,
649}