-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmitray.ahk
More file actions
1693 lines (1404 loc) · 48.9 KB
/
Copy pathmitray.ahk
File metadata and controls
1693 lines (1404 loc) · 48.9 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
;==============================================================================
; MiTray
; AutoHotkey v2.0+
; Description: Manage mihomo core with system tray interface
;==============================================================================
;@Ahk2Exe-SetMainIcon %A_ScriptName~\.[^.]+$~.ico%
;@Ahk2Exe-AddResource %A_ScriptName~\.[^.]+$~_on.ico%, 201
;@Ahk2Exe-AddResource %A_ScriptName~\.[^.]+$~_off.ico%, 202
;@Ahk2Exe-SetName %A_ScriptName~\.[^.]+$~~%
;@Ahk2Exe-SetVersion 1.0.0
;@Ahk2Exe-ExeName %A_ScriptName~\.[^.]+$~.exe%
#Requires AutoHotkey v2.0+
#SingleInstance Force
Persistent
OnError((*) => -1) ; 捕获全局未处理异常,防止脚本意外退出
;==============================================================================
; Global Variables
;==============================================================================
; 获取脚本基础名称(不含扩展名),用于注册表和程序标识
global ScriptBaseName := RegExReplace(A_ScriptName, "\.[^.]+$", "")
global MihomoProcess := 0
global ConfigFile := A_ScriptDir "\config.ini"
global MihomoConfigFile := ""
global TempConfigFile := "" ; 将在读取配置后设置到核心目录
; Configuration
global CorePath := ""
global CoreProcessName := ""
global ConfigPath := ""
global ConfigURL := ""
global ActiveProfile := "default"
global Profiles := Map()
global APIController := ""
global APISecret := ""
global ProxyPort := ""
global WebUIPath := ""
global WebUIName := ""
global AutoStartCore := true
global AutoStartupDelaySec := 15
global TUNControl := "runtime" ; "runtime" 或 "file"
global DesiredTUNEnabled := false
; State
global IsProxyEnabled := false
global IsTUNEnabled := false
global IsAutoStartup := false
global AutoStartupLevel := "" ; "normal" 或 "admin"
global AutoStartupMenu := 0 ; 开机自启子菜单对象
global ProfileMenu := 0 ; mihomo 配置文件子菜单对象
global StatusCheckTimer := 0
global StatusTimerCallback := 0
global TrayIconState := ""
global TrayIconOnResourceId := 201
global TrayIconOffResourceId := 202
;==============================================================================
; Initialization
;==============================================================================
LoadConfig()
SetupTrayMenu()
CheckAutoStartup()
CheckSystemProxyState() ; Check current system proxy state
; Auto-start mihomo if configured
if (AutoStartCore) {
if (StartMihomo()) {
; Wait for core to be fully ready
Sleep(3000)
; Get initial TUN status from API before starting monitoring
GetTUNStatusFromAPI()
ApplyRuntimeTUNControl()
; Update menu to reflect current state
UpdateMenuStates()
; Start status monitoring
StartStatusMonitoring()
}
} else {
; Even if not auto-starting, check if mihomo is already running
if (CoreProcessName && ProcessExist(CoreProcessName)) {
MihomoProcess := ProcessExist(CoreProcessName)
ShowNotification("检测到运行", "检测到 mihomo 已在运行", 2)
; Get initial TUN status from API
GetTUNStatusFromAPI()
ApplyRuntimeTUNControl()
; Update menu to reflect current state
UpdateMenuStates()
StartStatusMonitoring()
}
}
return
;==============================================================================
; Configuration Management
;==============================================================================
LoadConfig() {
global
; Create default config if not exists
if (!FileExist(ConfigFile)) {
CreateDefaultConfig()
}
ReadConfigValues()
if (!IsConfigUsable()) {
if (!ShowSettingsGui(true)) {
ExitApp()
}
ReadConfigValues()
}
}
ReadConfigValues() {
global
; Read Mihomo section
CorePath := IniRead(ConfigFile, "Mihomo", "CorePath", "")
ConfigPath := IniRead(ConfigFile, "Mihomo", "ConfigPath", "")
ConfigURL := IniRead(ConfigFile, "Mihomo", "ConfigURL", "")
ActiveProfile := IniRead(ConfigFile, "Mihomo", "ActiveProfile", "default")
LoadProfiles()
; Extract process name from CorePath
CoreProcessName := ""
if (CorePath) {
SplitPath(CorePath, &CoreProcessName)
}
; Read Settings section
AutoStartCore := IniRead(ConfigFile, "Settings", "AutoStartCore", "1") = "1"
TUNControl := IniRead(ConfigFile, "Settings", "TUNControl", "runtime")
if (TUNControl != "runtime" && TUNControl != "file") {
TUNControl := "runtime"
}
DesiredTUNEnabled := IniRead(ConfigFile, "Settings", "TUNEnabled", "0") = "1"
delayValue := IniRead(ConfigFile, "Settings", "AutoStartupDelaySec", "15")
if (RegExMatch(delayValue, "^\d+$")) {
AutoStartupDelaySec := delayValue + 0
if (AutoStartupDelaySec > 600) {
AutoStartupDelaySec := 600
}
} else {
AutoStartupDelaySec := 15
}
; Parse mihomo config file if exists to get API settings
if (ConfigPath && FileExist(ConfigPath)) {
ParseMihomoConfig(ConfigPath)
}
}
LoadProfiles() {
global Profiles, ConfigFile, ConfigPath, ConfigURL, ActiveProfile
Profiles := Map()
try {
section := IniRead(ConfigFile, "Profiles")
} catch {
section := ""
}
if (section) {
loop parse section, "`n", "`r" {
line := Trim(A_LoopField)
if (!line || !InStr(line, "=")) {
continue
}
parts := StrSplit(line, "=", , 2)
name := Trim(parts[1])
path := Trim(parts[2])
if (name && path) {
Profiles[name] := path
}
}
}
; Backward compatibility: migrate the legacy ConfigPath into Profiles.
if (Profiles.Count = 0 && ConfigPath) {
Profiles["default"] := ConfigPath
ActiveProfile := "default"
try {
IniWrite("default", ConfigFile, "Mihomo", "ActiveProfile")
IniWrite(ConfigPath, ConfigFile, "Profiles", "default")
}
}
if (!ActiveProfile) {
ActiveProfile := "default"
}
; Remote URL keeps the old precedence. Local profile selection is used when ConfigURL is empty.
if (!ConfigURL && Profiles.Has(ActiveProfile)) {
ConfigPath := Profiles[ActiveProfile]
try {
IniWrite(ConfigPath, ConfigFile, "Mihomo", "ConfigPath")
}
}
}
IsConfigUsable() {
global CorePath, ConfigPath, ConfigURL
if (!CorePath || !FileExist(CorePath)) {
return false
}
if (ConfigURL) {
return true
}
return ConfigPath && FileExist(ConfigPath)
}
SaveSettingsConfig(corePath, configPath, configURL, autoStart, tunControl, tunEnabled, delaySec) {
global ConfigFile, ActiveProfile, Profiles
if (!ActiveProfile) {
ActiveProfile := "default"
}
if (configPath) {
Profiles[ActiveProfile] := configPath
}
try {
IniWrite(corePath, ConfigFile, "Mihomo", "CorePath")
IniWrite(configPath, ConfigFile, "Mihomo", "ConfigPath")
IniWrite(configURL, ConfigFile, "Mihomo", "ConfigURL")
IniWrite(ActiveProfile, ConfigFile, "Mihomo", "ActiveProfile")
if (configPath) {
IniWrite(configPath, ConfigFile, "Profiles", ActiveProfile)
}
IniWrite(autoStart ? "1" : "0", ConfigFile, "Settings", "AutoStartCore")
IniWrite(tunControl, ConfigFile, "Settings", "TUNControl")
IniWrite(tunEnabled ? "1" : "0", ConfigFile, "Settings", "TUNEnabled")
IniWrite(delaySec, ConfigFile, "Settings", "AutoStartupDelaySec")
try {
IniDelete(ConfigFile, "Settings", "RememberTUN")
}
try {
IniDelete(ConfigFile, "Settings", "AutoRestoreTUN")
}
return true
} catch as err {
MsgBox("保存配置失败: " . err.Message, "MiTray", "Iconx")
return false
}
}
CreateDefaultConfig() {
global ConfigFile
configContent := "
(
[Mihomo]
; Path to mihomo executable (required)
CorePath=
; Active local profile name. ConfigURL still takes precedence if set.
ActiveProfile=default
; Local config file path (optional if ConfigURL is set)
ConfigPath=
; Remote config URL (optional, takes precedence over ConfigPath)
ConfigURL=
[Profiles]
; default=
[Settings]
; Auto-start mihomo on script launch (1=yes, 0=no)
AutoStartCore=1
; TUN control source:
; runtime = MiTray applies TUN state through mihomo API
; file = follow tun.enable in YAML
TUNControl=runtime
; Desired TUN state when TUNControl=runtime (1=enabled, 0=disabled)
TUNEnabled=0
; Delay (seconds) before auto-start task runs after user logon (0-600)
AutoStartupDelaySec=15
)"
FileAppend(configContent, ConfigFile)
}
ShowSettingsGui(firstRun := false) {
global CorePath, ConfigPath, ConfigURL, AutoStartCore, TUNControl, DesiredTUNEnabled, AutoStartupDelaySec
state := {Done: false, Saved: false}
title := firstRun ? "MiTray 首次设置" : "MiTray 设置"
settingsGui := Gui("+AlwaysOnTop", title)
settingsGui.MarginX := 14
settingsGui.MarginY := 14
settingsGui.SetFont("s9", "Microsoft YaHei UI")
settingsGui.Add("Text", "x14 y18 w120", "mihomo 核心")
coreEdit := settingsGui.Add("Edit", "x140 y15 w360", CorePath)
browseCoreBtn := settingsGui.Add("Button", "x510 y14 w70", "浏览...")
settingsGui.Add("Text", "x14 y58 w120", "本地配置文件")
configEdit := settingsGui.Add("Edit", "x140 y55 w360", ConfigPath)
browseConfigBtn := settingsGui.Add("Button", "x510 y54 w70", "浏览...")
settingsGui.Add("Text", "x14 y98 w120", "远程配置 URL")
urlEdit := settingsGui.Add("Edit", "x140 y95 w440", ConfigURL)
autoStartCheck := settingsGui.Add("Checkbox", "x140 y135 w220", "启动 MiTray 时自动启动 mihomo")
autoStartCheck.Value := AutoStartCore ? 1 : 0
settingsGui.Add("Text", "x14 y165 w120", "TUN 控制")
tunRuntimeRadio := settingsGui.Add("Radio", "x140 y165 w190", "MiTray 运行时接管")
tunFileRadio := settingsGui.Add("Radio", "x340 y165 w190", "跟随 YAML 的 tun.enable")
tunRuntimeRadio.Value := (TUNControl = "runtime") ? 1 : 0
tunFileRadio.Value := (TUNControl = "file") ? 1 : 0
tunEnabledCheck := settingsGui.Add("Checkbox", "x140 y195 w260", "接管时开启 TUN")
tunEnabledCheck.Value := DesiredTUNEnabled ? 1 : 0
settingsGui.Add("Text", "x14 y232 w120", "自启延迟秒数")
delayEdit := settingsGui.Add("Edit", "x140 y229 w80 Number", AutoStartupDelaySec)
settingsGui.Add("UpDown", "Range0-600", AutoStartupDelaySec)
settingsGui.Add("Text", "x140 y258 w440 c666666", "本地配置文件和远程配置 URL 填一个即可;如果都填写,远程 URL 优先。")
settingsGui.Add("Text", "x14 y292 w120", "解析结果")
previewEdit := settingsGui.Add("Edit", "x140 y289 w440 h105 Multi ReadOnly -Wrap +VScroll")
testBtn := settingsGui.Add("Button", "x140 y410 w100", "测试配置")
saveBtn := settingsGui.Add("Button", "x390 y410 w90 Default", "保存")
cancelBtn := settingsGui.Add("Button", "x490 y410 w90", firstRun ? "退出" : "取消")
browseCoreBtn.OnEvent("Click", (*) => BrowseCoreFileAndPreview(coreEdit, previewEdit, configEdit, urlEdit))
browseConfigBtn.OnEvent("Click", (*) => BrowseConfigFileAndPreview(configEdit, previewEdit, coreEdit, urlEdit))
coreEdit.OnEvent("Change", (*) => UpdateSettingsPreview(previewEdit, coreEdit, configEdit, urlEdit))
configEdit.OnEvent("Change", (*) => UpdateSettingsPreview(previewEdit, coreEdit, configEdit, urlEdit))
urlEdit.OnEvent("Change", (*) => UpdateSettingsPreview(previewEdit, coreEdit, configEdit, urlEdit))
testBtn.OnEvent("Click", (*) => UpdateSettingsPreview(previewEdit, coreEdit, configEdit, urlEdit, true))
saveBtn.OnEvent("Click", (*) => SaveSettingsGuiValues(settingsGui, state, coreEdit, configEdit, urlEdit,
autoStartCheck, tunRuntimeRadio, tunEnabledCheck, delayEdit))
cancelBtn.OnEvent("Click", (*) => (state.Done := true))
settingsGui.OnEvent("Close", (*) => (state.Done := true))
UpdateSettingsPreview(previewEdit, coreEdit, configEdit, urlEdit)
settingsGui.Show("w600 h465")
while (!state.Done) {
Sleep(50)
}
try {
settingsGui.Destroy()
}
return state.Saved
}
BrowseCoreFile(coreEdit) {
selected := FileSelect(, coreEdit.Value, "选择 mihomo 核心", "Executable (*.exe)")
if (selected) {
coreEdit.Value := selected
}
}
BrowseCoreFileAndPreview(coreEdit, previewEdit, configEdit, urlEdit) {
BrowseCoreFile(coreEdit)
UpdateSettingsPreview(previewEdit, coreEdit, configEdit, urlEdit)
}
BrowseConfigFile(configEdit) {
selected := FileSelect(, configEdit.Value, "选择 mihomo 配置文件", "YAML (*.yaml; *.yml)")
if (selected) {
configEdit.Value := selected
}
}
BrowseConfigFileAndPreview(configEdit, previewEdit, coreEdit, urlEdit) {
BrowseConfigFile(configEdit)
UpdateSettingsPreview(previewEdit, coreEdit, configEdit, urlEdit)
}
UpdateSettingsPreview(previewEdit, coreEdit, configEdit, urlEdit, testAPI := false) {
corePath := Trim(coreEdit.Value)
configPath := Trim(configEdit.Value)
configURL := Trim(urlEdit.Value)
lines := []
if (corePath && FileExist(corePath)) {
lines.Push("核心: OK")
} else if (corePath) {
lines.Push("核心: 文件不存在")
} else {
lines.Push("核心: 未选择")
}
if (configURL) {
lines.Push("远程配置: 已填写,将优先使用")
} else {
lines.Push("远程配置: 未填写")
}
parsed := 0
if (configPath) {
if (!FileExist(configPath)) {
lines.Push("本地配置: 文件不存在")
} else {
try {
parsed := ReadMihomoConfig(configPath)
lines.Push("本地配置: OK")
lines.Push("API: " . DisplayConfigValue(parsed.Controller))
lines.Push("代理端口: " . DisplayConfigValue(parsed.ProxyPort))
lines.Push("WebUI: " . BuildWebUIDisplay(parsed))
if (!parsed.Controller) {
lines.Push("提示: 未解析到 external-controller")
}
if (!parsed.ProxyPort) {
lines.Push("提示: 未解析到 mixed-port/port")
}
} catch as err {
lines.Push("本地配置: 读取失败 - " . err.Message)
}
}
} else {
lines.Push("本地配置: 未选择")
}
if (testAPI) {
if (parsed && parsed.Controller) {
result := TestMihomoAPI(parsed.Controller, parsed.Secret)
lines.Push("API 测试: " . result)
} else if (configURL) {
lines.Push("API 测试: 远程配置需要核心启动后解析")
} else {
lines.Push("API 测试: 缺少 external-controller")
}
}
previewEdit.Value := JoinLines(lines)
}
DisplayConfigValue(value) {
return value ? value : "未解析到"
}
BuildWebUIDisplay(parsed) {
if (!parsed.WebUIPath && !parsed.WebUIName) {
return "未解析到"
}
path := parsed.WebUIPath
if (parsed.WebUIName) {
path .= path ? "/" . parsed.WebUIName : parsed.WebUIName
}
return path
}
TestMihomoAPI(controller, secret) {
try {
whr := ComObject("WinHttp.WinHttpRequest.5.1")
whr.Open("GET", "http://" . controller . "/configs", false)
if (secret) {
whr.SetRequestHeader("Authorization", "Bearer " . secret)
}
whr.SetTimeouts(1000, 1000, 2000, 2000)
whr.Send()
if (whr.Status = 200) {
return "OK"
}
return "失败 HTTP " . whr.Status
} catch as err {
return "无法连接 - " . err.Message
}
}
JoinLines(lines) {
text := ""
for line in lines {
text .= (text ? "`r`n" : "") . line
}
return text
}
SaveSettingsGuiValues(settingsGui, state, coreEdit, configEdit, urlEdit, autoStartCheck, tunRuntimeRadio,
tunEnabledCheck, delayEdit) {
corePath := Trim(coreEdit.Value)
configPath := Trim(configEdit.Value)
configURL := Trim(urlEdit.Value)
delayValue := Trim(delayEdit.Value)
if (!corePath || !FileExist(corePath)) {
MsgBox("请选择有效的 mihomo 核心文件。", "MiTray", "Iconx")
return
}
if (!configURL && (!configPath || !FileExist(configPath))) {
MsgBox("请在「本地配置文件」和「远程配置 URL」中至少填写一个。", "MiTray", "Iconx")
return
}
if (!RegExMatch(delayValue, "^\d+$")) {
delayValue := "15"
}
delaySec := delayValue + 0
if (delaySec > 600) {
delaySec := 600
}
tunControl := (tunRuntimeRadio.Value = 1) ? "runtime" : "file"
if (SaveSettingsConfig(corePath, configPath, configURL, autoStartCheck.Value = 1, tunControl,
tunEnabledCheck.Value = 1, delaySec)) {
state.Saved := true
state.Done := true
}
}
ParseMihomoConfig(configPath) {
global APIController, APISecret, ProxyPort, WebUIPath, WebUIName
try {
parsed := ReadMihomoConfig(configPath)
APIController := parsed.Controller
APISecret := parsed.Secret
ProxyPort := parsed.ProxyPort
WebUIPath := parsed.WebUIPath
WebUIName := parsed.WebUIName
} catch {
APIController := ""
APISecret := ""
ProxyPort := ""
WebUIPath := ""
WebUIName := ""
}
}
ReadMihomoConfig(configPath) {
content := FileRead(configPath)
proxyPort := ReadTopLevelYamlValue(content, "mixed-port")
if (!proxyPort) {
proxyPort := ReadTopLevelYamlValue(content, "port")
}
return {
Controller: ReadTopLevelYamlValue(content, "external-controller"),
Secret: ReadTopLevelYamlValue(content, "secret"),
ProxyPort: proxyPort,
WebUIPath: ReadTopLevelYamlValue(content, "external-ui"),
WebUIName: ReadTopLevelYamlValue(content, "external-ui-name")
}
}
ReadTopLevelYamlValue(content, key) {
loop parse content, "`n", "`r" {
line := A_LoopField
if (!line || RegExMatch(line, "^\s+#")) {
continue
}
; Only read top-level scalar keys. Nested YAML is intentionally ignored.
if (RegExMatch(line, "^\s")) {
continue
}
if (!RegExMatch(line, "^" . key . "\s*:\s*(.*)$", &match)) {
continue
}
value := Trim(match[1])
if (value = "") {
return ""
}
return NormalizeYamlScalar(value)
}
return ""
}
NormalizeYamlScalar(value) {
value := Trim(value)
if (SubStr(value, 1, 1) = '"' || SubStr(value, 1, 1) = "'") {
quote := SubStr(value, 1, 1)
return ReadQuotedYamlScalar(value, quote)
}
value := StripYamlComment(value)
return Trim(value)
}
ReadQuotedYamlScalar(value, quote) {
result := ""
escaped := false
body := SubStr(value, 2)
loop parse body {
ch := A_LoopField
if (quote = '"' && escaped) {
switch ch {
case "n":
result .= "`n"
case "r":
result .= "`r"
case "t":
result .= "`t"
default:
result .= ch
}
escaped := false
continue
}
if (quote = '"' && ch = "\") {
escaped := true
continue
}
if (ch = quote) {
return result
}
result .= ch
}
; If the quote is not closed, fall back to the trimmed unquoted body.
return Trim(SubStr(value, 2))
}
StripYamlComment(value) {
inSpace := false
loop parse value {
ch := A_LoopField
if (ch = "#") {
if (A_Index = 1 || inSpace) {
return RTrim(SubStr(value, 1, A_Index - 1))
}
}
inSpace := ch = " " || ch = "`t"
}
return value
}
UpdateTrayIcon() {
global TrayIconState
nextState := "default"
if (!IsMihomoRunning()) {
nextState := "off"
} else if (IsProxyEnabled || IsTUNEnabled) {
nextState := "on"
}
if (nextState = TrayIconState) {
return
}
if (ApplyTrayIcon(nextState)) {
TrayIconState := nextState
}
}
ApplyTrayIcon(state) {
global TrayIconOnResourceId, TrayIconOffResourceId
if (A_IsCompiled) {
switch state {
case "on":
TraySetIcon(A_ScriptFullPath, -TrayIconOnResourceId, true)
case "off":
TraySetIcon(A_ScriptFullPath, -TrayIconOffResourceId, true)
default:
TraySetIcon("*", , true)
}
return true
}
iconPath := A_ScriptDir . "\mitray.ico"
switch state {
case "on":
iconPath := A_ScriptDir . "\mitray_on.ico"
case "off":
iconPath := A_ScriptDir . "\mitray_off.ico"
}
if (!FileExist(iconPath)) {
iconPath := A_ScriptDir . "\mitray.ico"
}
if (!FileExist(iconPath)) {
TraySetIcon("*", , true)
return false
}
TraySetIcon(iconPath, 1, true)
return true
}
;==============================================================================
; Tray Menu Setup
;==============================================================================
SetupTrayMenu() {
global AutoStartupMenu, ProfileMenu
; Remove default menu items
A_TrayMenu.Delete()
; Add menu items
A_TrayMenu.Add("打开 WebUI", MenuOpenWebUI)
A_TrayMenu.Add() ; Separator
A_TrayMenu.Add("启用系统代理", MenuToggleProxy)
A_TrayMenu.Add("TUN 模式", MenuToggleTUN)
A_TrayMenu.Add() ; Separator
A_TrayMenu.Add("刷新状态", MenuRefreshStatus)
; mihomo 配置文件子菜单
ProfileMenu := Menu()
BuildProfileMenu()
A_TrayMenu.Add("选择 mihomo 配置", ProfileMenu)
A_TrayMenu.Add("MiTray 设置...", MenuOpenSettings)
A_TrayMenu.Add() ; Separator
; 创建开机自启子菜单
AutoStartupMenu := Menu()
AutoStartupMenu.Add("普通权限", MenuAutoStartupNormal)
AutoStartupMenu.Add("管理员权限", MenuAutoStartupAdmin)
A_TrayMenu.Add("开机自启", AutoStartupMenu)
A_TrayMenu.Add() ; Separator
A_TrayMenu.Add("打开程序目录", MenuOpenScriptDir)
A_TrayMenu.Add("打开核心目录", MenuOpenCoreDir)
A_TrayMenu.Add() ; Separator
A_TrayMenu.Add("重启内核", MenuRestartCore)
A_TrayMenu.Add("停止内核", MenuStopCore)
A_TrayMenu.Add("退出程序", MenuExitProgram)
; Update menu states
UpdateMenuStates()
}
BuildProfileMenu() {
global ProfileMenu, Profiles
if (!ProfileMenu) {
return
}
for name, path in Profiles {
ProfileMenu.Add(name, MenuSelectProfile)
}
if (Profiles.Count > 0) {
ProfileMenu.Add()
}
ProfileMenu.Add("添加配置文件...", MenuAddProfile)
}
UpdateMenuStates() {
UpdateTrayIcon()
; Update proxy checkbox
if (IsProxyEnabled) {
A_TrayMenu.Check("启用系统代理")
} else {
A_TrayMenu.Uncheck("启用系统代理")
}
; Update TUN checkbox
if (IsTUNEnabled) {
A_TrayMenu.Check("TUN 模式")
} else {
A_TrayMenu.Uncheck("TUN 模式")
}
; Update auto-startup checkboxes
if (AutoStartupMenu) {
if (AutoStartupLevel = "normal") {
AutoStartupMenu.Check("普通权限")
AutoStartupMenu.Uncheck("管理员权限")
} else if (AutoStartupLevel = "admin") {
AutoStartupMenu.Uncheck("普通权限")
AutoStartupMenu.Check("管理员权限")
} else {
AutoStartupMenu.Uncheck("普通权限")
AutoStartupMenu.Uncheck("管理员权限")
}
}
; Update active profile checkbox
if (ProfileMenu) {
for name, path in Profiles {
if (name = ActiveProfile) {
ProfileMenu.Check(name)
} else {
ProfileMenu.Uncheck(name)
}
}
}
}
;==============================================================================
; Menu Handlers
;==============================================================================
MenuOpenWebUI(*) {
global APIController, APISecret, WebUIPath, WebUIName
if (!APIController) {
ShowNotification("错误", "API 配置未设置", 3)
return
}
; Check if mihomo is running
if (!IsMihomoRunning()) {
ShowNotification("错误", "mihomo 未运行", 3)
return
}
; Construct WebUI URL
url := "http://" . APIController . "/" . WebUIPath
; Add external-ui-name if configured
if (WebUIName) {
url .= "/" . WebUIName
}
; Add secret parameter
if (APISecret) {
url .= "?secret=" . APISecret
}
Run(url)
ShowNotification("WebUI", "已在浏览器中打开 WebUI", 2)
}
MenuToggleProxy(*) {
if (IsProxyEnabled) {
DisableSystemProxy()
} else {
EnableSystemProxy()
}
}
MenuToggleTUN(*) {
if (IsTUNEnabled) {
DisableTUNMode()
} else {
EnableTUNMode()
}
}
MenuRefreshStatus(*) {
RefreshAllStatus()
ShowNotification("状态刷新", "已刷新系统代理和 TUN 状态", 2)
}
MenuOpenSettings(*) {
wasRunning := IsMihomoRunning()
if (ShowSettingsGui(false)) {
LoadConfig()
SetupTrayMenu()
CheckAutoStartup()
CheckSystemProxyState()
if (wasRunning) {
ShowNotification("配置已保存", "配置已保存,重启内核后生效", 3)
} else {
ShowNotification("配置已保存", "配置已保存", 2)
}
}
}
MenuSelectProfile(itemName, *) {
SwitchMihomoProfile(itemName)
}
MenuAddProfile(*) {
global ConfigFile, Profiles, ActiveProfile, ConfigPath
selected := FileSelect(, ConfigPath, "选择 mihomo 配置文件", "YAML (*.yaml; *.yml)")
if (!selected) {
return
}
SplitPath(selected, , , , &baseName)
result := InputBox("请输入配置名称:", "添加 mihomo 配置", , baseName ? baseName : "default")
if (result.Result != "OK") {
return
}
profileName := Trim(result.Value)
profileName := RegExReplace(profileName, "[=\r\n]", "_")
if (!profileName) {
ShowNotification("错误", "配置名称不能为空", 2)
return
}
if (Profiles.Has(profileName)) {
ShowNotification("错误", "配置名称已存在: " . profileName, 3)
return
}
Profiles[profileName] := selected
try {
IniWrite(selected, ConfigFile, "Profiles", profileName)
SwitchMihomoProfile(profileName)
} catch as err {
ShowNotification("错误", "添加配置失败: " . err.Message, 3)
}
}
SwitchMihomoProfile(profileName) {
global ConfigFile, Profiles, ActiveProfile, ConfigPath, ConfigURL
if (!Profiles.Has(profileName)) {
ShowNotification("错误", "配置不存在: " . profileName, 2)
return false
}
if (profileName = ActiveProfile && ConfigPath = Profiles[profileName] && !ConfigURL) {
UpdateMenuStates()
return true
}
wasRunning := IsMihomoRunning()
ActiveProfile := profileName
ConfigPath := Profiles[profileName]
ConfigURL := ""
try {
IniWrite(ActiveProfile, ConfigFile, "Mihomo", "ActiveProfile")
IniWrite(ConfigPath, ConfigFile, "Mihomo", "ConfigPath")
IniWrite("", ConfigFile, "Mihomo", "ConfigURL")
} catch as err {
ShowNotification("错误", "保存配置选择失败: " . err.Message, 3)
return false
}
ParseMihomoConfig(ConfigPath)
SetupTrayMenu()
if (wasRunning) {
StopMihomo()
Sleep(1000)
if (StartMihomo()) {
Sleep(3000)
StartStatusMonitoring()
RefreshAllStatus()
}
} else {
UpdateMenuStates()
}
ShowNotification("配置切换", "已切换到: " . ActiveProfile, 2)
return true
}
MenuAutoStartupNormal(*) {
if (AutoStartupLevel = "normal") {
DisableAutoStartup()
} else {
EnableAutoStartup("normal")
}
}
MenuAutoStartupAdmin(*) {
if (AutoStartupLevel = "admin") {
DisableAutoStartup()
} else {
EnableAutoStartup("admin")
}
}
MenuOpenScriptDir(*) {
Run('explorer.exe "' . A_ScriptDir . '"')
}
MenuOpenCoreDir(*) {
global CorePath
if (!CorePath || !FileExist(CorePath)) {
ShowNotification("错误", "核心路径未配置或文件不存在", 3)
return
}
; 获取核心所在目录