rust_constructor/
lib.rs

1//! Rust Constructor v2.0.3
2//! 开发者: Cheple_Bob
3//! 一个强大的跨平台GUI框架,在Rust中开发GUI项目的最简单方法。
4use anyhow::Context;
5use eframe::{emath::Rect, epaint::Stroke, epaint::textures::TextureOptions};
6use egui::{
7    Color32, FontData, FontDefinitions, FontId, Frame, PointerButton, Pos2, Ui, Vec2, text::CCursor,
8};
9use json::JsonValue;
10use kira::{
11    AudioManager, AudioManagerSettings, DefaultBackend, sound::static_sound::StaticSoundData,
12};
13use std::{
14    collections::HashMap,
15    fs::{self, File},
16    io::Read,
17    path::{Path, PathBuf},
18    sync::Arc,
19    time::Instant,
20    vec::Vec,
21};
22use tray_icon::{Icon, TrayIconBuilder, menu::Menu};
23
24/// 从文件中加载图标。
25pub fn load_icon_from_file(path: &str) -> Result<Icon, Box<dyn std::error::Error>> {
26    let image = image::open(path)?.into_rgba8();
27    let (width, height) = image.dimensions();
28    let rgba = image.into_raw();
29    Ok(Icon::from_rgba(rgba, width, height)?)
30}
31
32/// 创建格式化的JSON文件。
33pub fn create_json<P: AsRef<Path>>(path: P, data: JsonValue) -> anyhow::Result<()> {
34    let parent_dir = path
35        .as_ref()
36        .parent()
37        .ok_or_else(|| anyhow::anyhow!("Invalid file path."))?;
38
39    // 创建父目录(如果不存在)。
40    fs::create_dir_all(parent_dir)?;
41
42    // 生成带缩进的JSON字符串(4空格缩进)。
43    let formatted = json::stringify_pretty(data, 4);
44
45    // 写入文件(自动处理换行符)。
46    fs::write(path, formatted)?;
47    Ok(())
48}
49
50/// 复制并重新格式化JSON文件。
51pub fn copy_and_reformat_json<P: AsRef<Path>>(src: P, dest: P) -> anyhow::Result<()> {
52    // 读取原始文件。
53    let content = fs::read_to_string(&src)?;
54
55    // 解析JSON(自动验证格式)。
56    let parsed = json::parse(&content)?;
57
58    // 使用格式化写入新文件。
59    create_json(dest, parsed)?;
60
61    Ok(())
62}
63
64/// 检查文件是否存在。
65pub fn check_file_exists<P: AsRef<Path>>(path: P) -> bool {
66    let path_ref = path.as_ref();
67    if path_ref.exists() {
68        true // 文件已存在时直接返回true。
69    } else {
70        // 文件不存在时,返回false。
71        false
72    }
73}
74
75/// 通用 JSON 写入函数。
76pub fn write_to_json<P: AsRef<Path>>(path: P, data: JsonValue) -> anyhow::Result<()> {
77    let parent_dir = path
78        .as_ref()
79        .parent()
80        .ok_or_else(|| anyhow::anyhow!("Invalid file path."))?;
81
82    fs::create_dir_all(parent_dir)?;
83    let formatted = json::stringify_pretty(data, 4);
84    fs::write(path, formatted)?;
85    Ok(())
86}
87
88/// 通用 JSON 读取函数。
89pub fn read_from_json<P: AsRef<Path>>(path: P) -> anyhow::Result<JsonValue> {
90    let content = fs::read_to_string(&path)
91        .with_context(|| format!("Cannot read the file: {}", path.as_ref().display()))?;
92    json::parse(&content)
93        .with_context(|| format!("Failed to parse JSON: {}", path.as_ref().display()))
94}
95
96/// 播放 WAV 文件。
97pub fn play_wav(path: &str) -> anyhow::Result<f64> {
98    let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
99    let sound_data = StaticSoundData::from_file(path)?;
100    let duration = sound_data.duration().as_secs_f64();
101    manager.play(sound_data)?;
102    std::thread::sleep(std::time::Duration::from_secs_f64(duration));
103    Ok(duration)
104}
105
106/// 通用按键点击反馈函数。
107pub fn general_click_feedback(sound_path: &str) {
108    let sound_path = sound_path.to_string();
109    std::thread::spawn(move || {
110        play_wav(&sound_path).unwrap_or(0_f64);
111    });
112}
113
114/// 检查指定目录下有多少个带有特定名称的文件。
115pub fn count_files_recursive(dir: &Path, target: &str) -> std::io::Result<usize> {
116    let mut count = 0;
117    if dir.is_dir() {
118        for entry in fs::read_dir(dir)? {
119            let entry = entry?;
120            let path = entry.path();
121            if path.is_dir() {
122                count += count_files_recursive(&path, target)?;
123            } else if path.file_name().unwrap().to_string_lossy().contains(target) {
124                count += 1;
125            }
126        }
127    }
128    Ok(count)
129}
130
131/// 检查指定目录下有多少个带有特定名称的文件并返回它们的名称。
132pub fn list_files_recursive(path: &Path, prefix: &str) -> Result<Vec<PathBuf>, std::io::Error> {
133    let mut matches = Vec::new();
134
135    for entry in std::fs::read_dir(path)? {
136        // 遍历目录
137        let entry = entry?;
138        let path = entry.path();
139
140        if path.is_dir() {
141            // 递归处理子目录
142            matches.extend(list_files_recursive(&path, prefix)?);
143        } else if let Some(file_name) = path.file_name() {
144            if file_name.to_string_lossy().contains(prefix) {
145                matches.push(path);
146            }
147        }
148    }
149
150    Ok(matches)
151}
152
153/// 配置文件。
154#[derive(Debug, Clone)]
155pub struct Config {
156    /// 显示的语言(注意:此值修改到大于实际语言数目极有可能导致程序崩溃!)。
157    pub language: u8,
158    /// 总共有多少种语言已被支持(注意:此值修改到大于实际语言数目极有可能导致程序崩溃!)。
159    pub amount_languages: u8,
160    /// 是否启用严格模式:严格模式下,当遇到无法处理的情况时,将直接panic;若未启用严格模式,则会发出一条问题报告来描述情况。
161    pub rc_strict_mode: bool,
162    /// 问题反馈音效(留空即可禁用)。
163    pub problem_report_sound: String,
164}
165
166impl Config {
167    pub fn from_json_value(value: &JsonValue) -> Option<Config> {
168        Some(Config {
169            language: value["language"].as_u8()?,
170            amount_languages: value["amount_languages"].as_u8()?,
171            rc_strict_mode: value["rc_strict_mode"].as_bool()?,
172            problem_report_sound: value["problem_report_sound"].as_str()?.to_string(),
173        })
174    }
175
176    pub fn to_json_value(&self) -> JsonValue {
177        json::object! {
178            language: self.language,
179            amount_languages: self.amount_languages,
180            rc_strict_mode: self.rc_strict_mode,
181        }
182    }
183}
184
185/// 统一的文本调用处。
186#[derive(Debug, Clone)]
187pub struct GameText {
188    pub game_text: HashMap<String, Vec<String>>,
189}
190
191impl GameText {
192    pub fn from_json_value(value: &JsonValue) -> Option<GameText> {
193        // 检查 game_text 字段是否为对象
194        if !value["game_text"].is_object() {
195            return None;
196        }
197
198        // 遍历对象键值对
199        let mut parsed = HashMap::new();
200        for (key, val) in value["game_text"].entries() {
201            if let JsonValue::Array(arr) = val {
202                let str_vec: Vec<String> = arr
203                    .iter()
204                    .filter_map(|v| v.as_str().map(String::from))
205                    .collect();
206                parsed.insert(key.to_string(), str_vec);
207            }
208        }
209
210        Some(GameText { game_text: parsed })
211    }
212}
213
214/// 存储特定值的枚举。
215#[derive(Clone, Debug)]
216pub enum Value {
217    Bool(bool),
218    Int(i32),
219    UInt(u32),
220    Float(f32),
221    Vec(Vec<Value>),
222    String(String),
223}
224
225impl From<bool> for Value {
226    fn from(b: bool) -> Self {
227        Value::Bool(b)
228    }
229}
230
231impl From<i32> for Value {
232    fn from(i: i32) -> Self {
233        Value::Int(i)
234    }
235}
236
237impl From<u32> for Value {
238    fn from(u: u32) -> Self {
239        Value::UInt(u)
240    }
241}
242
243impl From<f32> for Value {
244    fn from(f: f32) -> Self {
245        Value::Float(f)
246    }
247}
248
249impl<T: Into<Value>> From<Vec<T>> for Value {
250    fn from(v: Vec<T>) -> Self {
251        Value::Vec(v.into_iter().map(|x| x.into()).collect())
252    }
253}
254
255impl From<String> for Value {
256    fn from(s: String) -> Self {
257        Value::String(s)
258    }
259}
260
261/// 报告发生问题时的状态。
262#[derive(Clone, Debug)]
263pub struct ReportState {
264    /// 问题发生时所在页面。
265    pub current_page: String,
266    /// 问题发生时程序总运行时间。
267    pub current_total_runtime: f32,
268    /// 问题发生时页面运行时间。
269    pub current_page_runtime: f32,
270}
271
272/// 出现问题时用于存储问题内容、状态及注释的结构体。
273#[derive(Clone, Debug)]
274pub struct Problem {
275    /// 问题严重程度。
276    pub severity_level: SeverityLevel,
277    /// 问题描述。
278    pub problem: String,
279    /// 问题备注。
280    pub annotation: String,
281    /// 问题报告状态。
282    pub report_state: ReportState,
283    /// 问题类型。
284    pub problem_type: RustConstructorError,
285}
286
287/// 衡量问题的严重等级。
288#[derive(Clone, Debug)]
289pub enum SeverityLevel {
290    /// 弱警告:一般情况下不会产生影响。
291    MildWarning,
292    /// 强警告:会影响程序正常执行,但一般情况下不会有严重后果。
293    SevereWarning,
294    /// 错误:会导致程序无法运行。
295    Error,
296}
297
298/// 核心特征,用于统一管理Rust Constructor资源。
299pub trait RustConstructorResource {
300    /// 返回资源名称。
301    fn name(&self) -> &str;
302
303    /// 返回资源类型。
304    fn expose_type(&self) -> &str;
305
306    /// 注册资源。
307    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>);
308
309    /// 匹配资源。
310    fn match_resource(&self, resource_name: &str, resource_type: &str) -> bool {
311        resource_name == self.name() && resource_type == self.expose_type()
312    }
313}
314
315impl RustConstructorResource for PageData {
316    fn name(&self) -> &str {
317        &self.name
318    }
319
320    fn expose_type(&self) -> &str {
321        &self.discern_type
322    }
323
324    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
325        render_list.push(RenderResource {
326            discern_type: self.expose_type().to_string(),
327            name: self.name.to_string(),
328        });
329    }
330}
331
332/// 用于存储页面数据的RC资源。
333#[derive(Clone, Debug)]
334pub struct PageData {
335    pub discern_type: String,
336    pub name: String,
337    /// 是否强制在每帧都刷新页面(使用ctx.request_repaint())。
338    pub forced_update: bool,
339    /// 是否已经加载完首次进入此页面所需内容。
340    pub change_page_updated: bool,
341    /// 是否已经加载完进入此页面所需内容。
342    pub enter_page_updated: bool,
343}
344
345/// 用于存储运行时间的计时器。
346#[derive(Clone, Debug)]
347pub struct Timer {
348    /// 进入页面的时间。
349    pub start_time: f32,
350    /// 程序总运行时间。
351    pub total_time: f32,
352    /// 核心计时器。
353    pub timer: Instant,
354    /// 当前页面运行时间。
355    pub now_time: f32,
356}
357
358impl RustConstructorResource for ImageTexture {
359    fn name(&self) -> &str {
360        &self.name
361    }
362
363    fn expose_type(&self) -> &str {
364        &self.discern_type
365    }
366
367    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
368        render_list.push(RenderResource {
369            discern_type: self.expose_type().to_string(),
370            name: self.name.to_string(),
371        });
372    }
373}
374
375/// 用于存储图片纹理的RC资源。
376#[derive(Clone)]
377pub struct ImageTexture {
378    pub discern_type: String,
379    pub name: String,
380    /// 图片纹理。
381    pub texture: Option<egui::TextureHandle>,
382    /// 图片路径。
383    pub cite_path: String,
384}
385
386impl RustConstructorResource for CustomRect {
387    fn name(&self) -> &str {
388        &self.name
389    }
390
391    fn expose_type(&self) -> &str {
392        &self.discern_type
393    }
394
395    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
396        render_list.push(RenderResource {
397            discern_type: self.expose_type().to_string(),
398            name: self.name.to_string(),
399        });
400    }
401}
402
403/// RC的矩形资源。
404#[derive(Clone, Debug)]
405pub struct CustomRect {
406    pub discern_type: String,
407    pub name: String,
408    /// 位置。
409    pub position: [f32; 2],
410    /// 尺寸。
411    pub size: [f32; 2],
412    /// 圆角。
413    pub rounding: f32,
414    /// x轴的网格式定位:窗口宽 / 第二项 * 第一项 = x轴的原始位置。
415    pub x_grid: [u32; 2],
416    /// y轴的网格式定位:窗口高 / 第二项 * 第一项 = y轴的原始位置。
417    pub y_grid: [u32; 2],
418    /// 对齐方法。
419    pub center_display: [bool; 4],
420    /// 颜色。
421    pub color: [u8; 4],
422    /// 边框宽度。
423    pub border_width: f32,
424    /// 边框颜色。
425    pub border_color: [u8; 4],
426    /// 原始位置。
427    pub origin_position: [f32; 2],
428}
429
430impl RustConstructorResource for Image {
431    fn name(&self) -> &str {
432        &self.name
433    }
434
435    fn expose_type(&self) -> &str {
436        &self.discern_type
437    }
438
439    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
440        render_list.push(RenderResource {
441            discern_type: self.expose_type().to_string(),
442            name: self.name.to_string(),
443        });
444    }
445}
446
447/// RC的图片资源。
448#[derive(Clone)]
449pub struct Image {
450    pub discern_type: String,
451    pub name: String,
452    /// 图片纹理。
453    pub image_texture: Option<egui::TextureHandle>,
454    /// 图片位置。
455    pub image_position: [f32; 2],
456    /// 图片大小。
457    pub image_size: [f32; 2],
458    /// x轴的网格式定位:窗口宽 / 第二项 * 第一项 = x轴的原始位置。
459    pub x_grid: [u32; 2],
460    /// y轴的网格式定位:窗口高 / 第二项 * 第一项 = y轴的原始位置。
461    pub y_grid: [u32; 2],
462    /// 对齐方法。
463    pub center_display: [bool; 4],
464    /// 不透明度。
465    pub alpha: u8,
466    /// 叠加颜色。
467    pub overlay_color: [u8; 4],
468    /// 是否使用叠加颜色。
469    pub use_overlay_color: bool,
470    /// 原始位置。
471    pub origin_position: [f32; 2],
472    /// 引用纹理名。
473    pub cite_texture: String,
474    /// 上一帧引用纹理名。
475    pub last_frame_cite_texture: String,
476}
477
478impl RustConstructorResource for Text {
479    fn name(&self) -> &str {
480        &self.name
481    }
482
483    fn expose_type(&self) -> &str {
484        &self.discern_type
485    }
486
487    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
488        render_list.push(RenderResource {
489            discern_type: self.expose_type().to_string(),
490            name: self.name.to_string(),
491        });
492    }
493}
494
495/// RC的文本资源。
496#[derive(Clone, Debug)]
497pub struct Text {
498    pub discern_type: String,
499    pub name: String,
500    /// 文本内容。
501    pub text_content: String,
502    /// 字号。
503    pub font_size: f32,
504    /// 文本颜色。
505    pub rgba: [u8; 4],
506    /// 文本位置。
507    pub position: [f32; 2],
508    /// 对齐方法。
509    pub center_display: [bool; 4],
510    /// 单行宽度。
511    pub wrap_width: f32,
512    /// 是否有背景。
513    pub write_background: bool,
514    /// 背景颜色。
515    pub background_rgb: [u8; 4],
516    /// 圆角。
517    pub rounding: f32,
518    /// x轴的网格式定位:窗口宽 / 第二项 * 第一项 = x轴的原始位置。
519    pub x_grid: [u32; 2],
520    /// y轴的网格式定位:窗口高 / 第二项 * 第一项 = y轴的原始位置。
521    pub y_grid: [u32; 2],
522    /// 原始位置。
523    pub origin_position: [f32; 2],
524    /// 字体。
525    pub font: String,
526    /// 框选选中的文本。
527    pub selection: Option<(usize, usize)>,
528    /// 是否可框选。
529    pub selectable: bool,
530    /// 超链接文本。
531    pub hyperlink_text: Vec<(usize, usize, String)>,
532}
533
534impl RustConstructorResource for ScrollBackground {
535    fn name(&self) -> &str {
536        &self.name
537    }
538
539    fn expose_type(&self) -> &str {
540        &self.discern_type
541    }
542
543    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
544        render_list.push(RenderResource {
545            discern_type: self.expose_type().to_string(),
546            name: self.name.to_string(),
547        });
548    }
549}
550
551/// RC的滚动背景资源。
552#[derive(Clone, Debug)]
553pub struct ScrollBackground {
554    pub discern_type: String,
555    pub name: String,
556    /// 所有图片名称。
557    pub image_name: Vec<String>,
558    /// true:横向滚动;false:纵向滚动。
559    pub horizontal_or_vertical: bool,
560    /// 横向true:往左;横向false:往右。
561    /// 纵向true:往上;纵向false:往下。
562    pub left_and_top_or_right_and_bottom: bool,
563    /// 滚动速度。
564    pub scroll_speed: u32,
565    /// 边界(到达此处会复位)。
566    pub boundary: f32,
567    /// 恢复点(复位时会回到此处)。
568    pub resume_point: f32,
569}
570
571impl RustConstructorResource for Variable {
572    fn name(&self) -> &str {
573        &self.name
574    }
575
576    fn expose_type(&self) -> &str {
577        &self.discern_type
578    }
579
580    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
581        render_list.push(RenderResource {
582            discern_type: self.expose_type().to_string(),
583            name: self.name.to_string(),
584        });
585    }
586}
587
588/// RC的变量资源。
589#[derive(Clone, Debug)]
590pub struct Variable {
591    pub discern_type: String,
592    pub name: String,
593    /// 变量的值。
594    pub value: Value,
595}
596
597/// RC的字体资源。
598#[derive(Clone, Debug)]
599pub struct Font {
600    pub name: String,
601    pub discern_type: String,
602    /// 字体定义。
603    pub font_definitions: FontDefinitions,
604    /// 字体路径。
605    pub path: String,
606}
607
608impl RustConstructorResource for Font {
609    fn name(&self) -> &str {
610        &self.name
611    }
612
613    fn expose_type(&self) -> &str {
614        &self.discern_type
615    }
616
617    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
618        render_list.push(RenderResource {
619            discern_type: self.expose_type().to_string(),
620            name: self.name.to_string(),
621        });
622    }
623}
624
625impl RustConstructorResource for SplitTime {
626    fn name(&self) -> &str {
627        &self.name
628    }
629
630    fn expose_type(&self) -> &str {
631        &self.discern_type
632    }
633
634    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
635        render_list.push(RenderResource {
636            discern_type: self.expose_type().to_string(),
637            name: self.name.to_string(),
638        });
639    }
640}
641
642/// RC的时间分段资源。
643#[derive(Clone, Debug)]
644pub struct SplitTime {
645    pub discern_type: String,
646    pub name: String,
647    /// 时间点(第一个值为页面运行时间,第二个值为总运行时间)。
648    pub time: [f32; 2],
649}
650
651impl RustConstructorResource for Switch {
652    fn name(&self) -> &str {
653        &self.name
654    }
655
656    fn expose_type(&self) -> &str {
657        &self.discern_type
658    }
659
660    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
661        render_list.push(RenderResource {
662            discern_type: self.expose_type().to_string(),
663            name: self.name.to_string(),
664        });
665    }
666}
667
668/// RC的开关资源。
669#[derive(Clone, Debug)]
670pub struct Switch {
671    pub discern_type: String,
672    pub name: String,
673    /// 外观(包括图片纹理和叠加颜色,数量为开启的动画数量*开关状态总数)。
674    pub appearance: Vec<SwitchData>,
675    /// 开关使用的图片名称。
676    pub switch_image_name: String,
677    /// 是否启用鼠标悬浮和点击时的动画。
678    pub enable_hover_click_image: [bool; 2],
679    /// 开关当前状态。
680    pub state: u32,
681    /// 可以用于点击开关的方法(包含点击方式和是否改变开关状态两个参数)。
682    pub click_method: Vec<SwitchClickAction>,
683    /// 上一次渲染是否有鼠标悬浮。
684    pub last_time_hovered: bool,
685    /// 上一次渲染是否被鼠标点击。
686    pub last_time_clicked: bool,
687    /// 上一次点击对应的点击方法的索引。
688    pub last_time_clicked_index: usize,
689    /// 动画总数。
690    pub animation_count: u32,
691    /// 提示文本资源名。
692    pub hint_text_name: String,
693    /// 开关上的文本资源名称(不需要可留空)。
694    pub text_name: String,
695    /// 开关文本资源的原始位置。
696    pub text_origin_position: [f32; 2],
697    /// 开关点击音效路径。
698    pub sound_path: String,
699}
700
701/// 渲染的RC资源。
702#[derive(Clone, Debug)]
703pub struct RenderResource {
704    pub discern_type: String,
705    pub name: String,
706}
707
708/// 开关的外观。
709#[derive(Clone, Debug)]
710pub struct SwitchData {
711    /// 开关的纹理。
712    pub texture: String,
713    /// 开关的颜色。
714    pub color: [u8; 4],
715    /// 开关上的文本内容。
716    pub text: String,
717    /// 开关上的提示文本。
718    pub hint_text: String,
719}
720
721/// 开关的点击方法。
722#[derive(Clone, Debug)]
723pub struct SwitchClickAction {
724    /// 开关的点击方法。
725    pub click_method: PointerButton,
726    /// 点击后是否改变开关状态。
727    pub action: bool,
728}
729
730/// RC的消息框资源。
731#[derive(Clone, Debug)]
732pub struct MessageBox {
733    pub discern_type: String,
734    pub name: String,
735    /// 消息框大小。
736    pub box_size: [f32; 2],
737    /// 框内内容资源名。
738    pub box_content_name: String,
739    /// 框内标题资源名。
740    pub box_title_name: String,
741    /// 框内图片资源名。
742    pub box_image_name: String,
743    /// 消息框是否持续存在。
744    pub box_keep_existing: bool,
745    /// 如果不持续存在,消息框的持续时间。
746    pub box_existing_time: f32,
747    /// 消息框是否存在(不等于是否显示)。
748    pub box_exist: bool,
749    /// 消息框移动速度。
750    pub box_speed: f32,
751    /// 消息框补位速度。
752    pub box_restore_speed: f32,
753    /// 消息框上一次渲染时的y轴偏移量(用于实现补位动画)。
754    pub box_memory_offset: f32,
755}
756
757impl RustConstructorResource for MessageBox {
758    fn name(&self) -> &str {
759        &self.name
760    }
761
762    fn expose_type(&self) -> &str {
763        &self.discern_type
764    }
765
766    fn reg_render_resource(&self, render_list: &mut Vec<RenderResource>) {
767        render_list.push(RenderResource {
768            discern_type: self.expose_type().to_string(),
769            name: self.name.to_string(),
770        });
771    }
772}
773
774/// 用于将RC资源存储进vec的枚举。
775#[derive(Clone)]
776pub enum RCR {
777    Image(Image),
778    Text(Text),
779    CustomRect(CustomRect),
780    ScrollBackground(ScrollBackground),
781    Variable(Variable),
782    Font(Font),
783    SplitTime(SplitTime),
784    Switch(Switch),
785    MessageBox(MessageBox),
786    ImageTexture(ImageTexture),
787    PageData(PageData),
788}
789
790/// RC资源最基本的错误处理。
791#[derive(Clone, Debug)]
792pub enum RustConstructorError {
793    /// 图片获取失败。
794    ImageGetFailed { image_path: String },
795    /// 图片未找到(需在外部自行调用问题报告)。
796    ImageNotFound { image_name: String },
797    /// 文本未找到(需在外部自行调用问题报告)。
798    TextNotFound { text_name: String },
799    /// 变量未找到(需在外部自行调用问题报告)。
800    VariableNotFound { variable_name: String },
801    /// 变量获取失败。
802    VariableNotInt { variable_name: String },
803    /// 变量获取失败。
804    VariableNotUInt { variable_name: String },
805    /// 变量获取失败。
806    VariableNotFloat { variable_name: String },
807    /// 变量获取失败。
808    VariableNotVec { variable_name: String },
809    /// 变量获取失败。
810    VariableNotBool { variable_name: String },
811    /// 变量获取失败。
812    VariableNotString { variable_name: String },
813    /// 分段时间未找到(需在外部自行调用问题报告)。
814    SplitTimeNotFound { split_time_name: String },
815    /// 开关外观数量不匹配。
816    SwitchAppearanceMismatch { switch_name: String, differ: u32 },
817    /// 开关未找到(需在外部自行调用问题报告)。
818    SwitchNotFound { switch_name: String },
819    /// 消息框已存在。
820    MessageBoxAlreadyExists { message_box_name: String },
821    /// 获取字体失败。
822    FontGetFailed { font_path: String },
823    /// 字体未找到(需在外部自行调用问题报告)。
824    FontNotFound { font_name: String },
825    /// 资源未找到。
826    ResourceNotFound {
827        resource_name: String,
828        resource_type: String,
829    },
830    /// 页面未找到(需在外部自行调用问题报告)。
831    PageNotFound { page_name: String },
832}
833
834/// 程序主体。
835#[derive(Clone)]
836pub struct App {
837    /// 配置项。
838    pub config: Config,
839    /// 文本。
840    pub game_text: GameText,
841    /// RC资源。
842    pub rust_constructor_resource: Vec<RCR>,
843    /// 渲染资源列表。
844    pub render_resource_list: Vec<RenderResource>,
845    /// 问题列表。
846    pub problem_list: Vec<Problem>,
847    /// 窗口样式。
848    pub frame: Frame,
849    /// RC资源刷新率。
850    pub vertrefresh: f32,
851    /// 当前页面。
852    pub page: String,
853    /// 计时器。
854    pub timer: Timer,
855    /// 帧时间。
856    pub frame_times: Vec<f32>,
857    /// 上一帧时间。
858    pub last_frame_time: Option<f64>,
859    /// 托盘图标。
860    pub tray_icon: Option<tray_icon::TrayIcon>,
861    /// 托盘图标是否已创建。
862    pub tray_icon_created: bool,
863}
864
865impl App {
866    /// 初始化程序。
867    pub fn new(config_path: &str, game_text_path: &str) -> Self {
868        let mut config = Config {
869            language: 0,
870            amount_languages: 0,
871            rc_strict_mode: false,
872            problem_report_sound: String::new(),
873        };
874        let mut game_text = GameText {
875            game_text: HashMap::new(),
876        };
877        if let Ok(json_value) = read_from_json(config_path) {
878            if let Some(read_config) = Config::from_json_value(&json_value) {
879                config = read_config;
880            }
881        }
882        if let Ok(json_value) = read_from_json(game_text_path) {
883            if let Some(read_game_text) = GameText::from_json_value(&json_value) {
884                game_text = read_game_text;
885            }
886        }
887        Self {
888            config,
889            game_text,
890            rust_constructor_resource: vec![],
891            render_resource_list: Vec::new(),
892            problem_list: Vec::new(),
893            frame: Frame {
894                ..Default::default()
895            },
896            vertrefresh: 0.01,
897            page: "Launch".to_string(),
898            timer: Timer {
899                start_time: 0.0,
900                total_time: 0.0,
901                timer: Instant::now(),
902                now_time: 0.0,
903            },
904            frame_times: Vec::new(),
905            last_frame_time: None,
906            tray_icon: None,
907            tray_icon_created: false,
908        }
909    }
910
911    /// 运行时添加新页面。
912    pub fn add_page(&mut self, name: &str, forced_update: bool) {
913        self.rust_constructor_resource.push(RCR::PageData(PageData {
914            discern_type: "PageData".to_string(),
915            name: name.to_string(),
916            forced_update,
917            change_page_updated: false,
918            enter_page_updated: false,
919        }));
920    }
921
922    /// 切换页面。
923    pub fn switch_page(&mut self, page: &str) {
924        if let Ok(id) = self.get_resource_index("PageData", page) {
925            self.page = page.to_string();
926            if let RCR::PageData(pd) = &mut self.rust_constructor_resource[id] {
927                pd.enter_page_updated = false;
928                self.timer.start_time = self.timer.total_time;
929                self.update_timer();
930            };
931        };
932    }
933
934    /// 初始化托盘图标。
935    pub fn tray_icon_init(&mut self, icon_path: &str, tooltip: &str, menu: Box<Menu>) {
936        let icon = load_icon_from_file(icon_path).unwrap();
937        if let Ok(tray_icon) = TrayIconBuilder::new()
938            .with_menu(menu)
939            .with_tooltip(tooltip)
940            .with_icon(icon)
941            .with_icon_as_template(true)
942            .build()
943        {
944            self.tray_icon = Some(tray_icon);
945            self.tray_icon_created = true;
946        };
947    }
948
949    /// 检查是否存在特定资源。
950    pub fn check_resource_exists(&mut self, resource_type: &str, resource_name: &str) -> bool {
951        for i in 0..self.rust_constructor_resource.len() {
952            match self.rust_constructor_resource[i].clone() {
953                RCR::Image(im) => {
954                    if im.match_resource(resource_name, resource_type) {
955                        return true;
956                    }
957                }
958                RCR::Text(t) => {
959                    if t.match_resource(resource_name, resource_type) {
960                        return true;
961                    }
962                }
963                RCR::CustomRect(cr) => {
964                    if cr.match_resource(resource_name, resource_type) {
965                        return true;
966                    }
967                }
968                RCR::ScrollBackground(sb) => {
969                    if sb.match_resource(resource_name, resource_type) {
970                        return true;
971                    }
972                }
973                RCR::Variable(v) => {
974                    if v.match_resource(resource_name, resource_type) {
975                        return true;
976                    }
977                }
978                RCR::Font(f) => {
979                    if f.match_resource(resource_name, resource_type) {
980                        return true;
981                    }
982                }
983                RCR::SplitTime(st) => {
984                    if st.match_resource(resource_name, resource_type) {
985                        return true;
986                    }
987                }
988                RCR::Switch(s) => {
989                    if s.match_resource(resource_name, resource_type) {
990                        return true;
991                    }
992                }
993                RCR::MessageBox(mb) => {
994                    if mb.match_resource(resource_name, resource_type) {
995                        return true;
996                    }
997                }
998                RCR::ImageTexture(it) => {
999                    if it.match_resource(resource_name, resource_type) {
1000                        return true;
1001                    }
1002                }
1003                RCR::PageData(pd) => {
1004                    if pd.match_resource(resource_name, resource_type) {
1005                        return true;
1006                    }
1007                }
1008            }
1009        }
1010        false
1011    }
1012
1013    /// 获取资源索引。
1014    pub fn get_resource_index(
1015        &mut self,
1016        resource_type: &str,
1017        resource_name: &str,
1018    ) -> Result<usize, RustConstructorError> {
1019        for i in 0..self.rust_constructor_resource.len() {
1020            match self.rust_constructor_resource[i].clone() {
1021                RCR::Image(im) => {
1022                    if im.match_resource(resource_name, resource_type) {
1023                        return Ok(i);
1024                    }
1025                }
1026                RCR::Text(t) => {
1027                    if t.match_resource(resource_name, resource_type) {
1028                        return Ok(i);
1029                    }
1030                }
1031                RCR::CustomRect(cr) => {
1032                    if cr.match_resource(resource_name, resource_type) {
1033                        return Ok(i);
1034                    }
1035                }
1036                RCR::ScrollBackground(sb) => {
1037                    if sb.match_resource(resource_name, resource_type) {
1038                        return Ok(i);
1039                    }
1040                }
1041                RCR::Variable(v) => {
1042                    if v.match_resource(resource_name, resource_type) {
1043                        return Ok(i);
1044                    }
1045                }
1046                RCR::Font(f) => {
1047                    if f.match_resource(resource_name, resource_type) {
1048                        return Ok(i);
1049                    }
1050                }
1051                RCR::SplitTime(st) => {
1052                    if st.match_resource(resource_name, resource_type) {
1053                        return Ok(i);
1054                    }
1055                }
1056                RCR::Switch(s) => {
1057                    if s.match_resource(resource_name, resource_type) {
1058                        return Ok(i);
1059                    }
1060                }
1061                RCR::MessageBox(mb) => {
1062                    if mb.match_resource(resource_name, resource_type) {
1063                        return Ok(i);
1064                    }
1065                }
1066                RCR::ImageTexture(it) => {
1067                    if it.match_resource(resource_name, resource_type) {
1068                        return Ok(i);
1069                    }
1070                }
1071                RCR::PageData(pd) => {
1072                    if pd.match_resource(resource_name, resource_type) {
1073                        return Ok(i);
1074                    }
1075                }
1076            };
1077        }
1078        self.problem_report(
1079            RustConstructorError::ResourceNotFound {
1080                resource_name: resource_name.to_string(),
1081                resource_type: resource_type.to_string(),
1082            },
1083            SeverityLevel::SevereWarning,
1084        );
1085        Err(RustConstructorError::ResourceNotFound {
1086            resource_name: resource_name.to_string(),
1087            resource_type: resource_type.to_string(),
1088        })
1089    }
1090
1091    /// 添加字体资源。
1092    pub fn add_fonts(&mut self, font_name: &str, font_path: &str) {
1093        let mut fonts = FontDefinitions::default();
1094        if let Ok(font_read_data) = std::fs::read(font_path) {
1095            let font_data: Arc<Vec<u8>> = Arc::new(font_read_data);
1096            fonts.font_data.insert(
1097                font_name.to_owned(),
1098                Arc::new(FontData::from_owned(
1099                    Arc::try_unwrap(font_data).ok().unwrap(),
1100                )),
1101            );
1102
1103            // 将字体添加到字体列表中
1104            fonts
1105                .families
1106                .entry(egui::FontFamily::Proportional)
1107                .or_default()
1108                .insert(0, font_name.to_owned());
1109
1110            fonts
1111                .families
1112                .entry(egui::FontFamily::Monospace)
1113                .or_default()
1114                .insert(0, font_name.to_owned());
1115
1116            self.rust_constructor_resource.push(RCR::Font(Font {
1117                name: font_name.to_string(),
1118                discern_type: "Font".to_string(),
1119                font_definitions: fonts,
1120                path: font_path.to_string(),
1121            }));
1122        } else {
1123            self.problem_report(
1124                RustConstructorError::FontGetFailed {
1125                    font_path: font_path.to_string(),
1126                },
1127                SeverityLevel::SevereWarning,
1128            );
1129        };
1130        // 应用字体定义
1131        // ctx.set_fonts(fonts);
1132    }
1133
1134    /// 输出字体资源。
1135    pub fn font(&mut self, name: &str) -> Result<FontDefinitions, RustConstructorError> {
1136        if let Ok(id) = self.get_resource_index("Font", name) {
1137            if let RCR::Font(f) = &mut self.rust_constructor_resource[id] {
1138                return Ok(f.font_definitions.clone());
1139            }
1140        }
1141        self.problem_report(
1142            RustConstructorError::FontNotFound {
1143                font_name: name.to_string(),
1144            },
1145            SeverityLevel::SevereWarning,
1146        );
1147        Err(RustConstructorError::FontNotFound {
1148            font_name: name.to_string(),
1149        })
1150    }
1151
1152    /// 将所有已添加到RC的字体资源添加到egui中。
1153    pub fn register_all_fonts(&mut self, ctx: &egui::Context) {
1154        let mut font_definitions = egui::FontDefinitions::default();
1155        let mut font_resources = Vec::new();
1156        for i in 0..self.rust_constructor_resource.len() {
1157            if let RCR::Font(f) = &self.rust_constructor_resource[i] {
1158                font_resources.push(f.clone());
1159            };
1160        }
1161        for i in &font_resources {
1162            let font_name = i.name.clone();
1163            // 获取字体数据(返回 FontDefinitions)
1164            if let Ok(font_def) = self.font(&font_name) {
1165                // 从 font_def 中提取对应字体的 Arc<FontData>
1166                if let Some(font_data) = font_def.font_data.get(&font_name) {
1167                    font_definitions
1168                        .font_data
1169                        .insert(font_name.clone(), Arc::clone(font_data));
1170                    font_definitions
1171                        .families
1172                        .entry(egui::FontFamily::Name(font_name.clone().into()))
1173                        .or_default()
1174                        .push(font_name.clone());
1175                };
1176
1177                // 将字体添加到字体列表中
1178                font_definitions
1179                    .families
1180                    .entry(egui::FontFamily::Proportional)
1181                    .or_default()
1182                    .insert(0, font_name.to_owned());
1183
1184                font_definitions
1185                    .families
1186                    .entry(egui::FontFamily::Monospace)
1187                    .or_default()
1188                    .insert(0, font_name.to_owned());
1189            };
1190        }
1191        ctx.set_fonts(font_definitions);
1192    }
1193
1194    /// 发生问题时推送报告。
1195    pub fn problem_report(
1196        &mut self,
1197        problem_type: RustConstructorError,
1198        severity_level: SeverityLevel,
1199    ) {
1200        let (problem, annotation) = match problem_type.clone() {
1201            RustConstructorError::FontGetFailed { font_path } => (
1202                format!("Font get failed: {}", font_path,),
1203                "Please check if the font file exists and the path is correct.",
1204            ),
1205            RustConstructorError::FontNotFound { font_name } => (
1206                format!("Font not found: {}", font_name,),
1207                "Please check whether the font has been added.",
1208            ),
1209            RustConstructorError::ImageGetFailed { image_path } => (
1210                format!("Image get failed: {}", image_path,),
1211                "Please check whether the image path is correct and whether the image has been added.",
1212            ),
1213            RustConstructorError::ImageNotFound { image_name } => (
1214                format!("Image not found: {}", image_name,),
1215                "Please check whether the image has been added.",
1216            ),
1217            RustConstructorError::TextNotFound { text_name } => (
1218                format!("Text not found: {}", text_name,),
1219                "Please check whether the text has been added.",
1220            ),
1221            RustConstructorError::MessageBoxAlreadyExists { message_box_name } => (
1222                format!("Message box already exists: {}", message_box_name),
1223                "Please check whether the code for generating the message box has been accidentally called multiple times.",
1224            ),
1225            RustConstructorError::SplitTimeNotFound { split_time_name } => (
1226                format!("Split time not found: {}", split_time_name,),
1227                "Please check whether the split time has been added.",
1228            ),
1229            RustConstructorError::SwitchAppearanceMismatch {
1230                switch_name,
1231                differ,
1232            } => (
1233                format!(
1234                    "Switch appearance list's number of items is large / small {} more: {}",
1235                    differ, switch_name
1236                ),
1237                "Please check whether the number of appearance list items matches the number of enabled animations.",
1238            ),
1239            RustConstructorError::SwitchNotFound { switch_name } => (
1240                format!("Switch not found: {}", switch_name,),
1241                "Please check whether the switch has been added.",
1242            ),
1243            RustConstructorError::PageNotFound { page_name } => (
1244                format!("Page not found: {}", page_name,),
1245                "Please check whether the page has been added.",
1246            ),
1247            RustConstructorError::VariableNotFound { variable_name } => (
1248                format!("Variable not found: {}", variable_name,),
1249                "Please check whether the variable has been added.",
1250            ),
1251            RustConstructorError::VariableNotBool { variable_name } => (
1252                format!("Variable is not bool: {}", variable_name,),
1253                "Please check whether the variable names and types are correct and whether there are duplicate items.",
1254            ),
1255            RustConstructorError::VariableNotFloat { variable_name } => (
1256                format!("Variable is not f32: {}", variable_name,),
1257                "Please check whether the variable names and types are correct and whether there are duplicate items.",
1258            ),
1259            RustConstructorError::VariableNotInt { variable_name } => (
1260                format!("Variable is not int: {}", variable_name,),
1261                "Please check whether the variable names and types are correct and whether there are duplicate items.",
1262            ),
1263            RustConstructorError::VariableNotString { variable_name } => (
1264                format!("Variable is not string: {}", variable_name,),
1265                "Please check whether the variable names and types are correct and whether there are duplicate items.",
1266            ),
1267            RustConstructorError::VariableNotUInt { variable_name } => (
1268                format!("Variable is not uint: {}", variable_name,),
1269                "Please check whether the variable names and types are correct and whether there are duplicate items.",
1270            ),
1271            RustConstructorError::VariableNotVec { variable_name } => (
1272                format!("Variable is not vec: {}", variable_name,),
1273                "Please check whether the variable names and types are correct and whether there are duplicate items.",
1274            ),
1275            RustConstructorError::ResourceNotFound {
1276                resource_name,
1277                resource_type,
1278            } => (
1279                format!(
1280                    "Resource not found: {}(\"{}\")",
1281                    resource_type, resource_name,
1282                ),
1283                "Please check whether the resource has been added.",
1284            ),
1285        };
1286        // 如果处于严格模式下,则直接崩溃!
1287        if self.config.rc_strict_mode {
1288            panic!("{}", problem);
1289        } else {
1290            eprintln!("something goes wrong.");
1291            let sound = self.config.problem_report_sound.clone();
1292            std::thread::spawn(move || {
1293                play_wav(&sound).unwrap_or(0_f64);
1294            });
1295            self.problem_list.push(Problem {
1296                severity_level,
1297                problem,
1298                annotation: annotation.to_string(),
1299                report_state: ReportState {
1300                    current_page: self.page.clone(),
1301                    current_total_runtime: self.timer.total_time,
1302                    current_page_runtime: self.timer.now_time,
1303                },
1304                problem_type: problem_type.clone(),
1305            });
1306        };
1307    }
1308
1309    /// 检查页面是否已完成首次加载。
1310    pub fn check_updated(&mut self, name: &str) -> Result<bool, RustConstructorError> {
1311        if let Ok(id) = self.get_resource_index("PageData", name) {
1312            if let RCR::PageData(pd) = self.rust_constructor_resource[id].clone() {
1313                if !pd.change_page_updated {
1314                    self.new_page_update(name);
1315                };
1316                return Ok(pd.change_page_updated);
1317            };
1318        };
1319        self.problem_report(
1320            RustConstructorError::PageNotFound {
1321                page_name: name.to_string(),
1322            },
1323            SeverityLevel::SevereWarning,
1324        );
1325        Err(RustConstructorError::PageNotFound {
1326            page_name: name.to_string(),
1327        })
1328    }
1329
1330    /// 检查页面是否已完成加载。
1331    pub fn check_enter_updated(&mut self, name: &str) -> Result<bool, RustConstructorError> {
1332        if let Ok(id) = self.get_resource_index("PageData", name) {
1333            if let RCR::PageData(pd) = &mut self.rust_constructor_resource[id] {
1334                let return_value = pd.enter_page_updated;
1335                pd.enter_page_updated = true;
1336                return Ok(return_value);
1337            };
1338        };
1339        self.problem_report(
1340            RustConstructorError::PageNotFound {
1341                page_name: name.to_string(),
1342            },
1343            SeverityLevel::SevereWarning,
1344        );
1345        Err(RustConstructorError::PageNotFound {
1346            page_name: name.to_string(),
1347        })
1348    }
1349
1350    /// 进入新页面时的更新。
1351    pub fn new_page_update(&mut self, name: &str) {
1352        if let Ok(id) = self.get_resource_index("PageData", name) {
1353            self.timer.start_time = self.timer.total_time;
1354            self.update_timer();
1355            if let RCR::PageData(pd) = &mut self.rust_constructor_resource[id] {
1356                pd.change_page_updated = true;
1357            };
1358        };
1359    }
1360
1361    /// 更新帧数。
1362    pub fn update_frame_stats(&mut self, ctx: &egui::Context) {
1363        let current_time = ctx.input(|i| i.time);
1364        if let Some(last) = self.last_frame_time {
1365            let delta = (current_time - last) as f32;
1366            self.frame_times.push(delta);
1367            const MAX_SAMPLES: usize = 120;
1368            if self.frame_times.len() > MAX_SAMPLES {
1369                let remove_count = self.frame_times.len() - MAX_SAMPLES;
1370                self.frame_times.drain(0..remove_count);
1371            }
1372        }
1373        self.last_frame_time = Some(current_time);
1374    }
1375
1376    /// 更新帧数显示。
1377    pub fn current_fps(&self) -> f32 {
1378        if self.frame_times.is_empty() {
1379            0.0
1380        } else {
1381            1.0 / (self.frame_times.iter().sum::<f32>() / self.frame_times.len() as f32)
1382        }
1383    }
1384
1385    /// 添加分段时间。
1386    pub fn add_split_time(&mut self, name: &str, reset: bool) {
1387        if reset {
1388            if let Ok(id) = self.get_resource_index("SplitTime", name) {
1389                if let RCR::SplitTime(st) = &mut self.rust_constructor_resource[id] {
1390                    st.time = [self.timer.now_time, self.timer.total_time];
1391                };
1392            };
1393        } else {
1394            self.rust_constructor_resource
1395                .push(RCR::SplitTime(SplitTime {
1396                    discern_type: "SplitTime".to_string(),
1397                    name: name.to_string(),
1398                    time: [self.timer.now_time, self.timer.total_time],
1399                }));
1400        };
1401    }
1402
1403    /// 输出分段时间。
1404    pub fn split_time(&mut self, name: &str) -> Result<[f32; 2], RustConstructorError> {
1405        if let Ok(id) = self.get_resource_index("SplitTime", name) {
1406            if let RCR::SplitTime(st) = self.rust_constructor_resource[id].clone() {
1407                return Ok(st.time);
1408            };
1409        };
1410        self.problem_report(
1411            RustConstructorError::SplitTimeNotFound {
1412                split_time_name: name.to_string(),
1413            },
1414            SeverityLevel::SevereWarning,
1415        );
1416        Err(RustConstructorError::SplitTimeNotFound {
1417            split_time_name: name.to_string(),
1418        })
1419    }
1420
1421    /// 更新计时器。
1422    pub fn update_timer(&mut self) {
1423        let elapsed = self.timer.timer.elapsed();
1424        let seconds = elapsed.as_secs();
1425        let milliseconds = elapsed.subsec_millis();
1426        self.timer.total_time = seconds as f32 + milliseconds as f32 / 1000.0;
1427        self.timer.now_time = self.timer.total_time - self.timer.start_time
1428    }
1429
1430    /// 添加矩形资源。
1431    pub fn add_rect(
1432        &mut self,
1433        name: &str,
1434        position_size_and_rounding: [f32; 5],
1435        grid: [u32; 4],
1436        center_display: [bool; 4],
1437        color: [u8; 8],
1438        border_width: f32,
1439    ) {
1440        self.rust_constructor_resource
1441            .push(RCR::CustomRect(CustomRect {
1442                discern_type: "CustomRect".to_string(),
1443                name: name.to_string(),
1444                position: [position_size_and_rounding[0], position_size_and_rounding[1]],
1445                size: [position_size_and_rounding[2], position_size_and_rounding[3]],
1446                rounding: position_size_and_rounding[4],
1447                x_grid: [grid[0], grid[1]],
1448                y_grid: [grid[2], grid[3]],
1449                center_display,
1450                color: [color[0], color[1], color[2], color[3]],
1451                border_width,
1452                border_color: [color[4], color[5], color[6], color[7]],
1453                origin_position: [position_size_and_rounding[0], position_size_and_rounding[1]],
1454            }));
1455    }
1456
1457    /// 显示矩形资源。
1458    pub fn rect(&mut self, ui: &mut Ui, name: &str, ctx: &egui::Context) {
1459        if let Ok(id) = self.get_resource_index("CustomRect", name) {
1460            if let RCR::CustomRect(cr) = &mut self.rust_constructor_resource[id] {
1461                cr.reg_render_resource(&mut self.render_resource_list);
1462                cr.position[0] = match cr.x_grid[1] {
1463                    0 => cr.origin_position[0],
1464                    _ => {
1465                        (ctx.available_rect().width() as f64 / cr.x_grid[1] as f64
1466                            * cr.x_grid[0] as f64) as f32
1467                            + cr.origin_position[0]
1468                    }
1469                };
1470                cr.position[1] = match cr.y_grid[1] {
1471                    0 => cr.origin_position[1],
1472                    _ => {
1473                        (ctx.available_rect().height() as f64 / cr.y_grid[1] as f64
1474                            * cr.y_grid[0] as f64) as f32
1475                            + cr.origin_position[1]
1476                    }
1477                };
1478                let pos_x;
1479                let pos_y;
1480                if cr.center_display[2] {
1481                    pos_x = cr.position[0] - cr.size[0] / 2.0;
1482                } else if cr.center_display[0] {
1483                    pos_x = cr.position[0];
1484                } else {
1485                    pos_x = cr.position[0] - cr.size[0];
1486                };
1487                if cr.center_display[3] {
1488                    pos_y = cr.position[1] - cr.size[1] / 2.0;
1489                } else if cr.center_display[1] {
1490                    pos_y = cr.position[1];
1491                } else {
1492                    pos_y = cr.position[1] - cr.size[1];
1493                };
1494                ui.painter().rect(
1495                    Rect::from_min_max(
1496                        Pos2::new(pos_x, pos_y),
1497                        Pos2::new(pos_x + cr.size[0], pos_y + cr.size[1]),
1498                    ),
1499                    cr.rounding,
1500                    Color32::from_rgba_unmultiplied(
1501                        cr.color[0],
1502                        cr.color[1],
1503                        cr.color[2],
1504                        cr.color[3],
1505                    ),
1506                    Stroke {
1507                        width: cr.border_width,
1508                        color: Color32::from_rgba_unmultiplied(
1509                            cr.border_color[0],
1510                            cr.border_color[1],
1511                            cr.border_color[2],
1512                            cr.border_color[3],
1513                        ),
1514                    },
1515                    egui::StrokeKind::Inside,
1516                );
1517            };
1518        };
1519    }
1520
1521    /// 添加文本资源。
1522    pub fn add_text(
1523        &mut self,
1524        name_content_and_font: [&str; 3],
1525        position_font_size_wrap_width_rounding: [f32; 5],
1526        color: [u8; 8],
1527        center_display_write_background_and_enable_copy: [bool; 6],
1528        grid: [u32; 4],
1529        hyperlink_text: Vec<(usize, usize, &str)>,
1530    ) {
1531        self.rust_constructor_resource.push(RCR::Text(Text {
1532            discern_type: "Text".to_string(),
1533            name: name_content_and_font[0].to_string(),
1534            text_content: name_content_and_font[1].to_string(),
1535            font_size: position_font_size_wrap_width_rounding[2],
1536            rgba: [color[0], color[1], color[2], color[3]],
1537            position: [
1538                position_font_size_wrap_width_rounding[0],
1539                position_font_size_wrap_width_rounding[1],
1540            ],
1541            center_display: [
1542                center_display_write_background_and_enable_copy[0],
1543                center_display_write_background_and_enable_copy[1],
1544                center_display_write_background_and_enable_copy[2],
1545                center_display_write_background_and_enable_copy[3],
1546            ],
1547            wrap_width: position_font_size_wrap_width_rounding[3],
1548            write_background: center_display_write_background_and_enable_copy[4],
1549            background_rgb: [color[4], color[5], color[6], color[7]],
1550            rounding: position_font_size_wrap_width_rounding[4],
1551            x_grid: [grid[0], grid[1]],
1552            y_grid: [grid[2], grid[3]],
1553            origin_position: [
1554                position_font_size_wrap_width_rounding[0],
1555                position_font_size_wrap_width_rounding[1],
1556            ],
1557            font: name_content_and_font[2].to_string(),
1558            selection: None,
1559            selectable: center_display_write_background_and_enable_copy[5],
1560            hyperlink_text: hyperlink_text
1561                .into_iter()
1562                .map(|(a, b, c)| {
1563                    (
1564                        a,
1565                        if b > name_content_and_font[1].len() - 1 {
1566                            name_content_and_font[1].len() - 1
1567                        } else {
1568                            b
1569                        },
1570                        c.to_string(),
1571                    )
1572                })
1573                .collect(),
1574        }));
1575    }
1576
1577    /// 显示文本资源。
1578    pub fn text(&mut self, ui: &mut Ui, name: &str, ctx: &egui::Context) {
1579        if let Ok(id) = self.get_resource_index("Text", name) {
1580            if let RCR::Text(mut t) = self.rust_constructor_resource[id].clone() {
1581                t.reg_render_resource(&mut self.render_resource_list);
1582                // 计算文本大小
1583                let galley = ui.fonts(|f| {
1584                    f.layout(
1585                        t.text_content.to_string(),
1586                        if self.check_resource_exists("Font", &t.font.clone()) {
1587                            FontId::new(t.font_size, egui::FontFamily::Name(t.font.clone().into()))
1588                        } else {
1589                            FontId::proportional(t.font_size)
1590                        },
1591                        Color32::from_rgba_unmultiplied(t.rgba[0], t.rgba[1], t.rgba[2], t.rgba[3]),
1592                        t.wrap_width,
1593                    )
1594                });
1595                let text_size = galley.size();
1596                t.position[0] = match t.x_grid[1] {
1597                    0 => t.origin_position[0],
1598                    _ => {
1599                        (ctx.available_rect().width() as f64 / t.x_grid[1] as f64
1600                            * t.x_grid[0] as f64) as f32
1601                            + t.origin_position[0]
1602                    }
1603                };
1604                t.position[1] = match t.y_grid[1] {
1605                    0 => t.origin_position[1],
1606                    _ => {
1607                        (ctx.available_rect().height() as f64 / t.y_grid[1] as f64
1608                            * t.y_grid[0] as f64) as f32
1609                            + t.origin_position[1]
1610                    }
1611                };
1612                let pos_x;
1613                let pos_y;
1614                if t.center_display[2] {
1615                    pos_x = t.position[0] - text_size.x / 2.0;
1616                } else if t.center_display[0] {
1617                    pos_x = t.position[0];
1618                } else {
1619                    pos_x = t.position[0] - text_size.x;
1620                };
1621                if t.center_display[3] {
1622                    pos_y = t.position[1] - text_size.y / 2.0;
1623                } else if t.center_display[1] {
1624                    pos_y = t.position[1];
1625                } else {
1626                    pos_y = t.position[1] - text_size.y;
1627                };
1628                // 使用绝对定位放置文本
1629                let position = Pos2::new(pos_x, pos_y);
1630
1631                if t.write_background {
1632                    let rect = Rect::from_min_size(position, text_size);
1633                    // 绘制背景颜色
1634                    ui.painter().rect_filled(
1635                        rect,
1636                        t.rounding,
1637                        Color32::from_rgba_unmultiplied(
1638                            t.background_rgb[0],
1639                            t.background_rgb[1],
1640                            t.background_rgb[2],
1641                            t.background_rgb[3],
1642                        ),
1643                    ); // 背景色
1644                };
1645                // 绘制文本
1646                ui.painter().galley(
1647                    position,
1648                    galley.clone(),
1649                    Color32::from_rgba_unmultiplied(
1650                        t.rgba[0], t.rgba[1], t.rgba[2], t.rgba[3], // 应用透明度
1651                    ),
1652                );
1653
1654                if t.selectable {
1655                    let rect = Rect::from_min_size(
1656                        [position[0] - 20_f32, position[1] - 5_f32].into(),
1657                        [text_size[0] + 40_f32, text_size[1] + 10_f32].into(),
1658                    );
1659
1660                    let rect2 = Rect::from_min_size(
1661                        [0_f32, 0_f32].into(),
1662                        [ctx.available_rect().width(), ctx.available_rect().height()].into(),
1663                    );
1664
1665                    // 创建可交互的区域
1666                    let response = ui.interact(
1667                        rect,
1668                        egui::Id::new(format!("text_{}_click_and_drag", t.name)),
1669                        egui::Sense::click_and_drag(),
1670                    );
1671
1672                    let response2 = ui.interact(
1673                        rect2,
1674                        egui::Id::new(format!("text_{}_total", t.name)),
1675                        egui::Sense::click(),
1676                    );
1677
1678                    // 处理选择逻辑
1679                    let cursor_at_pointer = |pointer_pos: Vec2| -> usize {
1680                        let relative_pos = pointer_pos - position.to_vec2();
1681                        let cursor = galley.cursor_from_pos(relative_pos);
1682                        cursor.index
1683                    };
1684
1685                    if !response.clicked() && response2.clicked() {
1686                        t.selection = None;
1687                    };
1688
1689                    if response.clicked() || response.drag_started() {
1690                        if let Some(pointer_pos) = ui.input(|i| i.pointer.interact_pos()) {
1691                            let cursor = cursor_at_pointer(pointer_pos.to_vec2());
1692                            t.selection = Some((cursor, cursor));
1693                        };
1694                        response.request_focus();
1695                    };
1696
1697                    if response.dragged() && t.selection.is_some() {
1698                        if let Some(pointer_pos) = ui.input(|i| i.pointer.interact_pos()) {
1699                            let cursor = cursor_at_pointer(pointer_pos.to_vec2());
1700                            if let Some((start, _)) = t.selection {
1701                                t.selection = Some((start, cursor));
1702                            };
1703                        };
1704                    };
1705
1706                    // 处理复制操作
1707                    if response.has_focus() {
1708                        // 处理复制操作 - 使用按键释放事件
1709                        let copy_triggered = ui.input(|input| {
1710                            let c_released = input.key_released(egui::Key::C);
1711                            let cmd_pressed = input.modifiers.command || input.modifiers.mac_cmd;
1712                            let ctrl_pressed = input.modifiers.ctrl;
1713                            c_released && (cmd_pressed || ctrl_pressed)
1714                        });
1715                        if copy_triggered {
1716                            if let Some((start, end)) = t.selection {
1717                                let (start, end) = (start.min(end), start.max(end));
1718                                let chars: Vec<char> = t.text_content.chars().collect();
1719                                if start <= chars.len() && end <= chars.len() && start < end {
1720                                    let selected_text: String = chars[start..end].iter().collect();
1721                                    ui.ctx().copy_text(selected_text);
1722                                };
1723                            };
1724                        };
1725                    };
1726
1727                    // 绘制选择区域背景
1728                    if let Some((start, end)) = t.selection {
1729                        let (start, end) = (start.min(end), start.max(end));
1730                        if start != end {
1731                            // 获取选择区域的范围
1732                            let start_cursor = galley.pos_from_cursor(CCursor::new(start));
1733                            let end_cursor = galley.pos_from_cursor(CCursor::new(end));
1734
1735                            let start_pos = start_cursor.left_top();
1736                            let end_pos = end_cursor.right_top();
1737                            // 选择框绘制
1738                            if start_pos.y == end_pos.y {
1739                                // 单行选择
1740                                // 修复:使用实际行的高度而不是整个文本的高度除以行数
1741                                let rows = &galley.rows;
1742                                let row_height = if !rows.is_empty() {
1743                                    // 获取实际行的高度
1744                                    if let Some(row) = rows.first() {
1745                                        row.height()
1746                                    } else {
1747                                        text_size.y / t.text_content.lines().count() as f32
1748                                    }
1749                                } else {
1750                                    text_size.y / t.text_content.lines().count() as f32
1751                                };
1752
1753                                let selection_rect = Rect::from_min_max(
1754                                    Pos2::new(position.x + start_pos.x, position.y + start_pos.y),
1755                                    Pos2::new(
1756                                        position.x + end_pos.x,
1757                                        position.y + start_pos.y + row_height,
1758                                    ),
1759                                );
1760                                ui.painter().rect_filled(
1761                                    selection_rect,
1762                                    0.0,
1763                                    Color32::from_rgba_unmultiplied(0, 120, 255, 100),
1764                                );
1765                            } else {
1766                                // 多行选择 - 为每行创建精确的矩形
1767                                let rows = &galley.rows;
1768                                let row_height = if !rows.is_empty() {
1769                                    rows[0].height()
1770                                } else {
1771                                    text_size.y / t.text_content.lines().count() as f32
1772                                };
1773
1774                                // 计算选择的上下边界
1775                                let selection_top = position.y + start_pos.y.min(end_pos.y);
1776                                let selection_bottom = position.y + start_pos.y.max(end_pos.y);
1777
1778                                // 确定起始行和结束行的索引
1779                                let start_row_index = (start_pos.y / row_height).floor() as usize;
1780                                let end_row_index = (end_pos.y / row_height).floor() as usize;
1781                                let (first_row_index, last_row_index) =
1782                                    if start_row_index <= end_row_index {
1783                                        (start_row_index, end_row_index)
1784                                    } else {
1785                                        (end_row_index, start_row_index)
1786                                    };
1787
1788                                for (i, row) in rows.iter().enumerate() {
1789                                    let row_y = position.y + row_height * i as f32;
1790                                    let row_bottom = row_y + row_height;
1791                                    // 检查当前行是否与选择区域相交
1792                                    if row_bottom > selection_top && row_y <= selection_bottom {
1793                                        let left = if i == first_row_index {
1794                                            // 首行 - 从选择开始位置开始
1795                                            position.x + start_pos.x
1796                                        } else {
1797                                            // 非首行 - 从行首开始
1798                                            position.x + row.rect().min.x
1799                                        };
1800
1801                                        let right = if i == last_row_index {
1802                                            // 尾行 - 到选择结束位置结束
1803                                            position.x + end_pos.x
1804                                        } else {
1805                                            // 非尾行 - 到行尾结束
1806                                            position.x + row.rect().max.x
1807                                        };
1808
1809                                        let selection_rect = Rect::from_min_max(
1810                                            Pos2::new(left, row_y),
1811                                            Pos2::new(right, row_bottom),
1812                                        );
1813
1814                                        // 确保矩形有效
1815                                        if selection_rect.width() > 0.0
1816                                            && selection_rect.height() > 0.0
1817                                        {
1818                                            ui.painter().rect_filled(
1819                                                selection_rect,
1820                                                0.0,
1821                                                Color32::from_rgba_unmultiplied(0, 120, 255, 100),
1822                                            );
1823                                        };
1824                                    };
1825                                }
1826                            };
1827                        };
1828                    };
1829                };
1830
1831                // 绘制超链接
1832                for (start, end, url) in &t.hyperlink_text {
1833                    // 获取超链接文本的范围
1834                    let start_cursor = galley.pos_from_cursor(CCursor::new(*start));
1835                    let end_cursor = galley.pos_from_cursor(CCursor::new(*end));
1836
1837                    let start_pos = start_cursor.left_top();
1838                    let end_pos = end_cursor.right_top();
1839
1840                    // 检查鼠标是否在超链接上
1841                    let mut is_hovering_link = false;
1842                    if let Some(pointer_pos) = ui.input(|i| i.pointer.hover_pos()) {
1843                        let relative_pos = pointer_pos - position.to_vec2();
1844                        let cursor = galley.cursor_from_pos(relative_pos.to_vec2());
1845                        if cursor.index >= *start && cursor.index <= *end {
1846                            is_hovering_link = true;
1847                        };
1848                    };
1849
1850                    let row_height = galley.rows.first().map_or(14.0, |row| row.height());
1851
1852                    // 为超链接创建交互响应对象
1853                    let link_responses = if start_cursor.min.y == end_cursor.min.y {
1854                        // 单行超链接
1855                        let link_rect = Rect::from_min_max(
1856                            Pos2::new(position.x + start_pos.x, position.y + start_pos.y),
1857                            Pos2::new(
1858                                position.x + end_pos.x,
1859                                position.y + start_pos.y + row_height,
1860                            ),
1861                        );
1862                        vec![ui.interact(
1863                            link_rect,
1864                            egui::Id::new(format!("link_{}_{}_{}", t.name, start, end)),
1865                            egui::Sense::click(),
1866                        )]
1867                    } else {
1868                        // 多行超链接
1869                        let start_row = (start_pos.y / row_height).round() as usize;
1870                        let end_row = (end_pos.y / row_height).round() as usize;
1871                        let mut responses = Vec::new();
1872
1873                        for row in start_row..=end_row {
1874                            if let Some(current_row) = galley.rows.get(row) {
1875                                let row_rect = current_row.rect();
1876                                let row_y = position.y + row as f32 * row_height;
1877
1878                                let link_rect = if row == start_row {
1879                                    // 第一行从文本开始位置到行尾
1880                                    Rect::from_min_max(
1881                                        Pos2::new(position.x + start_pos.x, row_y),
1882                                        Pos2::new(position.x + row_rect.max.x, row_y + row_height),
1883                                    )
1884                                } else if row == end_row {
1885                                    // 最后一行从行首到文本结束位置
1886                                    Rect::from_min_max(
1887                                        Pos2::new(position.x + row_rect.min.x, row_y),
1888                                        Pos2::new(position.x + end_pos.x, row_y + row_height),
1889                                    )
1890                                } else {
1891                                    // 中间整行
1892                                    Rect::from_min_max(
1893                                        Pos2::new(position.x + row_rect.min.x, row_y),
1894                                        Pos2::new(position.x + row_rect.max.x, row_y + row_height),
1895                                    )
1896                                };
1897
1898                                responses.push(ui.interact(
1899                                    link_rect,
1900                                    egui::Id::new(format!(
1901                                        "link_{}_{}_{}_row_{}",
1902                                        t.name, start, end, row
1903                                    )),
1904                                    egui::Sense::click(),
1905                                ));
1906                            };
1907                        }
1908                        responses
1909                    };
1910
1911                    // 检查是否正在点击这个超链接
1912                    let mut is_pressing_link = false;
1913                    for link_response in &link_responses {
1914                        if link_response.is_pointer_button_down_on()
1915                            && !link_response.drag_started()
1916                        {
1917                            t.selection = None;
1918                            if let Some(pointer_pos) = ui.input(|i| i.pointer.interact_pos()) {
1919                                let relative_pos = pointer_pos - position.to_vec2();
1920                                let cursor = galley.cursor_from_pos(relative_pos.to_vec2());
1921                                if cursor.index >= *start && cursor.index <= *end {
1922                                    is_pressing_link = true;
1923                                    break;
1924                                };
1925                            };
1926                        };
1927                    }
1928
1929                    // 检查是否释放了鼠标(点击完成)
1930                    let mut clicked_on_link = false;
1931                    for link_response in &link_responses {
1932                        if link_response.clicked() {
1933                            if let Some(pointer_pos) = ui.input(|i| i.pointer.interact_pos()) {
1934                                let relative_pos = pointer_pos - position.to_vec2();
1935                                let cursor = galley.cursor_from_pos(relative_pos.to_vec2());
1936                                if cursor.index >= *start && cursor.index <= *end {
1937                                    clicked_on_link = true;
1938                                    break;
1939                                };
1940                            };
1941                        };
1942                    }
1943
1944                    if clicked_on_link {
1945                        // 执行超链接跳转
1946                        if !url.is_empty() {
1947                            ui.ctx().open_url(egui::OpenUrl::new_tab(url));
1948                        };
1949                    };
1950
1951                    // 绘制超链接高亮(如果正在点击或悬停)
1952                    if is_pressing_link {
1953                        if start_cursor.min.y == end_cursor.min.y {
1954                            // 单行超链接高亮
1955                            let selection_rect = Rect::from_min_max(
1956                                Pos2::new(position.x + start_pos.x, position.y + start_pos.y),
1957                                Pos2::new(
1958                                    position.x + end_pos.x,
1959                                    position.y
1960                                        + start_pos.y
1961                                        + galley.rows.first().map_or(14.0, |row| row.height()),
1962                                ),
1963                            );
1964                            ui.painter().rect_filled(
1965                                selection_rect,
1966                                0.0,
1967                                Color32::from_rgba_unmultiplied(0, 120, 255, 100),
1968                            );
1969                        } else {
1970                            // 多行超链接高亮
1971                            let row_height = galley.rows.first().map_or(14.0, |row| row.height());
1972                            let start_row = (start_pos.y / row_height).round() as usize;
1973                            let end_row = (end_pos.y / row_height).round() as usize;
1974
1975                            for row in start_row..=end_row {
1976                                if let Some(current_row) = galley.rows.get(row) {
1977                                    let row_rect = current_row.rect();
1978
1979                                    if row == start_row {
1980                                        // 第一行从文本开始位置到行尾
1981                                        let selection_rect = Rect::from_min_max(
1982                                            Pos2::new(
1983                                                position.x + start_pos.x,
1984                                                position.y + row as f32 * row_height,
1985                                            ),
1986                                            Pos2::new(
1987                                                position.x + row_rect.max.x,
1988                                                position.y + row as f32 * row_height + row_height,
1989                                            ),
1990                                        );
1991                                        ui.painter().rect_filled(
1992                                            selection_rect,
1993                                            0.0,
1994                                            Color32::from_rgba_unmultiplied(0, 120, 255, 100),
1995                                        );
1996                                    } else if row == end_row {
1997                                        // 最后一行从行首到文本结束位置
1998                                        let selection_rect = Rect::from_min_max(
1999                                            Pos2::new(
2000                                                position.x + row_rect.min.x,
2001                                                position.y + row as f32 * row_height,
2002                                            ),
2003                                            Pos2::new(
2004                                                position.x + end_pos.x,
2005                                                position.y + row as f32 * row_height + row_height,
2006                                            ),
2007                                        );
2008                                        ui.painter().rect_filled(
2009                                            selection_rect,
2010                                            0.0,
2011                                            Color32::from_rgba_unmultiplied(0, 120, 255, 100),
2012                                        );
2013                                    } else {
2014                                        // 中间整行高亮
2015                                        let selection_rect = Rect::from_min_max(
2016                                            Pos2::new(
2017                                                position.x + row_rect.min.x,
2018                                                position.y + row as f32 * row_height,
2019                                            ),
2020                                            Pos2::new(
2021                                                position.x + row_rect.max.x,
2022                                                position.y + row as f32 * row_height + row_height,
2023                                            ),
2024                                        );
2025                                        ui.painter().rect_filled(
2026                                            selection_rect,
2027                                            0.0,
2028                                            Color32::from_rgba_unmultiplied(0, 120, 255, 100),
2029                                        );
2030                                    };
2031                                };
2032                            }
2033                        };
2034                    };
2035
2036                    // 绘制超链接下划线
2037                    // 检查超链接是否跨行
2038                    if start_cursor.min.y == end_cursor.min.y {
2039                        // 单行超链接
2040                        let underline_y = position.y
2041                            + start_pos.y
2042                            + galley.rows.first().map_or(14.0, |row| row.height())
2043                            - 2.0;
2044
2045                        // 绘制下划线
2046                        let color = if is_hovering_link {
2047                            Color32::from_rgba_unmultiplied(
2048                                t.rgba[0].saturating_add(50),
2049                                t.rgba[1],
2050                                t.rgba[2],
2051                                t.rgba[3],
2052                            )
2053                        } else {
2054                            Color32::from_rgba_unmultiplied(
2055                                t.rgba[0], t.rgba[1], t.rgba[2], t.rgba[3],
2056                            )
2057                        };
2058
2059                        ui.painter().line_segment(
2060                            [
2061                                Pos2::new(position.x + start_pos.x, underline_y),
2062                                Pos2::new(position.x + end_pos.x, underline_y),
2063                            ],
2064                            Stroke::new(t.font_size / 10_f32, color),
2065                        );
2066                    } else {
2067                        // 多行超链接
2068                        let row_height = galley.rows.first().map_or(14.0, |row| row.height()); // 默认行高14.0
2069
2070                        // 计算起始行和结束行的索引
2071                        let start_row = (start_pos.y / row_height).round() as usize;
2072                        let end_row = (end_pos.y / row_height).round() as usize;
2073
2074                        for row in start_row..=end_row {
2075                            let row_y = position.y + row as f32 * row_height + row_height - 2.0; // 行底部稍微上移一点绘制下划线
2076
2077                            // 获取当前行的矩形范围
2078                            if let Some(current_row) = galley.rows.get(row) {
2079                                let row_rect = current_row.rect();
2080
2081                                let color = Color32::from_rgba_unmultiplied(
2082                                    t.rgba[0], t.rgba[1], t.rgba[2], t.rgba[3],
2083                                );
2084
2085                                if row == start_row {
2086                                    // 第一行从文本开始位置到行尾
2087                                    ui.painter().line_segment(
2088                                        [
2089                                            Pos2::new(position.x + start_pos.x, row_y),
2090                                            Pos2::new(position.x + row_rect.max.x, row_y),
2091                                        ],
2092                                        Stroke::new(t.font_size / 10_f32, color),
2093                                    );
2094                                } else if row == end_row {
2095                                    // 最后一行从行首到文本结束位置
2096                                    ui.painter().line_segment(
2097                                        [
2098                                            Pos2::new(position.x + row_rect.min.x, row_y),
2099                                            Pos2::new(position.x + end_pos.x, row_y),
2100                                        ],
2101                                        Stroke::new(t.font_size / 10_f32, color),
2102                                    );
2103                                } else {
2104                                    // 中间整行下划线
2105                                    ui.painter().line_segment(
2106                                        [
2107                                            Pos2::new(position.x + row_rect.min.x, row_y),
2108                                            Pos2::new(position.x + row_rect.max.x, row_y),
2109                                        ],
2110                                        Stroke::new(t.font_size / 10_f32, color),
2111                                    );
2112                                };
2113                            };
2114                        }
2115                    };
2116                }
2117                self.rust_constructor_resource[id] = RCR::Text(t);
2118            };
2119        };
2120    }
2121
2122    /// 获取文本大小。
2123    pub fn get_text_size(
2124        &mut self,
2125        resource_name: &str,
2126        ui: &mut Ui,
2127    ) -> Result<[f32; 2], RustConstructorError> {
2128        if let Ok(id) = self.get_resource_index("Text", resource_name) {
2129            if let RCR::Text(t) = self.rust_constructor_resource[id].clone() {
2130                let galley = ui.fonts(|f| {
2131                    f.layout(
2132                        t.text_content.to_string(),
2133                        FontId::proportional(t.font_size),
2134                        Color32::from_rgba_unmultiplied(t.rgba[0], t.rgba[1], t.rgba[2], t.rgba[3]),
2135                        t.wrap_width,
2136                    )
2137                });
2138                return Ok([galley.size().x, galley.size().y]);
2139            };
2140        };
2141        self.problem_report(
2142            RustConstructorError::TextNotFound {
2143                text_name: resource_name.to_string(),
2144            },
2145            SeverityLevel::SevereWarning,
2146        );
2147        Err(RustConstructorError::TextNotFound {
2148            text_name: resource_name.to_string(),
2149        })
2150    }
2151
2152    /// 添加变量资源。
2153    pub fn add_var<T: Into<Value>>(&mut self, name: &str, value: T) {
2154        self.rust_constructor_resource.push(RCR::Variable(Variable {
2155            discern_type: "Variable".to_string(),
2156            name: name.to_string(),
2157            value: value.into(),
2158        }));
2159    }
2160
2161    /// 修改变量资源。
2162    pub fn modify_var<T: Into<Value>>(&mut self, name: &str, value: T) {
2163        if let Ok(id) = self.get_resource_index("Variable", name) {
2164            if let RCR::Variable(v) = &mut self.rust_constructor_resource[id] {
2165                v.value = value.into();
2166            };
2167        };
2168    }
2169
2170    /// 取出Value变量。
2171    pub fn var(&mut self, name: &str) -> Result<Value, RustConstructorError> {
2172        if let Ok(id) = self.get_resource_index("Variable", name) {
2173            if let RCR::Variable(v) = self.rust_constructor_resource[id].clone() {
2174                return Ok(v.clone().value);
2175            };
2176        };
2177        self.problem_report(
2178            RustConstructorError::VariableNotFound {
2179                variable_name: name.to_string(),
2180            },
2181            SeverityLevel::SevereWarning,
2182        );
2183        Err(RustConstructorError::VariableNotFound {
2184            variable_name: name.to_string(),
2185        })
2186    }
2187
2188    /// 取出i32变量。
2189    pub fn var_i(&mut self, name: &str) -> Result<i32, RustConstructorError> {
2190        if let Ok(id) = self.get_resource_index("Variable", name) {
2191            if let RCR::Variable(v) = self.rust_constructor_resource[id].clone() {
2192                match &v.value {
2193                    // 直接访问 value 字段
2194                    Value::Int(i) => Ok(*i),
2195                    _ => {
2196                        self.problem_report(
2197                            RustConstructorError::VariableNotInt {
2198                                variable_name: name.to_string(),
2199                            },
2200                            SeverityLevel::SevereWarning,
2201                        );
2202                        Err(RustConstructorError::VariableNotInt {
2203                            variable_name: name.to_string(),
2204                        })
2205                    }
2206                }
2207            } else {
2208                // 正常情况下不会触发。
2209                Err(RustConstructorError::VariableNotFound {
2210                    variable_name: name.to_string(),
2211                })
2212            }
2213        } else {
2214            self.problem_report(
2215                RustConstructorError::VariableNotFound {
2216                    variable_name: name.to_string(),
2217                },
2218                SeverityLevel::SevereWarning,
2219            );
2220            Err(RustConstructorError::VariableNotFound {
2221                variable_name: name.to_string(),
2222            })
2223        }
2224    }
2225
2226    /// 取出u32资源。
2227    pub fn var_u(&mut self, name: &str) -> Result<u32, RustConstructorError> {
2228        if let Ok(id) = self.get_resource_index("Variable", name) {
2229            if let RCR::Variable(v) = self.rust_constructor_resource[id].clone() {
2230                match &v.value {
2231                    // 直接访问 value 字段
2232                    Value::UInt(u) => Ok(*u),
2233                    _ => {
2234                        self.problem_report(
2235                            RustConstructorError::VariableNotUInt {
2236                                variable_name: name.to_string(),
2237                            },
2238                            SeverityLevel::SevereWarning,
2239                        );
2240                        Err(RustConstructorError::VariableNotUInt {
2241                            variable_name: name.to_string(),
2242                        })
2243                    }
2244                }
2245            } else {
2246                // 正常情况下不会触发。
2247                Err(RustConstructorError::VariableNotFound {
2248                    variable_name: name.to_string(),
2249                })
2250            }
2251        } else {
2252            self.problem_report(
2253                RustConstructorError::VariableNotFound {
2254                    variable_name: name.to_string(),
2255                },
2256                SeverityLevel::SevereWarning,
2257            );
2258            Err(RustConstructorError::VariableNotFound {
2259                variable_name: name.to_string(),
2260            })
2261        }
2262    }
2263
2264    /// 取出f32资源。
2265    pub fn var_f(&mut self, name: &str) -> Result<f32, RustConstructorError> {
2266        if let Ok(id) = self.get_resource_index("Variable", name) {
2267            if let RCR::Variable(v) = self.rust_constructor_resource[id].clone() {
2268                match &v.value {
2269                    // 直接访问 value 字段
2270                    Value::Float(f) => Ok(*f),
2271                    _ => {
2272                        self.problem_report(
2273                            RustConstructorError::VariableNotFloat {
2274                                variable_name: name.to_string(),
2275                            },
2276                            SeverityLevel::SevereWarning,
2277                        );
2278                        Err(RustConstructorError::VariableNotFloat {
2279                            variable_name: name.to_string(),
2280                        })
2281                    }
2282                }
2283            } else {
2284                // 正常情况下不会触发。
2285                Err(RustConstructorError::VariableNotFound {
2286                    variable_name: name.to_string(),
2287                })
2288            }
2289        } else {
2290            self.problem_report(
2291                RustConstructorError::VariableNotFound {
2292                    variable_name: name.to_string(),
2293                },
2294                SeverityLevel::SevereWarning,
2295            );
2296            Err(RustConstructorError::VariableNotFound {
2297                variable_name: name.to_string(),
2298            })
2299        }
2300    }
2301
2302    /// 取出布尔值资源。
2303    pub fn var_b(&mut self, name: &str) -> Result<bool, RustConstructorError> {
2304        if let Ok(id) = self.get_resource_index("Variable", name) {
2305            if let RCR::Variable(v) = self.rust_constructor_resource[id].clone() {
2306                match &v.value {
2307                    // 直接访问 value 字段
2308                    Value::Bool(b) => Ok(*b),
2309                    _ => {
2310                        self.problem_report(
2311                            RustConstructorError::VariableNotBool {
2312                                variable_name: name.to_string(),
2313                            },
2314                            SeverityLevel::SevereWarning,
2315                        );
2316                        Err(RustConstructorError::VariableNotBool {
2317                            variable_name: name.to_string(),
2318                        })
2319                    }
2320                }
2321            } else {
2322                // 正常情况下不会触发。
2323                Err(RustConstructorError::VariableNotFound {
2324                    variable_name: name.to_string(),
2325                })
2326            }
2327        } else {
2328            self.problem_report(
2329                RustConstructorError::VariableNotFound {
2330                    variable_name: name.to_string(),
2331                },
2332                SeverityLevel::SevereWarning,
2333            );
2334            Err(RustConstructorError::VariableNotFound {
2335                variable_name: name.to_string(),
2336            })
2337        }
2338    }
2339
2340    /// 取出包含Value的Vec资源。
2341    pub fn var_v(&mut self, name: &str) -> Result<Vec<Value>, RustConstructorError> {
2342        if let Ok(id) = self.get_resource_index("Variable", name) {
2343            if let RCR::Variable(v) = self.rust_constructor_resource[id].clone() {
2344                match &v.value {
2345                    // 直接访问 value 字段
2346                    Value::Vec(v) => Ok(v.clone()),
2347                    _ => {
2348                        self.problem_report(
2349                            RustConstructorError::VariableNotVec {
2350                                variable_name: name.to_string(),
2351                            },
2352                            SeverityLevel::SevereWarning,
2353                        );
2354                        Err(RustConstructorError::VariableNotVec {
2355                            variable_name: name.to_string(),
2356                        })
2357                    }
2358                }
2359            } else {
2360                // 正常情况下不会触发。
2361                Err(RustConstructorError::VariableNotFound {
2362                    variable_name: name.to_string(),
2363                })
2364            }
2365        } else {
2366            self.problem_report(
2367                RustConstructorError::VariableNotFound {
2368                    variable_name: name.to_string(),
2369                },
2370                SeverityLevel::SevereWarning,
2371            );
2372            Err(RustConstructorError::VariableNotFound {
2373                variable_name: name.to_string(),
2374            })
2375        }
2376    }
2377
2378    /// 取出字符串资源。
2379    pub fn var_s(&mut self, name: &str) -> Result<String, RustConstructorError> {
2380        if let Ok(id) = self.get_resource_index("Variable", name) {
2381            if let RCR::Variable(v) = self.rust_constructor_resource[id].clone() {
2382                match &v.value {
2383                    // 直接访问 value 字段
2384                    Value::String(s) => Ok(s.clone()),
2385                    _ => {
2386                        self.problem_report(
2387                            RustConstructorError::VariableNotString {
2388                                variable_name: name.to_string(),
2389                            },
2390                            SeverityLevel::SevereWarning,
2391                        );
2392                        Err(RustConstructorError::VariableNotString {
2393                            variable_name: name.to_string(),
2394                        })
2395                    }
2396                }
2397            } else {
2398                // 正常情况下不会触发。
2399                Err(RustConstructorError::VariableNotFound {
2400                    variable_name: name.to_string(),
2401                })
2402            }
2403        } else {
2404            self.problem_report(
2405                RustConstructorError::VariableNotFound {
2406                    variable_name: name.to_string(),
2407                },
2408                SeverityLevel::SevereWarning,
2409            );
2410            Err(RustConstructorError::VariableNotFound {
2411                variable_name: name.to_string(),
2412            })
2413        }
2414    }
2415
2416    /// 尝试将Value转换成布尔值。
2417    pub fn var_decode_b(&mut self, target: Value) -> Result<bool, RustConstructorError> {
2418        match target {
2419            Value::Bool(b) => {
2420                // 处理布尔值
2421                Ok(b)
2422            }
2423            _ => {
2424                self.problem_report(
2425                    RustConstructorError::VariableNotBool {
2426                        variable_name: format!("{:?}", target),
2427                    },
2428                    SeverityLevel::SevereWarning,
2429                );
2430                Err(RustConstructorError::VariableNotBool {
2431                    variable_name: format!("{:?}", target),
2432                })
2433            }
2434        }
2435    }
2436
2437    /// 尝试将Value转换成i32。
2438    pub fn var_decode_i(&mut self, target: Value) -> Result<i32, RustConstructorError> {
2439        match target {
2440            Value::Int(i) => {
2441                // 处理i32整型
2442                Ok(i)
2443            }
2444            _ => {
2445                self.problem_report(
2446                    RustConstructorError::VariableNotInt {
2447                        variable_name: format!("{:?}", target),
2448                    },
2449                    SeverityLevel::SevereWarning,
2450                );
2451                Err(RustConstructorError::VariableNotInt {
2452                    variable_name: format!("{:?}", target),
2453                })
2454            }
2455        }
2456    }
2457
2458    /// 尝试将Value转换成u32。
2459    pub fn var_decode_u(&mut self, target: Value) -> Result<u32, RustConstructorError> {
2460        match target {
2461            Value::UInt(u) => {
2462                // 处理u32无符号整型
2463                Ok(u)
2464            }
2465            _ => {
2466                self.problem_report(
2467                    RustConstructorError::VariableNotUInt {
2468                        variable_name: format!("{:?}", target),
2469                    },
2470                    SeverityLevel::SevereWarning,
2471                );
2472                Err(RustConstructorError::VariableNotUInt {
2473                    variable_name: format!("{:?}", target),
2474                })
2475            }
2476        }
2477    }
2478
2479    /// 尝试将Value转换成f32。
2480    pub fn var_decode_f(&mut self, target: Value) -> Result<f32, RustConstructorError> {
2481        match target {
2482            Value::Float(f) => {
2483                // 处理浮点数
2484                Ok(f)
2485            }
2486            _ => {
2487                self.problem_report(
2488                    RustConstructorError::VariableNotFloat {
2489                        variable_name: format!("{:?}", target),
2490                    },
2491                    SeverityLevel::SevereWarning,
2492                );
2493                Err(RustConstructorError::VariableNotFloat {
2494                    variable_name: format!("{:?}", target),
2495                })
2496            }
2497        }
2498    }
2499
2500    /// 尝试将Value转换成字符串。
2501    pub fn var_decode_s(&mut self, target: Value) -> Result<String, RustConstructorError> {
2502        match target {
2503            Value::String(s) => {
2504                // 处理字符串
2505                Ok(s)
2506            }
2507            _ => {
2508                self.problem_report(
2509                    RustConstructorError::VariableNotString {
2510                        variable_name: format!("{:?}", target),
2511                    },
2512                    SeverityLevel::SevereWarning,
2513                );
2514                Err(RustConstructorError::VariableNotString {
2515                    variable_name: format!("{:?}", target),
2516                })
2517            }
2518        }
2519    }
2520
2521    /// 尝试将Value转换成Vec。
2522    pub fn var_decode_v(&mut self, target: Value) -> Result<Vec<Value>, RustConstructorError> {
2523        match target {
2524            Value::Vec(v) => {
2525                // 处理字符串
2526                Ok(v)
2527            }
2528            _ => {
2529                self.problem_report(
2530                    RustConstructorError::VariableNotVec {
2531                        variable_name: format!("{:?}", target),
2532                    },
2533                    SeverityLevel::SevereWarning,
2534                );
2535                Err(RustConstructorError::VariableNotVec {
2536                    variable_name: format!("{:?}", target),
2537                })
2538            }
2539        }
2540    }
2541
2542    /// 添加滚动背景资源。
2543    pub fn add_scroll_background(
2544        &mut self,
2545        name: &str,
2546        image_name: Vec<String>,
2547        horizontal_or_vertical: bool,
2548        left_and_top_or_right_and_bottom: bool,
2549        scroll_speed: u32,
2550        size_position_boundary: [f32; 5],
2551    ) {
2552        let mut image_id = vec![];
2553        for i in image_name.clone() {
2554            for u in 0..self.rust_constructor_resource.len() {
2555                if let RCR::Image(im) = self.rust_constructor_resource[u].clone() {
2556                    if im.name == i {
2557                        image_id.push(u);
2558                    };
2559                };
2560            }
2561        }
2562        for (count, _) in image_id.clone().into_iter().enumerate() {
2563            if let RCR::Image(im) = &mut self.rust_constructor_resource[image_id[count]] {
2564                im.x_grid = [0, 0];
2565                im.y_grid = [0, 0];
2566                im.center_display = [true, true, false, false];
2567                im.image_size = [size_position_boundary[0], size_position_boundary[1]];
2568                let mut temp_position;
2569                if horizontal_or_vertical {
2570                    temp_position = size_position_boundary[2];
2571                } else {
2572                    temp_position = size_position_boundary[3];
2573                };
2574                if horizontal_or_vertical {
2575                    for _ in 0..count {
2576                        if left_and_top_or_right_and_bottom {
2577                            temp_position += size_position_boundary[0];
2578                        } else {
2579                            temp_position -= size_position_boundary[0];
2580                        };
2581                    }
2582                    im.origin_position = [temp_position, size_position_boundary[3]];
2583                } else {
2584                    for _ in 0..count {
2585                        if left_and_top_or_right_and_bottom {
2586                            temp_position += size_position_boundary[1];
2587                        } else {
2588                            temp_position -= size_position_boundary[1];
2589                        };
2590                    }
2591                    im.origin_position = [size_position_boundary[2], temp_position];
2592                };
2593            };
2594        }
2595        if let RCR::Image(im) = self.rust_constructor_resource[image_id[image_id.len() - 1]].clone()
2596        {
2597            let resume_point = if horizontal_or_vertical {
2598                im.origin_position[0]
2599            } else {
2600                im.origin_position[1]
2601            };
2602            self.rust_constructor_resource
2603                .push(RCR::ScrollBackground(ScrollBackground {
2604                    discern_type: "ScrollBackground".to_string(),
2605                    name: name.to_string(),
2606                    image_name,
2607                    horizontal_or_vertical,
2608                    left_and_top_or_right_and_bottom,
2609                    scroll_speed,
2610                    boundary: size_position_boundary[4],
2611                    resume_point,
2612                }));
2613        };
2614    }
2615
2616    /// 显示滚动背景。
2617    pub fn scroll_background(&mut self, ui: &mut Ui, name: &str, ctx: &egui::Context) {
2618        if let Ok(id) = self.get_resource_index("ScrollBackground", name) {
2619            if let RCR::ScrollBackground(sb) = self.rust_constructor_resource[id].clone() {
2620                sb.reg_render_resource(&mut self.render_resource_list);
2621                if self.get_resource_index("SplitTime", name).is_err() {
2622                    self.add_split_time(name, false);
2623                };
2624                for i in 0..sb.image_name.len() {
2625                    self.image(ui, &sb.image_name[i].clone(), ctx);
2626                }
2627                if self.timer.now_time - self.split_time(name).unwrap()[0] >= self.vertrefresh {
2628                    self.add_split_time(name, true);
2629                    for i in 0..sb.image_name.len() {
2630                        if let Ok(id2) = self.get_resource_index("Image", &sb.image_name[i].clone())
2631                        {
2632                            if let RCR::Image(mut im) = self.rust_constructor_resource[id2].clone()
2633                            {
2634                                if sb.horizontal_or_vertical {
2635                                    if sb.left_and_top_or_right_and_bottom {
2636                                        for _ in 0..sb.scroll_speed {
2637                                            im.origin_position[0] -= 1_f32;
2638                                            if im.origin_position[0] <= sb.boundary {
2639                                                im.origin_position[0] = sb.resume_point;
2640                                            };
2641                                        }
2642                                        self.rust_constructor_resource[id2] =
2643                                            RCR::Image(im.clone());
2644                                    } else {
2645                                        for _ in 0..sb.scroll_speed {
2646                                            im.origin_position[0] += 1_f32;
2647                                            if im.origin_position[0] >= sb.boundary {
2648                                                im.origin_position[0] = sb.resume_point;
2649                                            };
2650                                        }
2651                                        self.rust_constructor_resource[id2] =
2652                                            RCR::Image(im.clone());
2653                                    };
2654                                } else if sb.left_and_top_or_right_and_bottom {
2655                                    for _ in 0..sb.scroll_speed {
2656                                        im.origin_position[1] -= 1_f32;
2657                                        if im.origin_position[1] <= sb.boundary {
2658                                            im.origin_position[1] = sb.resume_point;
2659                                        };
2660                                    }
2661                                    self.rust_constructor_resource[id2] = RCR::Image(im.clone());
2662                                } else {
2663                                    for _ in 0..sb.scroll_speed {
2664                                        im.origin_position[1] += 1_f32;
2665                                        if im.origin_position[1] >= sb.boundary {
2666                                            im.origin_position[1] = sb.resume_point;
2667                                        };
2668                                    }
2669                                    self.rust_constructor_resource[id2] = RCR::Image(im.clone());
2670                                };
2671                            };
2672                        };
2673                    }
2674                };
2675            };
2676        };
2677    }
2678
2679    /// 添加图片纹理资源。
2680    pub fn add_image_texture(
2681        &mut self,
2682        name: &str,
2683        path: &str,
2684        flip: [bool; 2],
2685        create_new_resource: bool,
2686        ctx: &egui::Context,
2687    ) {
2688        if let Ok(mut file) = File::open(path) {
2689            let mut buffer = Vec::new();
2690            file.read_to_end(&mut buffer).unwrap();
2691            let img_bytes = buffer;
2692            let img = image::load_from_memory(&img_bytes).unwrap();
2693            let rgba_data = match flip {
2694                [true, true] => img.fliph().flipv().into_rgba8(),
2695                [true, false] => img.fliph().into_rgba8(),
2696                [false, true] => img.flipv().into_rgba8(),
2697                _ => img.into_rgba8(),
2698            };
2699            let (w, h) = (rgba_data.width(), rgba_data.height());
2700            let raw_data: Vec<u8> = rgba_data.into_raw();
2701
2702            let color_image =
2703                egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &raw_data);
2704            let image_texture = Some(ctx.load_texture(name, color_image, TextureOptions::LINEAR));
2705            if create_new_resource {
2706                self.rust_constructor_resource
2707                    .push(RCR::ImageTexture(ImageTexture {
2708                        discern_type: "ImageTexture".to_string(),
2709                        name: name.to_string(),
2710                        texture: image_texture,
2711                        cite_path: path.to_string(),
2712                    }));
2713            } else if let Ok(id) = self.get_resource_index("ImageTexture", name) {
2714                if let RCR::ImageTexture(it) = &mut self.rust_constructor_resource[id] {
2715                    if !create_new_resource {
2716                        it.texture = image_texture;
2717                        it.cite_path = path.to_string();
2718                    };
2719                };
2720            } else {
2721                self.rust_constructor_resource
2722                    .push(RCR::ImageTexture(ImageTexture {
2723                        discern_type: "ImageTexture".to_string(),
2724                        name: name.to_string(),
2725                        texture: image_texture,
2726                        cite_path: path.to_string(),
2727                    }));
2728            };
2729        } else {
2730            self.problem_report(
2731                RustConstructorError::ImageGetFailed {
2732                    image_path: path.to_string(),
2733                },
2734                SeverityLevel::SevereWarning,
2735            );
2736        };
2737    }
2738
2739    /// 添加图片资源。
2740    pub fn add_image(
2741        &mut self,
2742        name: &str,
2743        position_size: [f32; 4],
2744        grid: [u32; 4],
2745        center_display_and_use_overlay: [bool; 5],
2746        alpha_and_overlay_color: [u8; 5],
2747        image_texture_name: &str,
2748    ) {
2749        if let Ok(id) = self.get_resource_index("ImageTexture", image_texture_name) {
2750            if let RCR::ImageTexture(it) = self.rust_constructor_resource[id].clone() {
2751                self.rust_constructor_resource.push(RCR::Image(Image {
2752                    discern_type: "Image".to_string(),
2753                    name: name.to_string(),
2754                    image_texture: it.texture.clone(),
2755                    image_position: [position_size[0], position_size[1]],
2756                    image_size: [position_size[2], position_size[3]],
2757                    x_grid: [grid[0], grid[1]],
2758                    y_grid: [grid[2], grid[3]],
2759                    center_display: [
2760                        center_display_and_use_overlay[0],
2761                        center_display_and_use_overlay[1],
2762                        center_display_and_use_overlay[2],
2763                        center_display_and_use_overlay[3],
2764                    ],
2765                    alpha: alpha_and_overlay_color[0],
2766                    overlay_color: [
2767                        alpha_and_overlay_color[1],
2768                        alpha_and_overlay_color[2],
2769                        alpha_and_overlay_color[3],
2770                        alpha_and_overlay_color[4],
2771                    ],
2772                    use_overlay_color: center_display_and_use_overlay[4],
2773                    origin_position: [position_size[0], position_size[1]],
2774                    cite_texture: image_texture_name.to_string(),
2775                    last_frame_cite_texture: image_texture_name.to_string(),
2776                }));
2777            };
2778        };
2779    }
2780
2781    /// 显示图片资源。
2782    pub fn image(&mut self, ui: &mut Ui, name: &str, ctx: &egui::Context) {
2783        if let Ok(id) = self.get_resource_index("Image", name) {
2784            if let RCR::Image(mut im) = self.rust_constructor_resource[id].clone() {
2785                if im.cite_texture != im.last_frame_cite_texture {
2786                    if let Ok(id2) = self.get_resource_index("ImageTexture", &im.cite_texture) {
2787                        if let RCR::ImageTexture(it) = self.rust_constructor_resource[id2].clone() {
2788                            im.image_texture = it.texture;
2789                        };
2790                    };
2791                };
2792                im.reg_render_resource(&mut self.render_resource_list);
2793                im.image_position[0] = match im.x_grid[1] {
2794                    0 => im.origin_position[0],
2795                    _ => {
2796                        (ctx.available_rect().width() as f64 / im.x_grid[1] as f64
2797                            * im.x_grid[0] as f64) as f32
2798                            + im.origin_position[0]
2799                    }
2800                };
2801                im.image_position[1] = match im.y_grid[1] {
2802                    0 => im.origin_position[1],
2803                    _ => {
2804                        (ctx.available_rect().height() as f64 / im.y_grid[1] as f64
2805                            * im.y_grid[0] as f64) as f32
2806                            + im.origin_position[1]
2807                    }
2808                };
2809                if im.center_display[2] {
2810                    im.image_position[0] -= im.image_size[0] / 2.0;
2811                } else if !im.center_display[0] {
2812                    im.image_position[0] -= im.image_size[0];
2813                };
2814                if im.center_display[3] {
2815                    im.image_position[1] -= im.image_size[1] / 2.0;
2816                } else if !im.center_display[1] {
2817                    im.image_position[1] -= im.image_size[1];
2818                };
2819                if let Some(texture) = &im.image_texture {
2820                    let rect = Rect::from_min_size(
2821                        Pos2::new(im.image_position[0], im.image_position[1]),
2822                        Vec2::new(im.image_size[0], im.image_size[1]),
2823                    );
2824                    let color = if im.use_overlay_color {
2825                        // 创建颜色覆盖
2826                        Color32::from_rgba_unmultiplied(
2827                            im.overlay_color[0],
2828                            im.overlay_color[1],
2829                            im.overlay_color[2],
2830                            // 将图片透明度与覆盖颜色透明度相乘
2831                            (im.alpha as f32 * im.overlay_color[3] as f32 / 255.0) as u8,
2832                        )
2833                    } else {
2834                        Color32::from_white_alpha(im.alpha)
2835                    };
2836
2837                    // 直接绘制图片
2838                    egui::Image::new(egui::ImageSource::Texture(texture.into()))
2839                        .tint(color)
2840                        .paint_at(ui, rect)
2841                };
2842                im.last_frame_cite_texture = im.cite_texture.clone();
2843                self.rust_constructor_resource[id] = RCR::Image(im);
2844            };
2845        };
2846    }
2847
2848    /// 添加消息框资源(重要事项:你需要添加一个CloseMessageBox图片纹理资源才可正常使用!)。
2849    pub fn add_message_box(
2850        &mut self,
2851        box_itself_title_content_image_name_and_sound_path: [&str; 5],
2852        box_size: [f32; 2],
2853        box_keep_existing: bool,
2854        box_existing_time: f32,
2855        box_normal_and_restore_speed: [f32; 2],
2856    ) {
2857        if !self.check_resource_exists(
2858            "MessageBox",
2859            box_itself_title_content_image_name_and_sound_path[0],
2860        ) {
2861            if let Ok(id) = self.get_resource_index(
2862                "Image",
2863                box_itself_title_content_image_name_and_sound_path[3],
2864            ) {
2865                if let RCR::Image(im) = &mut self.rust_constructor_resource[id] {
2866                    im.image_size = [box_size[1] - 15_f32, box_size[1] - 15_f32];
2867                    im.center_display = [true, false, false, true];
2868                    im.x_grid = [1, 1];
2869                    im.y_grid = [0, 1];
2870                    im.name = format!("MessageBox{}", im.name);
2871                };
2872            };
2873            if let Ok(id) = self.get_resource_index(
2874                "Text",
2875                box_itself_title_content_image_name_and_sound_path[1],
2876            ) {
2877                if let RCR::Text(t) = &mut self.rust_constructor_resource[id] {
2878                    t.x_grid = [1, 1];
2879                    t.y_grid = [0, 1];
2880                    t.center_display = [true, true, false, false];
2881                    t.wrap_width = box_size[0] - box_size[1] + 5_f32;
2882                    t.name = format!("MessageBox{}", t.name);
2883                };
2884            };
2885            if let Ok(id) = self.get_resource_index(
2886                "Text",
2887                box_itself_title_content_image_name_and_sound_path[2],
2888            ) {
2889                if let RCR::Text(t) = &mut self.rust_constructor_resource[id] {
2890                    t.center_display = [true, true, false, false];
2891                    t.x_grid = [1, 1];
2892                    t.y_grid = [0, 1];
2893                    t.wrap_width = box_size[0] - box_size[1] + 5_f32;
2894                    t.name = format!("MessageBox{}", t.name);
2895                };
2896            };
2897            self.rust_constructor_resource
2898                .push(RCR::MessageBox(MessageBox {
2899                    discern_type: "MessageBox".to_string(),
2900                    name: box_itself_title_content_image_name_and_sound_path[0].to_string(),
2901                    box_size,
2902                    box_title_name: format!(
2903                        "MessageBox{}",
2904                        box_itself_title_content_image_name_and_sound_path[1]
2905                    ),
2906                    box_content_name: format!(
2907                        "MessageBox{}",
2908                        box_itself_title_content_image_name_and_sound_path[2]
2909                    ),
2910                    box_image_name: format!(
2911                        "MessageBox{}",
2912                        box_itself_title_content_image_name_and_sound_path[3]
2913                    ),
2914                    box_keep_existing,
2915                    box_existing_time,
2916                    box_exist: true,
2917                    box_speed: box_normal_and_restore_speed[0],
2918                    box_restore_speed: box_normal_and_restore_speed[1],
2919                    box_memory_offset: 0_f32,
2920                }));
2921            if !box_keep_existing {
2922                self.add_split_time(
2923                    &format!(
2924                        "MessageBox{}",
2925                        box_itself_title_content_image_name_and_sound_path[0]
2926                    ),
2927                    false,
2928                );
2929            };
2930            self.add_split_time(
2931                &format!(
2932                    "MessageBox{}Animation",
2933                    box_itself_title_content_image_name_and_sound_path[0]
2934                ),
2935                false,
2936            );
2937            self.add_rect(
2938                &format!(
2939                    "MessageBox{}",
2940                    box_itself_title_content_image_name_and_sound_path[0]
2941                ),
2942                [0_f32, 0_f32, box_size[0], box_size[1], 20_f32],
2943                [1, 1, 0, 1],
2944                [true, true, false, false],
2945                [100, 100, 100, 125, 240, 255, 255, 255],
2946                0.0,
2947            );
2948            self.add_image(
2949                &format!(
2950                    "MessageBox{}Close",
2951                    box_itself_title_content_image_name_and_sound_path[0]
2952                ),
2953                [0_f32, 0_f32, 30_f32, 30_f32],
2954                [0, 0, 0, 0],
2955                [false, false, true, true, false],
2956                [255, 0, 0, 0, 0],
2957                "CloseMessageBox",
2958            );
2959            self.add_switch(
2960                [
2961                    &format!(
2962                        "MessageBox{}Close",
2963                        box_itself_title_content_image_name_and_sound_path[0]
2964                    ),
2965                    &format!(
2966                        "MessageBox{}Close",
2967                        box_itself_title_content_image_name_and_sound_path[0]
2968                    ),
2969                    "",
2970                    box_itself_title_content_image_name_and_sound_path[4],
2971                ],
2972                vec![
2973                    SwitchData {
2974                        texture: "CloseMessageBox".to_string(),
2975                        color: [255, 255, 255, 0],
2976                        text: String::new(),
2977                        hint_text: String::new(),
2978                    },
2979                    SwitchData {
2980                        texture: "CloseMessageBox".to_string(),
2981                        color: [180, 180, 180, 200],
2982                        text: String::new(),
2983                        hint_text: String::new(),
2984                    },
2985                    SwitchData {
2986                        texture: "CloseMessageBox".to_string(),
2987                        color: [255, 255, 255, 200],
2988                        text: String::new(),
2989                        hint_text: String::new(),
2990                    },
2991                    SwitchData {
2992                        texture: "CloseMessageBox".to_string(),
2993                        color: [180, 180, 180, 200],
2994                        text: String::new(),
2995                        hint_text: String::new(),
2996                    },
2997                ],
2998                [false, true, true],
2999                2,
3000                vec![SwitchClickAction {
3001                    click_method: PointerButton::Primary,
3002                    action: true,
3003                }],
3004            );
3005        } else {
3006            self.problem_report(
3007                RustConstructorError::MessageBoxAlreadyExists {
3008                    message_box_name: box_itself_title_content_image_name_and_sound_path[0]
3009                        .to_string(),
3010                },
3011                SeverityLevel::SevereWarning,
3012            );
3013        };
3014    }
3015
3016    /// 处理所有已添加的消息框资源。
3017    pub fn message_box_display(&mut self, ctx: &egui::Context, ui: &mut Ui) {
3018        let mut offset = 0_f32;
3019        let mut delete_count = 0;
3020        let mut index_list = Vec::new();
3021        for i in 0..self.rust_constructor_resource.len() {
3022            if let RCR::MessageBox(_) = self.rust_constructor_resource[i] {
3023                index_list.push(i);
3024            };
3025        }
3026        for u in 0..index_list.len() {
3027            let mut deleted = false;
3028            let i = u - delete_count;
3029            if let RCR::MessageBox(mut mb) = self.rust_constructor_resource[index_list[i]].clone() {
3030                if let Ok(id1) = self.get_resource_index("Image", &mb.box_image_name) {
3031                    if let RCR::Image(mut im1) = self.rust_constructor_resource[id1].clone() {
3032                        if let Ok(id2) =
3033                            self.get_resource_index("CustomRect", &format!("MessageBox{}", mb.name))
3034                        {
3035                            if let RCR::CustomRect(mut cr) =
3036                                self.rust_constructor_resource[id2].clone()
3037                            {
3038                                if let Ok(id3) = self.get_resource_index("Text", &mb.box_title_name)
3039                                {
3040                                    if let RCR::Text(mut t1) =
3041                                        self.rust_constructor_resource[id3].clone()
3042                                    {
3043                                        if let Ok(id4) =
3044                                            self.get_resource_index("Text", &mb.box_content_name)
3045                                        {
3046                                            if let RCR::Text(mut t2) =
3047                                                self.rust_constructor_resource[id4].clone()
3048                                            {
3049                                                if let Ok(id5) = self.get_resource_index(
3050                                                    "Switch",
3051                                                    &format!("MessageBox{}Close", mb.name),
3052                                                ) {
3053                                                    if let RCR::Switch(mut s) =
3054                                                        self.rust_constructor_resource[id5].clone()
3055                                                    {
3056                                                        if let Ok(id6) = self.get_resource_index(
3057                                                            "Image",
3058                                                            &format!("MessageBox{}Close", mb.name),
3059                                                        ) {
3060                                                            if let RCR::Image(mut im2) = self
3061                                                                .rust_constructor_resource[id6]
3062                                                                .clone()
3063                                                            {
3064                                                                if mb.box_size[1]
3065                                                                    < self.get_text_size(&mb.box_title_name.clone(), ui).unwrap()[1]
3066                                                                        + self.get_text_size(&mb.box_content_name.clone(), ui).unwrap()
3067                                                                            [1]
3068                                                                        + 10_f32
3069                                                                {
3070                                                                    mb.box_size[1] = self
3071                                                                        .get_text_size(&mb.box_title_name.clone(), ui).unwrap()[1]
3072                                                                        + self
3073                                                                            .get_text_size(&mb.box_content_name.clone(), ui).unwrap()
3074                                                                            [1]
3075                                                                        + 10_f32;
3076                                                                    cr.size[1] = mb.box_size[1];
3077                                                                    im1.image_size = [
3078                                                                        mb.box_size[1] - 15_f32,
3079                                                                        mb.box_size[1] - 15_f32,
3080                                                                    ];
3081                                                                    t1.wrap_width = mb.box_size[0]
3082                                                                        - mb.box_size[1]
3083                                                                        + 5_f32;
3084                                                                    t2.wrap_width = mb.box_size[0]
3085                                                                        - mb.box_size[1]
3086                                                                        + 5_f32;
3087                                                                };
3088                                                                if self.timer.total_time
3089                                                                    - self
3090                                                                        .split_time(&format!(
3091                                                                            "MessageBox{}Animation",
3092                                                                            mb.name
3093                                                                        ))
3094                                                                        .unwrap()[1]
3095                                                                    >= self.vertrefresh
3096                                                                {
3097                                                                    self.add_split_time(
3098                                                                        &format!(
3099                                                                            "MessageBox{}Animation",
3100                                                                            mb.name
3101                                                                        ),
3102                                                                        true,
3103                                                                    );
3104                                                                    if offset
3105                                                                        != mb.box_memory_offset
3106                                                                    {
3107                                                                        if mb.box_memory_offset
3108                                                                            < offset
3109                                                                        {
3110                                                                            if mb.box_memory_offset
3111                                                                                + mb.box_restore_speed
3112                                                                                >= offset
3113                                                                            {
3114                                                                                mb.box_memory_offset = offset;
3115                                                                            } else {
3116                                                                                mb.box_memory_offset +=
3117                                                                                    mb.box_restore_speed;
3118                                                                            };
3119                                                                        } else if mb
3120                                                                            .box_memory_offset
3121                                                                            - mb.box_restore_speed
3122                                                                            <= offset
3123                                                                        {
3124                                                                            mb.box_memory_offset =
3125                                                                                offset;
3126                                                                        } else {
3127                                                                            mb.box_memory_offset -=
3128                                                                                mb.box_restore_speed;
3129                                                                        };
3130                                                                    };
3131                                                                    if cr.origin_position[0]
3132                                                                        != -mb.box_size[0] - 5_f32
3133                                                                    {
3134                                                                        if mb.box_exist {
3135                                                                            if cr.origin_position[0]
3136                                                                                - mb.box_speed
3137                                                                                <= -mb.box_size[0]
3138                                                                                    - 5_f32
3139                                                                            {
3140                                                                                cr.origin_position[0] =
3141                                                                                    -mb.box_size[0] - 5_f32;
3142                                                                                if self.check_resource_exists("SplitTime", &format!("MessageBox{}", mb.name)) {
3143                                                                                    self.add_split_time(
3144                                                                                        &format!("MessageBox{}", mb.name),
3145                                                                                        true,
3146                                                                                    );
3147                                                                                };
3148                                                                            } else {
3149                                                                                cr.origin_position[0] -=
3150                                                                                    mb.box_speed;
3151                                                                            };
3152                                                                        } else if cr.origin_position
3153                                                                            [0]
3154                                                                            + mb.box_speed
3155                                                                            >= 15_f32
3156                                                                        {
3157                                                                            cr.origin_position[0] =
3158                                                                                15_f32;
3159                                                                            delete_count += 1;
3160                                                                            deleted = true;
3161                                                                        } else {
3162                                                                            cr.origin_position
3163                                                                                [0] += mb.box_speed;
3164                                                                        };
3165                                                                    };
3166                                                                };
3167                                                                cr.origin_position[1] =
3168                                                                    mb.box_memory_offset + 20_f32;
3169                                                                im1.origin_position = [
3170                                                                    cr.origin_position[0] + 5_f32,
3171                                                                    cr.origin_position[1]
3172                                                                        + mb.box_size[1] / 2_f32,
3173                                                                ];
3174                                                                t1.origin_position = [
3175                                                                    im1.origin_position[0]
3176                                                                        + im1.image_size[0]
3177                                                                        + 5_f32,
3178                                                                    cr.origin_position[1] + 5_f32,
3179                                                                ];
3180                                                                t2.origin_position = [
3181                                                                    im1.origin_position[0]
3182                                                                        + im1.image_size[0]
3183                                                                        + 5_f32,
3184                                                                    t1.origin_position[1]
3185                                                                        + self
3186                                                                            .get_text_size(
3187                                                                                &mb.box_title_name
3188                                                                                    .clone(),
3189                                                                                ui,
3190                                                                            )
3191                                                                            .unwrap()[1],
3192                                                                ];
3193                                                                im2.origin_position = cr.position;
3194                                                                if !mb.box_keep_existing
3195                                                                    && self.timer.total_time
3196                                                                        - self
3197                                                                            .split_time(&format!(
3198                                                                                "MessageBox{}",
3199                                                                                mb.name
3200                                                                            ))
3201                                                                            .unwrap()[1]
3202                                                                        >= mb.box_existing_time
3203                                                                    && cr.origin_position[0]
3204                                                                        == -mb.box_size[0] - 5_f32
3205                                                                {
3206                                                                    mb.box_exist = false;
3207                                                                    if cr.origin_position[0]
3208                                                                        + mb.box_speed
3209                                                                        >= 15_f32
3210                                                                    {
3211                                                                        cr.origin_position[0] =
3212                                                                            15_f32;
3213                                                                    } else {
3214                                                                        cr.origin_position[0] +=
3215                                                                            mb.box_speed;
3216                                                                    };
3217                                                                };
3218                                                                if let Some(mouse_pos) =
3219                                                                    ui.input(|i| {
3220                                                                        i.pointer.hover_pos()
3221                                                                    })
3222                                                                {
3223                                                                    let rect =
3224                                                                        egui::Rect::from_min_size(
3225                                                                            Pos2 {
3226                                                                                x: im2
3227                                                                                    .image_position
3228                                                                                    [0],
3229                                                                                y: im2
3230                                                                                    .image_position
3231                                                                                    [1],
3232                                                                            },
3233                                                                            Vec2 {
3234                                                                                x: cr.size[0]
3235                                                                                    + 25_f32,
3236                                                                                y: cr.size[1]
3237                                                                                    + 25_f32,
3238                                                                            },
3239                                                                        );
3240                                                                    if rect.contains(mouse_pos) {
3241                                                                        s.appearance[0].color[3] =
3242                                                                            200;
3243                                                                    } else {
3244                                                                        s.appearance[0].color[3] =
3245                                                                            0;
3246                                                                    };
3247                                                                };
3248                                                                self.rust_constructor_resource
3249                                                                    [index_list[i]] =
3250                                                                    RCR::MessageBox(mb.clone());
3251                                                                self.rust_constructor_resource
3252                                                                    [id1] = RCR::Image(im1.clone());
3253                                                                self.rust_constructor_resource
3254                                                                    [id2] =
3255                                                                    RCR::CustomRect(cr.clone());
3256                                                                self.rust_constructor_resource
3257                                                                    [id3] = RCR::Text(t1.clone());
3258                                                                self.rust_constructor_resource
3259                                                                    [id4] = RCR::Text(t2.clone());
3260                                                                self.rust_constructor_resource
3261                                                                    [id5] = RCR::Switch(s.clone());
3262                                                                self.rust_constructor_resource
3263                                                                    [id6] = RCR::Image(im2.clone());
3264                                                                self.rect(
3265                                                                    ui,
3266                                                                    &format!(
3267                                                                        "MessageBox{}",
3268                                                                        mb.name
3269                                                                    ),
3270                                                                    ctx,
3271                                                                );
3272                                                                self.image(
3273                                                                    ui,
3274                                                                    &mb.box_image_name.clone(),
3275                                                                    ctx,
3276                                                                );
3277                                                                self.text(
3278                                                                    ui,
3279                                                                    &t1.name.clone(),
3280                                                                    ctx,
3281                                                                );
3282                                                                self.text(
3283                                                                    ui,
3284                                                                    &t2.name.clone(),
3285                                                                    ctx,
3286                                                                );
3287                                                                if self
3288                                                                    .switch(
3289                                                                        &format!(
3290                                                                            "MessageBox{}Close",
3291                                                                            mb.name
3292                                                                        ),
3293                                                                        ui,
3294                                                                        ctx,
3295                                                                        s.state == 0
3296                                                                            && mb.box_exist,
3297                                                                        true,
3298                                                                    )
3299                                                                    .unwrap()[0]
3300                                                                    == 0
3301                                                                {
3302                                                                    mb.box_exist = false;
3303                                                                    if cr.origin_position[0]
3304                                                                        + mb.box_speed
3305                                                                        >= 15_f32
3306                                                                    {
3307                                                                        cr.origin_position[0] =
3308                                                                            15_f32;
3309                                                                    } else {
3310                                                                        cr.origin_position[0] +=
3311                                                                            mb.box_speed;
3312                                                                    };
3313                                                                    self.rust_constructor_resource[id2] = RCR::CustomRect(cr.clone());
3314                                                                    self.rust_constructor_resource[index_list[i]] = RCR::MessageBox(mb.clone());
3315                                                                };
3316                                                                if deleted {
3317                                                                    if let Ok(id) = self
3318                                                                        .get_resource_index(
3319                                                                            "Image",
3320                                                                            &mb.box_image_name,
3321                                                                        )
3322                                                                    {
3323                                                                        self.rust_constructor_resource.remove(id);
3324                                                                    };
3325                                                                    if let Ok(id) = self
3326                                                                        .get_resource_index(
3327                                                                            "CustomRect",
3328                                                                            &format!(
3329                                                                                "MessageBox{}",
3330                                                                                mb.name
3331                                                                            ),
3332                                                                        )
3333                                                                    {
3334                                                                        self.rust_constructor_resource.remove(id);
3335                                                                    };
3336                                                                    if let Ok(id) = self
3337                                                                        .get_resource_index(
3338                                                                            "Text",
3339                                                                            &mb.box_title_name,
3340                                                                        )
3341                                                                    {
3342                                                                        self.rust_constructor_resource.remove(id);
3343                                                                    };
3344                                                                    if let Ok(id) = self
3345                                                                        .get_resource_index(
3346                                                                            "Text",
3347                                                                            &mb.box_content_name,
3348                                                                        )
3349                                                                    {
3350                                                                        self.rust_constructor_resource.remove(id);
3351                                                                    };
3352                                                                    if let Ok(id) = self
3353                                                                        .get_resource_index(
3354                                                                            "Switch",
3355                                                                            &format!(
3356                                                                                "MessageBox{}Close",
3357                                                                                mb.name
3358                                                                            ),
3359                                                                        )
3360                                                                    {
3361                                                                        self.rust_constructor_resource.remove(id);
3362                                                                    };
3363                                                                    if let Ok(id) = self
3364                                                                        .get_resource_index(
3365                                                                            "Image",
3366                                                                            &format!(
3367                                                                                "MessageBox{}Close",
3368                                                                                mb.name
3369                                                                            ),
3370                                                                        )
3371                                                                    {
3372                                                                        self.rust_constructor_resource.remove(id);
3373                                                                    };
3374                                                                    if let Ok(id) = self.get_resource_index("SplitTime", &format!("MessageBox{}Animation", mb.name)) {
3375                                                                        self.rust_constructor_resource.remove(id);
3376                                                                    };
3377                                                                    if !mb.box_keep_existing {
3378                                                                        if let Ok(id) = self
3379                                                                            .get_resource_index(
3380                                                                                "SplitTime",
3381                                                                                &format!(
3382                                                                                    "MessageBox{}",
3383                                                                                    mb.name
3384                                                                                ),
3385                                                                            )
3386                                                                        {
3387                                                                            self.rust_constructor_resource.remove(id);
3388                                                                        };
3389                                                                    };
3390                                                                    if let Ok(id) = self
3391                                                                        .get_resource_index(
3392                                                                            "MessageBox",
3393                                                                            &mb.name,
3394                                                                        )
3395                                                                    {
3396                                                                        self.rust_constructor_resource.remove(id);
3397                                                                    };
3398                                                                } else {
3399                                                                    offset +=
3400                                                                        mb.box_size[1] + 15_f32;
3401                                                                };
3402                                                            };
3403                                                        };
3404                                                    };
3405                                                };
3406                                            };
3407                                        };
3408                                    };
3409                                };
3410                            };
3411                        };
3412                    };
3413                };
3414            };
3415        }
3416    }
3417
3418    /// 添加开关资源。
3419    pub fn add_switch(
3420        &mut self,
3421        name_switch_image_name_text_name_and_sound_path: [&str; 4],
3422        mut appearance: Vec<SwitchData>,
3423        enable_hover_click_image_and_use_overlay: [bool; 3],
3424        switch_amounts_state: u32,
3425        click_method: Vec<SwitchClickAction>,
3426    ) {
3427        let mut count = 1;
3428        if enable_hover_click_image_and_use_overlay[0] {
3429            count += 1;
3430        };
3431        if enable_hover_click_image_and_use_overlay[1] {
3432            count += 1;
3433        };
3434        if appearance.len() as u32 != count * switch_amounts_state {
3435            self.problem_report(
3436                RustConstructorError::SwitchAppearanceMismatch {
3437                    switch_name: name_switch_image_name_text_name_and_sound_path[0].to_string(),
3438                    differ: (count as i32 * switch_amounts_state as i32 - appearance.len() as i32)
3439                        .unsigned_abs(),
3440                },
3441                SeverityLevel::SevereWarning,
3442            );
3443            for _ in
3444                0..(count as i32 * switch_amounts_state as i32 - appearance.len() as i32) as usize
3445            {
3446                appearance.push(SwitchData {
3447                    texture: "Error".to_string(),
3448                    color: [255, 255, 255, 255],
3449                    text: String::new(),
3450                    hint_text: String::new(),
3451                });
3452            }
3453        };
3454        let mut text_origin_position = [0_f32, 0_f32];
3455        if let Ok(id) =
3456            self.get_resource_index("Image", name_switch_image_name_text_name_and_sound_path[1])
3457        {
3458            if let RCR::Image(mut im) = self.rust_constructor_resource[id].clone() {
3459                im.use_overlay_color = true;
3460                if self.check_resource_exists(
3461                    "Text",
3462                    name_switch_image_name_text_name_and_sound_path[2],
3463                ) {
3464                    if let Ok(id2) = self.get_resource_index(
3465                        "Text",
3466                        name_switch_image_name_text_name_and_sound_path[2],
3467                    ) {
3468                        if let RCR::Text(t) = &mut self.rust_constructor_resource[id2] {
3469                            t.center_display = [false, false, true, true];
3470                            t.x_grid = [0, 0];
3471                            t.y_grid = [0, 0];
3472                            text_origin_position = t.origin_position;
3473                        };
3474                    };
3475                };
3476                self.rust_constructor_resource[id] = RCR::Image(im);
3477            };
3478        };
3479        if !appearance.iter().any(|x| x.hint_text.is_empty())
3480        {
3481            self.add_text(
3482                [
3483                    &format!("{}Hint", name_switch_image_name_text_name_and_sound_path[0]),
3484                    "",
3485                    "Content",
3486                ],
3487                [0_f32, 0_f32, 25_f32, 300_f32, 10_f32],
3488                [255, 255, 255, 0, 0, 0, 0, 0],
3489                [true, true, false, false, true, false],
3490                [0, 0, 0, 0],
3491                vec![],
3492            );
3493            self.add_split_time(
3494                &format!(
3495                    "{}StartHoverTime",
3496                    name_switch_image_name_text_name_and_sound_path[0]
3497                ),
3498                false,
3499            );
3500            self.add_split_time(
3501                &format!(
3502                    "{}HintFadeAnimation",
3503                    name_switch_image_name_text_name_and_sound_path[0]
3504                ),
3505                false,
3506            );
3507        };
3508        self.rust_constructor_resource.push(RCR::Switch(Switch {
3509            discern_type: "Switch".to_string(),
3510            name: name_switch_image_name_text_name_and_sound_path[0].to_string(),
3511            appearance: appearance.clone(),
3512            switch_image_name: name_switch_image_name_text_name_and_sound_path[1].to_string(),
3513            enable_hover_click_image: [
3514                enable_hover_click_image_and_use_overlay[0],
3515                enable_hover_click_image_and_use_overlay[1],
3516            ],
3517            state: 0,
3518            click_method,
3519            last_time_hovered: false,
3520            last_time_clicked: false,
3521            last_time_clicked_index: 0,
3522            animation_count: count,
3523            hint_text_name: if !appearance
3524                .iter()
3525                .any(|x| x.hint_text.is_empty())
3526            {
3527                format!("{}Hint", name_switch_image_name_text_name_and_sound_path[0])
3528            } else {
3529                "".to_string()
3530            },
3531            text_name: name_switch_image_name_text_name_and_sound_path[2].to_string(),
3532            text_origin_position,
3533            sound_path: name_switch_image_name_text_name_and_sound_path[3].to_string(),
3534        }));
3535    }
3536
3537    /// 显示开关资源并返回点击方法和开关状态。
3538    pub fn switch(
3539        &mut self,
3540        name: &str,
3541        ui: &mut Ui,
3542        ctx: &egui::Context,
3543        enable: bool,
3544        play_sound: bool,
3545    ) -> Result<[usize; 2], RustConstructorError> {
3546        let mut activated = [5, 0];
3547        let mut appearance_count = 0;
3548        if let Ok(id) = self.get_resource_index("Switch", name) {
3549            if let RCR::Switch(mut s) = self.rust_constructor_resource[id].clone() {
3550                if let Ok(id2) = self.get_resource_index("Image", &s.switch_image_name.clone()) {
3551                    if let RCR::Image(mut im) = self.rust_constructor_resource[id2].clone() {
3552                        s.reg_render_resource(&mut self.render_resource_list);
3553                        let rect = Rect::from_min_size(
3554                            Pos2::new(im.image_position[0], im.image_position[1]),
3555                            Vec2::new(im.image_size[0], im.image_size[1]),
3556                        );
3557                        let mut hovered = false;
3558                        if enable {
3559                            if let Some(mouse_pos) = ui.input(|i| i.pointer.hover_pos()) {
3560                                // 判断是否在矩形内
3561                                if rect.contains(mouse_pos) {
3562                                    if !s.hint_text_name.is_empty() {
3563                                        if let Ok(id3) =
3564                                            self.get_resource_index("Text", &s.hint_text_name)
3565                                        {
3566                                            if let RCR::Text(mut t) =
3567                                                self.rust_constructor_resource[id3].clone()
3568                                            {
3569                                                if !s.last_time_hovered {
3570                                                    self.add_split_time(
3571                                                        &format!("{}StartHoverTime", s.name),
3572                                                        true,
3573                                                    );
3574                                                } else if self.timer.total_time
3575                                                    - self
3576                                                        .split_time(&format!(
3577                                                            "{}StartHoverTime",
3578                                                            s.name
3579                                                        ))
3580                                                        .unwrap()[1]
3581                                                    >= 2_f32
3582                                                    || t.rgba[3] != 0
3583                                                {
3584                                                    t.rgba[3] = 255;
3585                                                    t.origin_position = [mouse_pos.x, mouse_pos.y];
3586                                                };
3587                                                t.center_display[0] = mouse_pos.x + self
3588                                                        .get_text_size(&s.hint_text_name, ui)
3589                                                        .unwrap()[0]
3590                                                    <= ctx.available_rect().width();
3591                                                t.center_display[1] = mouse_pos.y
3592                                                    + self
3593                                                        .get_text_size(&s.hint_text_name, ui)
3594                                                        .unwrap()[1]
3595                                                    <= ctx.available_rect().height();
3596                                                self.rust_constructor_resource[id3] = RCR::Text(t);
3597                                            };
3598                                        };
3599                                    };
3600                                    hovered = true;
3601                                    let mut clicked = vec![];
3602                                    let mut active = false;
3603                                    for u in 0..s.click_method.len() as u32 {
3604                                        clicked.push(ui.input(|i| {
3605                                            i.pointer.button_down(
3606                                                s.click_method[u as usize].click_method,
3607                                            )
3608                                        }));
3609                                        if clicked[u as usize] {
3610                                            active = true;
3611                                            s.last_time_clicked_index = u as usize;
3612                                            break;
3613                                        };
3614                                    }
3615                                    if active {
3616                                        s.last_time_clicked = true;
3617                                        if s.enable_hover_click_image[1] {
3618                                            if s.enable_hover_click_image[0] {
3619                                                appearance_count = 2;
3620                                            } else {
3621                                                appearance_count = 1;
3622                                            };
3623                                        } else if !s.enable_hover_click_image[0] {
3624                                            appearance_count = 0;
3625                                        };
3626                                    } else {
3627                                        if s.last_time_clicked {
3628                                            if play_sound {
3629                                                general_click_feedback(&s.sound_path);
3630                                            };
3631                                            let mut count = 1;
3632                                            if s.enable_hover_click_image[0] {
3633                                                count += 1;
3634                                            };
3635                                            if s.enable_hover_click_image[1] {
3636                                                count += 1;
3637                                            };
3638                                            if s.click_method[s.last_time_clicked_index].action {
3639                                                if s.state < (s.appearance.len() / count - 1) as u32
3640                                                {
3641                                                    s.state += 1;
3642                                                } else {
3643                                                    s.state = 0;
3644                                                };
3645                                            };
3646                                            activated[0] = s.last_time_clicked_index;
3647                                            s.last_time_clicked = false;
3648                                        };
3649                                        if s.enable_hover_click_image[0] {
3650                                            appearance_count = 1;
3651                                        } else {
3652                                            appearance_count = 0;
3653                                        };
3654                                    };
3655                                } else {
3656                                    s.last_time_clicked = false;
3657                                    appearance_count = 0;
3658                                };
3659                            } else {
3660                                s.last_time_clicked = false;
3661                                appearance_count = 0;
3662                            };
3663                        } else {
3664                            s.last_time_clicked = false;
3665                            appearance_count = 0;
3666                        };
3667                        if !hovered && !s.hint_text_name.is_empty() {
3668                            if s.last_time_hovered {
3669                                self.add_split_time(&format!("{}HintFadeAnimation", s.name), true);
3670                            };
3671                            if let Ok(id3) = self.get_resource_index("Text", &s.hint_text_name) {
3672                                if let RCR::Text(mut t) =
3673                                    self.rust_constructor_resource[id3].clone()
3674                                {
3675                                    if self.timer.total_time
3676                                        - self
3677                                            .split_time(&format!("{}HintFadeAnimation", s.name))
3678                                            .unwrap()[1]
3679                                        >= self.vertrefresh
3680                                    {
3681                                        t.rgba[3] = t.rgba[3].saturating_sub(1);
3682                                    };
3683                                    self.rust_constructor_resource[id3] = RCR::Text(t);
3684                                };
3685                            };
3686                        };
3687                        im.overlay_color = s.appearance
3688                            [(s.state * s.animation_count + appearance_count) as usize]
3689                            .color;
3690                        if let Ok(id4) = self.get_resource_index(
3691                            "ImageTexture",
3692                            &s.appearance
3693                                [(s.state * s.animation_count + appearance_count) as usize]
3694                                .texture
3695                                .clone(),
3696                        ) {
3697                            if let RCR::ImageTexture(it) =
3698                                self.rust_constructor_resource[id4].clone()
3699                            {
3700                                im.image_texture = it.texture.clone();
3701                            };
3702                        };
3703                        if !s.hint_text_name.is_empty() {
3704                            if let Ok(id3) = self.get_resource_index("Text", &s.hint_text_name) {
3705                                if let RCR::Text(mut t) =
3706                                    self.rust_constructor_resource[id3].clone()
3707                                {
3708                                    t.background_rgb[3] = t.rgba[3];
3709                                    t.text_content = s.appearance
3710                                        [(s.state * s.animation_count + appearance_count) as usize]
3711                                        .hint_text
3712                                        .clone();
3713                                    self.rust_constructor_resource[id3] = RCR::Text(t);
3714                                };
3715                            };
3716                        };
3717                        s.last_time_hovered = hovered;
3718                        activated[1] = s.state as usize;
3719                        self.rust_constructor_resource[id] = RCR::Switch(s.clone());
3720                        self.rust_constructor_resource[id2] = RCR::Image(im.clone());
3721                        self.image(ui, &s.switch_image_name.clone(), ctx);
3722                        if self.check_resource_exists("Text", &s.text_name) {
3723                            if let Ok(id4) = self.get_resource_index("Text", &s.text_name) {
3724                                if let RCR::Text(mut t2) =
3725                                    self.rust_constructor_resource[id4].clone()
3726                                {
3727                                    t2.origin_position = [
3728                                        im.image_position[0] + s.text_origin_position[0],
3729                                        im.image_position[1] + s.text_origin_position[1],
3730                                    ];
3731                                    t2.text_content = s.appearance
3732                                        [(s.state * s.animation_count + appearance_count) as usize]
3733                                        .text
3734                                        .clone();
3735                                    self.rust_constructor_resource[id4] = RCR::Text(t2);
3736                                };
3737                            };
3738                            self.text(ui, &s.text_name, ctx);
3739                        };
3740                        if self.check_resource_exists("Text", &s.hint_text_name) {
3741                            self.text(ui, &s.hint_text_name, ctx);
3742                        };
3743                        Ok(activated)
3744                    } else {
3745                        // 一般情况下不会触发。
3746                        Err(RustConstructorError::ImageNotFound {
3747                            image_name: s.switch_image_name,
3748                        })
3749                    }
3750                } else {
3751                    self.problem_report(
3752                        RustConstructorError::ImageNotFound {
3753                            image_name: name.to_string(),
3754                        },
3755                        SeverityLevel::SevereWarning,
3756                    );
3757                    Err(RustConstructorError::ImageNotFound {
3758                        image_name: s.switch_image_name,
3759                    })
3760                }
3761            } else {
3762                // 一般情况下不会触发。
3763                Err(RustConstructorError::SwitchNotFound {
3764                    switch_name: name.to_string(),
3765                })
3766            }
3767        } else {
3768            self.problem_report(
3769                RustConstructorError::SwitchNotFound {
3770                    switch_name: name.to_string(),
3771                },
3772                SeverityLevel::SevereWarning,
3773            );
3774            Err(RustConstructorError::SwitchNotFound {
3775                switch_name: name.to_string(),
3776            })
3777        }
3778    }
3779}