Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
7356 lines (6374 loc) · 290 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
7356 lines (6374 loc) · 290 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// MultiFlash TOOL - Main Window
// 主窗口 | メインウィンドウ | 메인 윈도우 | Ventana Principal | Главное окно
// ============================================================================
// [EN] Main application window with multi-platform flash support
// Qualcomm EDL / MediaTek BROM / Unisoc SPRD / ADB Fastboot
// [中文] 主应用程序窗口,支持多平台刷机
// 高通 EDL / 联发科 BROM / 展讯 SPRD / ADB Fastboot
// [日本語] マルチプラットフォームフラッシュをサポートするメインアプリケーションウィンドウ
// Qualcomm EDL / MediaTek BROM / Unisoc SPRD / ADB Fastboot
// [한국어] 멀티 플랫폼 플래시를 지원하는 메인 애플리케이션 창
// 퀄컴 EDL / 미디어텍 BROM / 유니속 SPRD / ADB Fastboot
// [Español] Ventana principal de la aplicación con soporte multi-plataforma
// Qualcomm EDL / MediaTek BROM / Unisoc SPRD / ADB Fastboot
// [Русский] Главное окно приложения с поддержкой мульти-платформы
// Qualcomm EDL / MediaTek BROM / Unisoc SPRD / ADB Fastboot
// ============================================================================
// GitHub: https://github.com/xiriovo/edlormtk
// Contact: QQ 1708298587 | Email: 1708298587@qq.com
// License: MIT
// ============================================================================
using System.Collections.ObjectModel;
using System.IO;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using tools.Dialogs;
using tools.Modules.Common;
using tools.Modules.Qualcomm;
using tools.Modules.MTK;
using tools.Modules.Unisoc;
using tools.Modules.Unisoc.Models;
namespace tools
{
/// <summary>
/// Main Window - Transparent themed with custom drag support
/// 主窗口 - 透明主题,支持自定义拖拽
/// メインウィンドウ - 透明テーマ、カスタムドラッグサポート
/// 메인 윈도우 - 투명 테마, 커스텀 드래그 지원
/// </summary>
public partial class MainWindow : Window
{
// 多个图片API - 随机选择加载,减少服务器压力
private static readonly string[] ImageApis = new[]
{
"https://www.dmoe.cc/random.php", // 樱花动漫 (最快)
"http://www.98qy.com/sjbz/api.php", // 98轻云二次元
"https://t.alcy.cc/pc", // 二次元PC横图
"https://t.alcy.cc/fj", // 风景横图
"https://www.loliapi.com/acg/pc", // Loli API
};
// 随机数生成器
private static readonly Random _random = new();
// HTTP客户端 - 禁用自动重定向,手动处理混合协议重定向
private static readonly HttpClient _httpClient;
static MainWindow()
{
var handler = new HttpClientHandler
{
AllowAutoRedirect = false, // ⚠️ 禁用自动重定向,手动处理 HTTPS→HTTP
AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(15)
};
// 模拟浏览器请求
_httpClient.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
_httpClient.DefaultRequestHeaders.Add("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
_httpClient.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
}
// 高通 UI 服务
private QualcommUIService? _qcService;
private CancellationTokenSource? _operationCts;
// 设备状态管理器
private DeviceStateManager? _deviceStateManager;
// MTK UI 服务
private MtkUIService? _mtkService;
private CancellationTokenSource? _mtkOperationCts;
// 展讯 (Unisoc) UI 服务
private UnisocUIService? _sprdService;
private CancellationTokenSource? _sprdOperationCts;
// ADB/Fastboot 取消令牌
private CancellationTokenSource? _fastbootOperationCts;
public MainWindow()
{
InitializeComponent();
// 初始化日志
InitializeLog();
InitializeMtkLog();
InitializeSprdLog();
InitializeAdbLog();
// 初始化高通服务
InitializeQualcommService();
// 初始化 MTK 服务
InitializeMtkService();
// 初始化展讯服务
InitializeUnisocService();
// 监听窗口状态变化,更新最大化按钮图标
StateChanged += MainWindow_StateChanged;
// 窗口加载完成后加载背景图片
Loaded += MainWindow_Loaded;
// 窗口关闭时释放资源
Closing += MainWindow_Closing;
}
/// <summary>
/// 窗口关闭时释放资源
/// </summary>
private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
{
// 释放高通服务资源
_qcService?.Dispose();
_qcService = null;
// 释放 MTK 服务资源
_mtkService?.Dispose();
_mtkService = null;
// 释放展讯服务资源
_sprdService?.Dispose();
_sprdService = null;
}
/// <summary>
/// 初始化高通服务
/// </summary>
private void InitializeQualcommService()
{
_qcService = new QualcommUIService(
Dispatcher,
(msg, color) => AppendLog(msg, color),
(percent, status) => UpdateProgress((int)percent, status),
status => Dispatcher.Invoke(() => TxtProgressStatus.Text = status),
info => UpdateDeviceInfoUI(info)
);
// 设备事件
_qcService.DeviceArrived += port =>
{
// ⚠️ 不要自动检测状态!会消耗 Sahara Hello 包导致后续连接失败
// 只显示设备已连接,让用户手动操作
SetDeviceStatus(true, "Sahara 就绪", port);
AppendLog($"[设备] ✓ 9008 设备就绪,可以进行操作", "#10B981");
};
_qcService.DeviceRemoved += () =>
{
Dispatcher.Invoke(() =>
{
// 完整清空设备信息
SetDeviceStatus(false, "未连接", "---", "---", "---", "---", "---");
// 清空分区表
PartitionList.ItemsSource = null;
_allPartitions.Clear();
TxtPartitionCount.Text = "0 个分区";
TxtPartitionSearch.Text = "";
// 重置进度条
SetProgressState(ProgressState.Ready, "就绪", 0);
TxtTransferredSize.Text = "0 MB";
TxtElapsedTime.Text = "00:00";
TxtTransferSpeed.Text = "0 MB/s";
// 停止状态监控
_deviceStateManager?.StopMonitoring();
_deviceStateManager?.Dispose();
_deviceStateManager = null;
AppendLog("[设备] 设备已断开,UI 已重置", "#888888");
});
};
// 分区加载事件 - 直接绑定 PartitionInfo 支持双向绑定
_qcService.PartitionsLoaded += partitions =>
{
Dispatcher.Invoke(() =>
{
UpdatePartitionList(partitions);
AppendLog($"📋 已加载 {partitions.Count} 个分区", "#10B981");
});
};
// 传输进度事件 - 更新已传输字节数
_qcService.TransferProgress += (current, total) =>
{
UpdateTransferSize(current);
};
// 启动设备监听
_qcService.StartDeviceWatcher();
}
/// <summary>
/// 更新设备信息 UI
/// </summary>
private void UpdateDeviceInfoUI(QcDeviceInfo info)
{
Dispatcher.Invoke(() =>
{
// 厂商优先显示读取到的厂商,否则显示 PK Hash 推断的厂商
TxtDeviceVendor.Text = !string.IsNullOrEmpty(info.Manufacturer) ? info.Manufacturer : info.Vendor;
// 型号优先显示设备型号,否则显示芯片型号
TxtDeviceModel.Text = !string.IsNullOrEmpty(info.Model) ? info.Model : info.ChipName;
// OTA 版本
TxtDeviceOTA.Text = !string.IsNullOrEmpty(info.OtaVersion) ? info.OtaVersion : "---";
// SN 序列号
TxtDeviceSN.Text = !string.IsNullOrEmpty(info.Serial) ? info.Serial : "---";
// 端口
TxtDevicePort.Text = info.Port;
// 更新设备状态显示(显示设备名称或连接状态)
if (!string.IsNullOrEmpty(info.Model) && info.Model != "---")
{
TxtDeviceStatus.Text = info.Model;
}
});
}
/// <summary>
/// 自动检测设备协议状态
/// </summary>
private async Task DetectDeviceProtocolStateAsync(string port)
{
try
{
AppendLog($"[状态检测] 检测端口 {port} 协议状态...", "#3B82F6");
// 尝试打开端口进行状态检测
using var tempPort = new SerialPortManager();
tempPort.BaudRate = 3000000;
if (!tempPort.Open(port, discardBuffer: false))
{
AppendLog($"[状态检测] 无法打开端口 {port}", "#EF4444");
SetDeviceStatus(true, "端口错误", port);
return;
}
var detector = new DeviceStateDetector(tempPort, msg => AppendLog(msg, "#6B7280"));
var stateInfo = await detector.DetectStateAsync();
tempPort.Close();
// 更新 UI 显示
Dispatcher.Invoke(() =>
{
string stateText = DeviceStateDetector.GetStateDisplayText(stateInfo.State);
string stateColor = DeviceStateDetector.GetStateColor(stateInfo.State);
// 更新状态显示
SetDeviceStatus(true, stateText.Replace("📤 ", "").Replace("✅ ", "").Replace("🔧 ", ""), port);
// 根据状态显示建议
if (!string.IsNullOrEmpty(stateInfo.SuggestedAction))
{
AppendLog($"[建议] {stateInfo.SuggestedAction}", "#F59E0B");
}
});
// 根据状态采取自动措施
await HandleDeviceStateAsync(stateInfo, port);
}
catch (Exception ex)
{
AppendLog($"[状态检测] 异常: {ex.Message}", "#EF4444");
SetDeviceStatus(true, "检测失败", port);
}
}
/// <summary>
/// 根据设备状态采取自动措施
/// </summary>
private async Task HandleDeviceStateAsync(DeviceStateInfo stateInfo, string port)
{
switch (stateInfo.State)
{
case DeviceProtocolState.SaharaWaitingLoader:
// Sahara 模式 - 显示等待 Loader 状态
AppendLog($"[Sahara] 设备等待 Loader (版本 {stateInfo.SaharaVersion})", "#10B981");
if (stateInfo.Supports64Bit)
{
AppendLog("[Sahara] 支持 64 位传输", "#6B7280");
}
SetDeviceStatus(true, "Sahara 就绪", port);
break;
case DeviceProtocolState.FirehoseConfigured:
// Firehose 已配置 - 可以直接操作
AppendLog("[Firehose] 设备已配置,可以直接操作", "#10B981");
if (!string.IsNullOrEmpty(stateInfo.StorageType))
{
AppendLog($"[Firehose] 存储类型: {stateInfo.StorageType.ToUpper()}", "#6B7280");
}
SetDeviceStatus(true, "Firehose 就绪", port);
break;
case DeviceProtocolState.FirehoseNotConfigured:
// Firehose 未配置 - 提示用户需要配置
AppendLog("[Firehose] 设备未配置,需要发送 Configure 命令", "#F59E0B");
SetDeviceStatus(true, "需要配置", port);
break;
case DeviceProtocolState.FirehoseConfigureFailed:
// 配置失败 - 尝试自动恢复
AppendLog("[Firehose] 配置失败,尝试自动恢复...", "#EF4444");
// 可以在这里调用自动恢复逻辑
break;
case DeviceProtocolState.NoResponse:
// 无响应 - 提示用户检查连接
AppendLog("[警告] 设备无响应,请检查连接或重新进入 EDL 模式", "#EF4444");
SetDeviceStatus(true, "无响应", port);
break;
default:
SetDeviceStatus(true, "9008 就绪", port);
break;
}
}
#region 背景图片加载
/// <summary>
/// 窗口加载完成 (不再自动加载背景图片,需手动刷新)
/// </summary>
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
// 默认不加载背景图片,用户可点击刷新按钮手动加载
LoadingIndicator.Visibility = Visibility.Collapsed;
}
/// <summary>
/// 随机API加载 - 随机选择一个API,失败后尝试其他
/// </summary>
private async Task LoadBackgroundImageAsync()
{
// 显示加载指示器
LoadingIndicator.Visibility = Visibility.Visible;
LoadingText.Text = "正在加载背景图片...";
// 创建打乱顺序的API列表 (随机化)
var shuffledApis = ImageApis.OrderBy(_ => _random.Next()).ToList();
try
{
// 依次尝试每个API
for (int i = 0; i < shuffledApis.Count; i++)
{
var apiUrl = shuffledApis[i];
await Dispatcher.InvokeAsync(() =>
{
LoadingText.Text = $"正在尝试 API {i + 1}/{shuffledApis.Count}...";
});
var bitmap = await LoadImageFromApiAsync(apiUrl);
if (bitmap != null)
{
// 成功获取图片
await Dispatcher.InvokeAsync(() =>
{
BackgroundImage.Source = bitmap;
// 淡入动画
var fadeIn = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(500))
{
EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
};
BackgroundImage.BeginAnimation(OpacityProperty, fadeIn);
LoadingIndicator.Visibility = Visibility.Collapsed;
});
return;
}
}
// 所有API都失败了
await Dispatcher.InvokeAsync(() =>
{
LoadingText.Text = "所有图片源加载失败\n点击刷新按钮重试";
});
}
catch (Exception ex)
{
await Dispatcher.InvokeAsync(() =>
{
LoadingText.Text = $"加载失败: {ex.Message}\n点击刷新按钮重试";
});
}
}
/// <summary>
/// 从单个API加载图片 - 支持混合协议重定向 (HTTPS→HTTP→HTTPS)
/// </summary>
private async Task<BitmapImage?> LoadImageFromApiAsync(string apiUrl)
{
try
{
// 添加随机参数避免缓存
string url = $"{apiUrl}?t={DateTime.Now.Ticks}";
// 手动跟随重定向 (支持 HTTPS→HTTP 混合)
int redirectCount = 0;
const int maxRedirects = 10;
while (redirectCount < maxRedirects)
{
using var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
int statusCode = (int)response.StatusCode;
// 处理重定向 (301, 302, 303, 307, 308)
if (statusCode >= 300 && statusCode < 400 && response.Headers.Location != null)
{
var location = response.Headers.Location;
if (!location.IsAbsoluteUri)
{
location = new Uri(new Uri(url), location);
}
url = location.ToString();
redirectCount++;
continue;
}
// 非重定向响应
if (!response.IsSuccessStatusCode)
{
return null;
}
// 读取图片数据
var imageBytes = await response.Content.ReadAsByteArrayAsync();
if (imageBytes.Length < 1000)
{
// 数据太小,可能不是有效图片
return null;
}
// 创建BitmapImage
BitmapImage? bitmap = null;
await Dispatcher.InvokeAsync(() =>
{
bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = new MemoryStream(imageBytes);
bitmap.EndInit();
bitmap.Freeze();
});
return bitmap;
}
// 重定向次数过多
return null;
}
catch
{
// API失败,返回null让其他API继续
return null;
}
}
/// <summary>
/// 关于按钮点击 - 显示关于对话框
/// About button click - Show about dialog
/// </summary>
private void AboutButton_Click(object sender, RoutedEventArgs e)
{
var aboutDialog = new AboutDialog
{
Owner = this
};
aboutDialog.ShowDialog();
}
/// <summary>
/// Settings button click - Show settings dialog
/// 设置按钮点击 - 显示设置对话框
/// </summary>
private void SettingsButton_Click(object sender, RoutedEventArgs e)
{
var settingsDialog = new SettingsDialog
{
Owner = this
};
settingsDialog.ShowDialog();
}
#region 资源中心事件处理 / Resource Center Event Handlers
/// <summary>
/// 打开URL工具方法 / Open URL helper
/// </summary>
private void OpenUrl(string url)
{
try
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = url,
UseShellExecute = true
});
}
catch (Exception ex)
{
AppendLog($"无法打开链接: {ex.Message}", "#FF5252");
}
}
// ===== 驱动下载 =====
private void Resource_QcomDriver_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://gsmusbdriver.com/qualcomm-hs-usb-qdloader-9008");
AppendLog("📥 正在打开 Qualcomm QDLoader 9008 驱动下载页面...", "#00D4FF");
}
private void Resource_MtkDriver_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://gsmusbdriver.com/mediatek-vcom-usb-preloader-driver");
AppendLog("📥 正在打开 MediaTek VCOM/Preloader 驱动下载页面...", "#4CAF50");
}
private void Resource_UnisocDriver_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://gsmusbdriver.com/spd-unisoc-usb-driver");
AppendLog("📥 正在打开 Unisoc/Spreadtrum 驱动下载页面...", "#FF9800");
}
private void Resource_AdbDriver_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://developer.android.com/studio/run/win-usb");
AppendLog("📥 正在打开 Google USB Driver 下载页面...", "#2196F3");
}
// ===== 工具下载 =====
private void Resource_PlatformTools_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://developer.android.com/tools/releases/platform-tools");
AppendLog("🛠️ 正在打开 Android Platform Tools 下载页面...", "#2196F3");
}
private void Resource_QFIL_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://qfiltool.com/");
AppendLog("🛠️ 正在打开 QFIL Tool 下载页面...", "#00D4FF");
}
private void Resource_SPFlashTool_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://spflashtool.com/");
AppendLog("🛠️ 正在打开 SP Flash Tool 下载页面...", "#4CAF50");
}
private void Resource_ResearchDownload_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://unisoc.com/");
AppendLog("🛠️ 正在打开 Unisoc Research Download 页面...", "#FF9800");
}
// ===== 内置浏览器功能 =====
private bool _browserInitialized = false;
private const string BrowserHomePage = "https://www.xiriacg.top/";
private async void InitializeBrowser()
{
if (_browserInitialized) return;
try
{
await ResourceBrowser.EnsureCoreWebView2Async(null);
_browserInitialized = true;
// 拦截新窗口请求,在内置浏览器中打开
ResourceBrowser.CoreWebView2.NewWindowRequested += (s, args) =>
{
args.Handled = true;
NavigateBrowser(args.Uri);
};
// 隐藏加载提示,显示浏览器
BrowserLoadingPanel.Visibility = Visibility.Collapsed;
ResourceBrowser.Visibility = Visibility.Visible;
// 导航到首页
ResourceBrowser.CoreWebView2.Navigate(BrowserHomePage);
TxtBrowserUrl.Text = BrowserHomePage;
AppendLog("🌐 内置浏览器已初始化", "#00D4FF");
}
catch (Exception ex)
{
AppendLog($"❌ 浏览器初始化失败: {ex.Message}", "#FF5252");
}
}
private void NavigateBrowser(string url)
{
if (!_browserInitialized)
{
InitializeBrowser();
return;
}
if (!url.StartsWith("http://") && !url.StartsWith("https://"))
url = "https://" + url;
ResourceBrowser.CoreWebView2.Navigate(url);
TxtBrowserUrl.Text = url;
}
// 浏览器导航按钮
private void BrowserBack_Click(object sender, RoutedEventArgs e)
{
if (_browserInitialized && ResourceBrowser.CanGoBack)
ResourceBrowser.GoBack();
}
private void BrowserForward_Click(object sender, RoutedEventArgs e)
{
if (_browserInitialized && ResourceBrowser.CanGoForward)
ResourceBrowser.GoForward();
}
private void BrowserRefresh_Click(object sender, RoutedEventArgs e)
{
if (_browserInitialized)
ResourceBrowser.Reload();
}
private void BrowserHome_Click(object sender, RoutedEventArgs e)
{
NavigateBrowser(BrowserHomePage);
}
private void BrowserGo_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(TxtBrowserUrl.Text))
NavigateBrowser(TxtBrowserUrl.Text);
}
private void BrowserUrl_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter)
BrowserGo_Click(sender, e);
}
// WebView2 事件
private void ResourceBrowser_NavigationStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs e)
{
TxtBrowserUrl.Text = e.Uri;
}
private void ResourceBrowser_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
{
if (!e.IsSuccess)
AppendLog($"⚠️ 页面加载失败", "#FFA000");
}
private void ResourceBrowser_SourceChanged(object sender, Microsoft.Web.WebView2.Core.CoreWebView2SourceChangedEventArgs e)
{
if (ResourceBrowser.Source != null)
TxtBrowserUrl.Text = ResourceBrowser.Source.ToString();
}
// ===== 教程文档 =====
private void Resource_XDA_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://xdaforums.com/");
AppendLog("📚 正在打开 XDA Developers 论坛...", "#F57C00");
}
private void Resource_GitHub_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://github.com/xiriovo/edlormtk");
AppendLog("📚 正在打开项目 GitHub 页面...", "#333333");
}
private void Resource_Wiki_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://github.com/xiriovo/edlormtk/wiki");
AppendLog("📚 正在打开项目 Wiki 文档...", "#4CAF50");
}
private void Resource_Telegram_Click(object sender, RoutedEventArgs e)
{
OpenUrl("https://t.me/multiflash_tool");
AppendLog("📚 正在打开 Telegram 交流群...", "#0088CC");
}
#endregion
/// <summary>
/// 刷新背景图片按钮点击
/// </summary>
private async void RefreshButton_Click(object sender, RoutedEventArgs e)
{
// 先淡出当前图片
var fadeOut = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(200));
BackgroundImage.BeginAnimation(OpacityProperty, fadeOut);
await Task.Delay(200);
await LoadBackgroundImageAsync();
}
#endregion
#region 二次元点击效果 (性能优化版)
// 粒子符号集合 - 轻量文本符号 (丰富版)
private static readonly string[] ParticleSymbols = new[]
{
// 星星
"✦", "✧", "★", "☆", "⭐", "✡", "✪", "✫", "✬", "✭", "✮", "✯", "⁂", "⁎", "⁑",
// 爱心
"❤", "♡", "♥", "❥", "❣", "💕", "💗", "💖", "💘", "💝",
// 花朵
"✿", "❀", "❁", "✾", "❃", "❋", "✻", "✼", "❊", "🌸", "🌺", "🌼",
// 音符
"♪", "♫", "♬", "♩", "🎵", "🎶",
// 几何
"◇", "◆", "○", "●", "◎", "◉", "△", "▽", "☾", "☽",
// 闪光
"✨", "💫", "🌟", "⚡", "✴", "✵", "❇", "✳",
// 可爱
"🎀", "🍀", "🌈", "☀", "🌙", "💎", "🔮", "🍭", "🍬", "🧸"
};
// 二次元风格文字 - 随机显示
private static readonly string[] ParticleTexts = new[]
{
// 日语可爱词
"かわいい", "すごい", "やった", "きらきら", "ふわふわ", "わくわく",
"ドキドキ", "にゃん", "うわぁ", "えへへ", "やばい", "最高",
"大好き", "嬉しい", "幸せ", "素敵", "綺麗", "天才",
// 英文萌词
"Love", "Cute", "Wow", "Yeah", "Nice", "Cool", "Great",
"OwO", "UwU", "QwQ", "TwT", "AwA", "OvO", "OuO",
"Yay", "Woo", "Nya", "Meow", "Paw", "Hehe", "Hihi",
"Sweet", "Kawaii", "Sugoi", "Doki", "Moe", "Nyan",
// 颜文字风格
"(*´▽`*)", "(◕‿◕)", "٩(◕‿◕。)۶", "(≧▽≦)", "ヾ(≧▽≦*)o",
"(。♥‿♥。)", "(◍•ᴗ•◍)", "(✿◠‿◠)", "٩(๑❛ᴗ❛๑)۶",
"(●'◡'●)", "(◠‿◠)", "(*≧ω≦)", "(´▽`ʃ♡ƪ)",
"ლ(╹◡╹ლ)", "(灬ºωº灬)", "♪(´ε`)", "( •̀ ω •́ )✧"
};
// 预编译的粒子颜色画刷 (避免每次创建新对象)
private static readonly System.Windows.Media.SolidColorBrush[] ParticleBrushes = InitParticleBrushes();
// 性能限制
private const int MaxParticlesOnScreen = 50; // 屏幕上最大粒子数
private const int ParticlesPerClick = 6; // 每次点击粒子数 (减少)
private DateTime _lastParticleClickTime = DateTime.MinValue;
private const int ClickThrottleMs = 50; // 点击节流 (毫秒)
/// <summary>
/// 初始化预编译的粒子画刷
/// </summary>
private static System.Windows.Media.SolidColorBrush[] InitParticleBrushes()
{
var colors = new[]
{
"#FF69B4", "#FFB6C1", "#DDA0DD", "#87CEEB", "#98FB98",
"#FFD700", "#FF6B6B", "#A8E6CF", "#74B9FF", "#FDA7DF"
};
return colors.Select(c =>
{
var brush = new System.Windows.Media.SolidColorBrush(
(System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(c));
brush.Freeze(); // 冻结以提高性能
return brush;
}).ToArray();
}
/// <summary>
/// 处理全局鼠标点击 - 生成粒子效果 (带节流)
/// </summary>
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnPreviewMouseLeftButtonDown(e);
// 节流检查 - 避免快速点击产生过多粒子
var now = DateTime.Now;
if ((now - _lastParticleClickTime).TotalMilliseconds < ClickThrottleMs)
return;
_lastParticleClickTime = now;
// 检查当前粒子数量
if (ClickEffectCanvas.Children.Count >= MaxParticlesOnScreen)
return;
// 获取点击位置
var position = e.GetPosition(ClickEffectCanvas);
// 生成粒子效果
CreateClickParticlesOptimized(position);
}
/// <summary>
/// 创建优化的粒子效果
/// </summary>
private void CreateClickParticlesOptimized(Point position)
{
for (int i = 0; i < ParticlesPerClick; i++)
{
CreateLightweightParticle(position);
}
}
/// <summary>
/// 创建轻量级粒子 (无阴影效果,使用合并动画)
/// </summary>
private void CreateLightweightParticle(Point origin)
{
// 使用预编译的画刷
var brush = ParticleBrushes[_random.Next(ParticleBrushes.Length)];
// 20% 概率显示文字,80% 概率显示符号
bool isText = _random.Next(100) < 20;
string content;
int fontSize;
if (isText)
{
content = ParticleTexts[_random.Next(ParticleTexts.Length)];
fontSize = _random.Next(10, 16); // 文字稍小一点
}
else
{
content = ParticleSymbols[_random.Next(ParticleSymbols.Length)];
fontSize = _random.Next(14, 24);
}
// 创建轻量粒子
var particle = new TextBlock
{
Text = content,
FontSize = fontSize,
FontWeight = isText ? FontWeights.Bold : FontWeights.Normal,
Foreground = brush,
RenderTransformOrigin = new Point(0.5, 0.5),
IsHitTestVisible = false,
Opacity = 0
// 移除 DropShadowEffect - 这是最大的性能瓶颈
};
// 简化的变换
var translateTransform = new System.Windows.Media.TranslateTransform(0, 0);
particle.RenderTransform = translateTransform;
// 设置位置
Canvas.SetLeft(particle, origin.X - 8);
Canvas.SetTop(particle, origin.Y - 8);
ClickEffectCanvas.Children.Add(particle);
// 计算飞散方向 (文字粒子飞得更高更慢)
double angle = _random.NextDouble() * Math.PI * 2;
double distance = isText ? _random.Next(30, 70) : _random.Next(40, 100);
double targetX = Math.Cos(angle) * distance;
double targetY = isText
? -_random.Next(60, 100) // 文字主要向上飞
: Math.Sin(angle) * distance - _random.Next(20, 50);
// 动画时长 (文字粒子停留更久便于阅读)
var duration = isText
? TimeSpan.FromMilliseconds(_random.Next(800, 1200))
: TimeSpan.FromMilliseconds(_random.Next(400, 800));
// 使用 Storyboard 合并动画 (更高效)
var storyboard = new System.Windows.Media.Animation.Storyboard();
// 位移 X
var moveX = new DoubleAnimation(0, targetX, duration)
{
EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
};
Storyboard.SetTarget(moveX, particle);
Storyboard.SetTargetProperty(moveX, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
storyboard.Children.Add(moveX);
// 位移 Y
var moveY = new DoubleAnimation(0, targetY, duration)
{
EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
};
Storyboard.SetTarget(moveY, particle);
Storyboard.SetTargetProperty(moveY, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.Y)"));
storyboard.Children.Add(moveY);
// 透明度 (淡入淡出)
var opacity = new DoubleAnimationUsingKeyFrames { Duration = duration };
opacity.KeyFrames.Add(new LinearDoubleKeyFrame(1, KeyTime.FromPercent(0.1)));
opacity.KeyFrames.Add(new LinearDoubleKeyFrame(1, KeyTime.FromPercent(0.5)));
opacity.KeyFrames.Add(new LinearDoubleKeyFrame(0, KeyTime.FromPercent(1)));
Storyboard.SetTarget(opacity, particle);
Storyboard.SetTargetProperty(opacity, new PropertyPath(OpacityProperty));
storyboard.Children.Add(opacity);
// 动画完成后移除粒子
storyboard.Completed += (s, e) =>
{
ClickEffectCanvas.Children.Remove(particle);
};
storyboard.Begin();
}
#endregion
#region 窗口状态管理
/// <summary>
/// 窗口状态变化时更新UI
/// </summary>
private void MainWindow_StateChanged(object? sender, EventArgs e)
{
if (WindowState == WindowState.Maximized)
{
// 最大化状态:显示还原图标,调整边距
MaximizeButton.Content = "\uE923"; // 还原图标
MaximizeButton.ToolTip = "向下还原";
MainBorder.Margin = new Thickness(7); // 防止最大化时内容超出屏幕
}
else
{
// 正常状态:显示最大化图标
MaximizeButton.Content = "\uE922"; // 最大化图标
MaximizeButton.ToolTip = "最大化";
MainBorder.Margin = new Thickness(0);
}
}
#endregion
#region 标题栏拖拽逻辑
private bool _isDoubleClick = false;
/// <summary>
/// 标题栏鼠标按下 - 处理拖拽和双击最大化
/// </summary>
private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
// 双击标题栏:切换最大化/还原
_isDoubleClick = true;
ToggleMaximize();
}
else
{
_isDoubleClick = false;
// 单击:开始拖拽
if (e.LeftButton == MouseButtonState.Pressed)
{
// 如果是最大化状态,先还原再拖拽
if (WindowState == WindowState.Maximized)
{
// 计算鼠标相对位置
var mousePos = e.GetPosition(this);
var screenPos = PointToScreen(mousePos);
// 还原窗口
WindowState = WindowState.Normal;
// 将窗口移动到鼠标位置
Left = screenPos.X - (ActualWidth / 2);
Top = screenPos.Y - 20;
}