ModMain.vb 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. Imports System.Collections.ObjectModel
  2. Imports System.Windows.Interop
  3. Imports System.Windows.Threading
  4. Public Module ModMain
  5. #Region "弹出提示"
  6. ''' <summary>
  7. ''' 提示信息的种类。
  8. ''' 该枚举在自定义事件中使用,是公开 API 的一部分。
  9. ''' </summary>
  10. Public Enum HintType
  11. Blue
  12. Green
  13. Red
  14. End Enum
  15. Private Structure HintMessage
  16. Public Text As String
  17. Public Type As HintType
  18. Public Log As Boolean
  19. End Structure
  20. ''' <summary>
  21. ''' 等待弹出的提示列表。以 {String, HintType, Log As Boolean} 形式存储为数组。
  22. ''' </summary>
  23. Private HintWaiting As New ConcurrentQueue(Of HintMessage)
  24. ''' <summary>
  25. ''' 在窗口左下角弹出提示文本。
  26. ''' </summary>
  27. Public Sub Hint(Text As String, Optional Type As HintType = HintType.Blue, Optional Log As Boolean = True)
  28. HintWaiting.Enqueue(New HintMessage With {.Text = If(Text, ""), .Type = Type, .Log = Log})
  29. End Sub
  30. Private Sub HintTick()
  31. Try
  32. 'Tag 存储了:{ 是否可以重用, Uuid }
  33. Dim CurrentHint As HintMessage = Nothing
  34. Do While HintWaiting.TryDequeue(CurrentHint)
  35. ''清除空提示
  36. 'If IsNothing(HintWaiting(0)) OrElse IsNothing(HintWaiting(0)(0)) Then
  37. ' HintWaiting.RemoveAt(0)
  38. ' Continue Do
  39. 'End If
  40. '去回车
  41. CurrentHint.Text = CurrentHint.Text.ReplaceLineEndings(" ", mergeMultiple:=True)
  42. '超量提示直接忽略
  43. If FrmMain.PanHint.Children.Count >= 20 Then GoTo EndHint
  44. '检查是否有重复提示
  45. Dim DoubleStack As Border = Nothing
  46. For Each stack As Border In FrmMain.PanHint.Children
  47. If stack.Tag(0) AndAlso CType(stack.Child, TextBlock).Text = CurrentHint.Text Then DoubleStack = stack
  48. Next
  49. '获取渐变颜色
  50. Dim TargetColor0, TargetColor1 As MyColor
  51. Dim Percent As Double = 0.3
  52. Select Case CurrentHint.Type
  53. Case HintType.Blue
  54. TargetColor0 = New MyColor(215, 37, 155, 252)
  55. TargetColor1 = New MyColor(215, 10, 142, 252)
  56. Case HintType.Green
  57. TargetColor0 = New MyColor(215, 33, 177, 33)
  58. TargetColor1 = New MyColor(215, 29, 160, 29)
  59. Case Else 'HintType.Red
  60. TargetColor0 = New MyColor(215, 255, 53, 11)
  61. TargetColor1 = New MyColor(215, 255, 43, 0)
  62. End Select
  63. If Not IsNothing(DoubleStack) Then
  64. '有重复提示,且该提示的进入动画已播放
  65. If Not AniIsRun("Hint Show " & DoubleStack.Tag(1)) Then
  66. AniStop("Hint Hide " & DoubleStack.Tag(1))
  67. Dim Delay As Double = (800 + CurrentHint.Text.Length.Clamp(5, 23) * 180) * AniSpeed
  68. AniStart({
  69. AaX(DoubleStack, -12 - DoubleStack.Margin.Left, 50,, New AniEaseOutFluent),
  70. AaX(DoubleStack, -8, 50, 50, New AniEaseInFluent),
  71. AaX(DoubleStack, 8, 50, 100, New AniEaseOutFluent),
  72. AaX(DoubleStack, -8, 50, 150, New AniEaseInFluent),
  73. AaDouble(Sub(i)
  74. Percent += i
  75. Dim Gradient As LinearGradientBrush = DoubleStack.Background
  76. Gradient.GradientStops(0).Color = TargetColor0 * Percent + New MyColor(255, 255, 255) * (1 - Percent)
  77. Gradient.GradientStops(1).Color = TargetColor1 * Percent + New MyColor(255, 255, 255) * (1 - Percent)
  78. End Sub, 0.7, 250),
  79. AaX(DoubleStack, -50, 200, Delay, New AniEaseInFluent),
  80. AaOpacity(DoubleStack, -1, 150, Delay),
  81. AaCode(Sub() DoubleStack.Tag(0) = False, Delay),
  82. AaHeight(DoubleStack, -26, 100,, New AniEaseOutFluent, True),
  83. AaCode(Sub() FrmMain.PanHint.Children.Remove(DoubleStack), , True)
  84. }, "Hint Hide " & DoubleStack.Tag(1))
  85. End If
  86. Else
  87. '准备控件
  88. Dim NewHintControl As New Border With {.Tag = {True, GetUuid()}, .Margin = New Thickness(-70, 0, 20, 0), .Opacity = 0, .Height = 0, .HorizontalAlignment = HorizontalAlignment.Left, .CornerRadius = New CornerRadius(0, 6, 6, 0)}
  89. NewHintControl.Background = New LinearGradientBrush(New GradientStopCollection(New List(Of GradientStop) From {
  90. New GradientStop(TargetColor0 * Percent + New MyColor(255, 255, 255) * (1 - Percent), 0),
  91. New GradientStop(TargetColor1 * Percent + New MyColor(255, 255, 255) * (1 - Percent), 1)}), 90)
  92. NewHintControl.Child = New TextBlock With {.TextTrimming = TextTrimming.CharacterEllipsis, .FontSize = 13, .Text = CurrentHint.Text, .Foreground = New MyColor(255, 255, 255), .Margin = New Thickness(33, 5, 8, 5)}
  93. 'AddHandler NewHintControl.MouseLeftButtonDown, AddressOf HideAllHint
  94. FrmMain.PanHint.Children.Add(NewHintControl)
  95. '控件动画
  96. Dim Animations As New List(Of AniData)
  97. If FrmMain.PanHint.Children.Count > 1 Then
  98. '已有提示
  99. Animations.Add(AaHeight(NewHintControl, 26, 150, , New AniEaseOutFluent))
  100. Else
  101. '是唯一提示
  102. NewHintControl.Height = 26
  103. End If
  104. '开始动画
  105. Animations.AddRange({
  106. AaX(NewHintControl, 30, 400, , New AniEaseOutElastic(AniEasePower.Weak)),
  107. AaX(NewHintControl, 20, 200, , New AniEaseOutFluent),
  108. AaOpacity(NewHintControl, 1, 100),
  109. AaDouble(Sub(i)
  110. Percent += i
  111. Dim Gradient As LinearGradientBrush = NewHintControl.Background
  112. Gradient.GradientStops(0).Color = TargetColor0 * Percent + New MyColor(255, 255, 255) * (1 - Percent)
  113. Gradient.GradientStops(1).Color = TargetColor1 * Percent + New MyColor(255, 255, 255) * (1 - Percent)
  114. End Sub, 0.7, 250, 100)
  115. })
  116. AniStart(Animations, "Hint Show " & NewHintControl.Tag(1))
  117. '结束动画
  118. Dim Delay As Double = (800 + CurrentHint.Text.Length.Clamp(5, 23) * 180) * AniSpeed
  119. AniStart({
  120. AaX(NewHintControl, -50, 200, Delay, New AniEaseInFluent),
  121. AaOpacity(NewHintControl, -1, 150, Delay),
  122. AaCode(Sub() NewHintControl.Tag(0) = False, Delay),
  123. AaHeight(NewHintControl, -26, 100,, New AniEaseOutFluent, True),
  124. AaCode(Sub() FrmMain.PanHint.Children.Remove(NewHintControl), , True)
  125. }, "Hint Hide " & NewHintControl.Tag(1))
  126. End If
  127. '结束处理
  128. EndHint:
  129. If CurrentHint.Log Then Logger.Info($"弹出提示:{CurrentHint.Text}")
  130. Loop
  131. Catch ex As Exception
  132. Logger.Info(ex, "显示弹出提示失败")
  133. End Try
  134. End Sub
  135. Private Sub HideAllHint()
  136. For Each Control As Border In FrmMain.PanHint.Children
  137. Control.IsHitTestVisible = False
  138. AniStart({
  139. AaX(Control, -50, 200, , New AniEaseInFluent),
  140. AaOpacity(Control, -1, 150, , New AniEaseInFluent),
  141. AaCode(Sub() Control.Tag(0) = False),
  142. AaHeight(Control, -26, 100,, New AniEaseOutFluent, True),
  143. AaCode(Sub() FrmMain.PanHint.Children.Remove(Control), , True)
  144. }, "Hint Hide " & Control.Tag(1))
  145. Next
  146. End Sub
  147. #End Region
  148. #Region "弹窗"
  149. ''' <summary>
  150. ''' 存储弹窗信息的转换器。
  151. ''' </summary>
  152. Public Class MyMsgBoxConverter
  153. Public Type As MyMsgBoxType
  154. Public Title As String
  155. Public Text As String
  156. ''' <summary>
  157. ''' 输入模式:文本框的文本。
  158. ''' 选择模式:需要放进去的 IEnumberable(Of IMyRadio)。
  159. ''' 登录模式:登录步骤 1 中返回的 JSON。
  160. ''' </summary>
  161. Public Content As Object
  162. ''' <summary>
  163. ''' 输入模式:输入验证规则。
  164. ''' </summary>
  165. Public ValidateRules As Collection(Of Validate)
  166. ''' <summary>
  167. ''' 输入模式:提示文本。
  168. ''' </summary>
  169. Public HintText As String = ""
  170. ''' <summary>
  171. ''' 有多个按钮时,是否给第一个按钮加高亮。
  172. ''' </summary>
  173. Public HighLight As Boolean
  174. Public Button1 As String = "确定"
  175. Public Button2 As String = ""
  176. Public Button3 As String = ""
  177. ''' <summary>
  178. ''' 点击第一个按钮将执行该方法,不关闭弹窗。
  179. ''' </summary>
  180. Public Button1Action As Action = Nothing
  181. ''' <summary>
  182. ''' 点击第二个按钮将执行该方法,不关闭弹窗。
  183. ''' </summary>
  184. Public Button2Action As Action = Nothing
  185. ''' <summary>
  186. ''' 点击第三个按钮将执行该方法,不关闭弹窗。
  187. ''' </summary>
  188. Public Button3Action As Action = Nothing
  189. Public IsWarn As Boolean = False
  190. Public ForceWait As Boolean = False
  191. Public WaitFrame As New DispatcherFrame(True)
  192. ''' <summary>
  193. ''' 弹窗是否已经关闭。
  194. ''' </summary>
  195. Public IsExited As Boolean = False
  196. ''' <summary>
  197. ''' 输入模式:输入的文本。若点击了 非 第一个按钮,则为 Nothing。
  198. ''' 选择模式:点击的按钮编号,从 1 开始。
  199. ''' 登录模式:字符串数组 {AccessToken, RefreshToken} 或一个 Exception。
  200. ''' </summary>
  201. Public Result As Object
  202. End Class
  203. Public Enum MyMsgBoxType
  204. Text
  205. [Select]
  206. Input
  207. Login
  208. End Enum
  209. ''' <summary>
  210. ''' 显示弹窗,返回点击按钮的编号(从 1 开始)。
  211. ''' </summary>
  212. ''' <param name="Title">弹窗的标题。</param>
  213. ''' <param name="Caption">弹窗的内容。</param>
  214. ''' <param name="Button1">显示的第一个按钮,默认为“确定”。</param>
  215. ''' <param name="Button2">显示的第二个按钮,默认为空。</param>
  216. ''' <param name="Button3">显示的第三个按钮,默认为空。</param>
  217. ''' <param name="Button1Action">点击第一个按钮将执行该方法,不关闭弹窗。</param>
  218. ''' <param name="Button2Action">点击第二个按钮将执行该方法,不关闭弹窗。</param>
  219. ''' <param name="Button3Action">点击第三个按钮将执行该方法,不关闭弹窗。</param>
  220. ''' <param name="IsWarn">是否为警告弹窗,若为 True,弹窗配色和背景会变为红色。</param>
  221. Public Function MyMsgBox(Caption As String, Optional Title As String = "提示",
  222. Optional Button1 As String = "确定", Optional Button2 As String = "", Optional Button3 As String = "",
  223. Optional IsWarn As Boolean = False, Optional HighLight As Boolean = True, Optional ForceWait As Boolean = False,
  224. Optional Button1Action As Action = Nothing, Optional Button2Action As Action = Nothing, Optional Button3Action As Action = Nothing) As Integer
  225. '将弹窗列入队列
  226. Dim Converter As New MyMsgBoxConverter With {.Type = MyMsgBoxType.Text, .Button1 = Button1, .Button2 = Button2, .Button3 = Button3, .Text = Caption, .IsWarn = IsWarn, .Title = Title, .HighLight = HighLight, .ForceWait = True, .Button1Action = Button1Action, .Button2Action = Button2Action, .Button3Action = Button3Action}
  227. If Button2.Length > 0 OrElse ForceWait Then
  228. '若有多个按钮则开始等待
  229. If FrmMain Is Nothing OrElse FrmMain.PanMsg Is Nothing AndAlso RunInUi() Then
  230. '主窗体尚未加载,用老土的弹窗来替代
  231. If Button2.Length > 0 Then
  232. Dim RawResult As MsgBoxResult =
  233. MsgBox(Caption, If(Button3.Length > 0, MsgBoxStyle.YesNoCancel, MsgBoxStyle.YesNo) + If(IsWarn, MsgBoxStyle.Critical, MsgBoxStyle.Question), Title)
  234. Select Case RawResult
  235. Case MsgBoxResult.Yes
  236. Converter.Result = 1
  237. Case MsgBoxResult.No
  238. Converter.Result = 2
  239. Case MsgBoxResult.Cancel
  240. Converter.Result = 3
  241. End Select
  242. Else
  243. MsgBox(Caption, MsgBoxStyle.OkOnly + If(IsWarn, MsgBoxStyle.Critical, MsgBoxStyle.Question), Title)
  244. Converter.Result = 1
  245. End If
  246. Logger.Warn($"主窗体加载完成前出现意料外的等待弹窗:{Button1},{Button2},{Button3}")
  247. Else
  248. WaitingMyMsgBox.Enqueue(Converter)
  249. Try
  250. FrmMain.DragStop()
  251. If RunInUi() Then MyMsgBoxTick()
  252. ComponentDispatcher.PushModal()
  253. Dispatcher.PushFrame(Converter.WaitFrame)
  254. Finally
  255. ComponentDispatcher.PopModal()
  256. End Try
  257. End If
  258. Logger.Info($"普通弹框返回:{If(Converter.Result, "null")}")
  259. Return Converter.Result
  260. Else
  261. '不进行等待,直接返回
  262. WaitingMyMsgBox.Enqueue(Converter)
  263. Return 1
  264. End If
  265. End Function
  266. ''' <summary>
  267. ''' 显示输入框并返回输入的文本。若点击第二个按钮,则返回 Nothing。
  268. ''' </summary>
  269. ''' <param name="Title">弹窗的标题。</param>
  270. ''' <param name="ValidateRules">文本框的输入检测。</param>
  271. ''' <param name="Text">弹窗的介绍文本。</param>
  272. ''' <param name="DefaultInput">文本框的默认内容。</param>
  273. ''' <param name="HintText">文本框的提示内容。</param>
  274. ''' <param name="Button1">显示的第一个按钮,默认为“确定”。</param>
  275. ''' <param name="Button2">显示的第二个按钮,默认为“取消”。</param>
  276. ''' <param name="IsWarn">是否为警告弹窗,若为 True,弹窗配色和背景会变为红色。</param>
  277. Public Function MyMsgBoxInput(Title As String, Optional Text As String = Nothing, Optional DefaultInput As String = Nothing, Optional ValidateRules As Collection(Of Validate) = Nothing, Optional HintText As String = "", Optional Button1 As String = "确定", Optional Button2 As String = "取消", Optional IsWarn As Boolean = False) As String
  278. '将弹窗列入队列
  279. Dim Converter As New MyMsgBoxConverter With {.Text = If(Text, ""), .HintText = If(HintText, ""), .Type = MyMsgBoxType.Input, .ValidateRules = If(ValidateRules, New Collection(Of Validate)), .Button1 = Button1, .Button2 = Button2, .Content = DefaultInput, .IsWarn = IsWarn, .Title = Title}
  280. WaitingMyMsgBox.Enqueue(Converter)
  281. '虽然我也不知道这是啥但是能用就成了 :)
  282. Try
  283. If FrmMain IsNot Nothing Then FrmMain.DragStop()
  284. If RunInUi() Then MyMsgBoxTick()
  285. ComponentDispatcher.PushModal()
  286. Dispatcher.PushFrame(Converter.WaitFrame)
  287. Finally
  288. ComponentDispatcher.PopModal()
  289. End Try
  290. Logger.Info($"输入弹框返回:{If(Converter.Result, "null")}")
  291. Return Converter.Result
  292. End Function
  293. ''' <summary>
  294. ''' 显示选择框并返回选择的第几项(从 0 开始)。若点击第二个按钮,则返回 Nothing。
  295. ''' </summary>
  296. ''' <param name="Title">弹窗的标题。</param>
  297. ''' <param name="Button1">显示的第一个按钮,默认为 “确定”。</param>
  298. ''' <param name="Button2">显示的第二个按钮,默认为空。</param>
  299. ''' <param name="IsWarn">是否为警告弹窗,若为 True,弹窗配色和背景会变为红色。</param>
  300. Public Function MyMsgBoxSelect(Selections As IEnumerable(Of IMyRadio), Optional Title As String = "提示", Optional Button1 As String = "确定", Optional Button2 As String = "", Optional IsWarn As Boolean = False) As Integer?
  301. '将弹窗列入队列
  302. Dim Converter As New MyMsgBoxConverter With {.Type = MyMsgBoxType.Select, .Button1 = Button1, .Button2 = Button2, .Content = Selections, .IsWarn = IsWarn, .Title = Title}
  303. WaitingMyMsgBox.Enqueue(Converter)
  304. '虽然我也不知道这是啥但是能用就成了 :)
  305. Try
  306. If FrmMain IsNot Nothing Then FrmMain.DragStop()
  307. If RunInUi() Then MyMsgBoxTick()
  308. ComponentDispatcher.PushModal()
  309. Dispatcher.PushFrame(Converter.WaitFrame)
  310. Finally
  311. ComponentDispatcher.PopModal()
  312. End Try
  313. Logger.Info($"选择弹框返回:{If(Converter.Result, "null")}")
  314. Return Converter.Result
  315. End Function
  316. ''' <summary>
  317. ''' 等待显示的弹窗。
  318. ''' </summary>
  319. Public WaitingMyMsgBox As New ConcurrentQueue(Of MyMsgBoxConverter)
  320. Public Sub MyMsgBoxTick()
  321. Try
  322. If FrmMain?.PanMsg Is Nothing OrElse FrmMain.WindowState = WindowState.Minimized Then Return
  323. Dim TargetMsgBox As MyMsgBoxConverter = Nothing
  324. If FrmMain.PanMsg.Children.Count > 0 Then
  325. '弹窗中
  326. FrmMain.PanMsg.Visibility = Visibility.Visible
  327. ElseIf WaitingMyMsgBox.TryDequeue(TargetMsgBox) Then
  328. '没有弹窗,显示一个等待的弹窗
  329. FrmMain.PanMsg.Visibility = Visibility.Visible
  330. Select Case TargetMsgBox.Type
  331. Case MyMsgBoxType.Input
  332. FrmMain.PanMsg.Children.Add(New MyMsgInput(TargetMsgBox))
  333. Case MyMsgBoxType.Select
  334. FrmMain.PanMsg.Children.Add(New MyMsgSelect(TargetMsgBox))
  335. Case MyMsgBoxType.Text
  336. FrmMain.PanMsg.Children.Add(New MyMsgText(TargetMsgBox))
  337. Case MyMsgBoxType.Login
  338. FrmMain.PanMsg.Children.Add(New MyMsgLogin(TargetMsgBox))
  339. End Select
  340. Else
  341. '没有弹窗,没有等待的弹窗
  342. If FrmMain.PanMsg.Visibility <> Visibility.Collapsed Then FrmMain.PanMsg.Visibility = Visibility.Collapsed
  343. End If
  344. Catch ex As Exception
  345. Logger.Error(ex, "处理等待中的弹窗失败")
  346. End Try
  347. End Sub
  348. #End Region
  349. #Region "页面声明"
  350. '在最后进行页面声明,避免颜色尚未加载完毕
  351. '窗体声明
  352. Public FrmMain As FormMain
  353. Public FrmStart As SplashScreen
  354. '页面声明(出于单元测试考虑,初始化页面已转入 FormMain 中)
  355. Public FrmLaunchLeft As PageLaunchLeft
  356. Public FrmLaunchRight As PageLaunchRight
  357. Public FrmSelectLeft As PageSelectLeft
  358. Public FrmSelectRight As PageSelectRight
  359. Public FrmSpeedLeft As PageSpeedLeft
  360. Public FrmSpeedRight As PageSpeedRight
  361. '联机页面声明
  362. Public FrmLinkMain As PageLinkMain
  363. '下载页面声明
  364. Public FrmDownloadLeft As PageDownloadLeft
  365. Public FrmDownloadInstall As PageDownloadInstall
  366. Public FrmDownloadMod As PageDownloadMod
  367. Public FrmDownloadPack As PageDownloadPack
  368. Public FrmDownloadDataPack As PageDownloadDataPack
  369. Public FrmDownloadShader As PageDownloadShader
  370. Public FrmDownloadResourcePack As PageDownloadResourcePack
  371. '设置页面声明
  372. Public FrmSetupLeft As PageSetupLeft
  373. Public FrmSetupLaunch As PageSetupLaunch
  374. Public FrmSetupUI As PageSetupUI
  375. Public FrmSetupSystem As PageSetupSystem
  376. Public FrmSetupLink As PageSetupLink
  377. '其他页面声明
  378. Public FrmOtherLeft As PageOtherLeft
  379. Public FrmOtherHelp As PageOtherHelp
  380. Public FrmOtherAbout As PageOtherAbout
  381. Public FrmOtherTest As PageOtherTest
  382. '登录页面声明
  383. Public FrmLoginLegacy As PageLoginLegacy
  384. Public FrmLoginNide As PageLoginNide
  385. Public FrmLoginNideSkin As PageLoginNideSkin
  386. Public FrmLoginAuth As PageLoginAuth
  387. Public FrmLoginAuthSkin As PageLoginAuthSkin
  388. Public FrmLoginMs As PageLoginMs
  389. Public FrmLoginMsSkin As PageLoginMsSkin
  390. '版本设置页面声明
  391. Public FrmInstanceLeft As PageInstanceLeft
  392. Public FrmInstanceOverall As PageInstanceOverall
  393. Public FrmInstanceMod As PageInstanceMod
  394. Public FrmInstanceModDisabled As PageInstanceModDisabled
  395. Public FrmInstanceSetup As PageInstanceSetup
  396. Public FrmInstanceExport As PageInstanceExport
  397. Public FrmDownloadModify As PageDownloadModify
  398. '资源信息分页声明
  399. Public FrmDownloadResourceDetail As PageDownloadResourceDetail
  400. #End Region
  401. #Region "帮助"
  402. Public Class HelpEntry
  403. ''' <summary>
  404. ''' 原始信息路径。用于刷新。
  405. ''' </summary>
  406. Public RawPath As String
  407. '基础
  408. ''' <summary>
  409. ''' 显示标题。
  410. ''' </summary>
  411. Public Title As String
  412. ''' <summary>
  413. ''' 显示描述。
  414. ''' </summary>
  415. Public Desc As String
  416. ''' <summary>
  417. ''' 检索关键字。
  418. ''' </summary>
  419. Public Search As String
  420. ''' <summary>
  421. ''' 用于分类的标签列表。
  422. ''' </summary>
  423. Public Types As List(Of String)
  424. '显示(可选)
  425. ''' <summary>
  426. ''' 帮助项的自定义图标。可能为 Nothing。
  427. ''' </summary>
  428. Public Logo As String = Nothing
  429. ''' <summary>
  430. ''' 是否显示在搜索结果。默认为 True。
  431. ''' </summary>
  432. Public ShowInSearch As Boolean = True
  433. ''' <summary>
  434. ''' 是否在公开版的 PCL 中显示(这会影响主页与搜索)。默认为 True。
  435. ''' </summary>
  436. Public ShowInPublic As Boolean = True
  437. ''' <summary>
  438. ''' 是否在快照版的 PCL 中显示(这会影响主页与搜索)。默认为 True。
  439. ''' </summary>
  440. Public ShowInSnapshot As Boolean = True
  441. '动作
  442. ''' <summary>
  443. ''' 是否为 “执行事件”。
  444. ''' </summary>
  445. Public IsEvent As Boolean
  446. Public EventType As CustomEvent.EventType
  447. Public EventData As String
  448. ''' <summary>
  449. ''' 若非执行事件,其对应的 .xaml 本地文件内容。
  450. ''' </summary>
  451. Public XamlContent As String
  452. '转换
  453. ''' <summary>
  454. ''' 从文件初始化 HelpEntry 对象,失败会抛出异常。
  455. ''' </summary>
  456. Public Sub New(FilePath As String)
  457. RawPath = FilePath
  458. If Not FileUtils.Exists(FilePath) Then Throw New FileNotFoundException("未找到帮助文件:" & FilePath, FilePath)
  459. Dim JsonData As JObject = ArgumentReplace(FileUtils.ReadAsString(FilePath), AddressOf StringUtils.XmlEscape).DeserializeJson()
  460. '加载常规信息
  461. If JsonData("Title") IsNot Nothing Then
  462. Title = JsonData("Title")
  463. Else
  464. Throw New ArgumentException("未找到 Title 项")
  465. End If
  466. Desc = If(JsonData("Description"), "")
  467. Search = If(JsonData("Keywords"), "")
  468. Logo = JsonData("Logo") '为保持 Nothing,不要加 If
  469. ShowInSearch = If(JsonData("ShowInSearch"), ShowInSearch)
  470. ShowInPublic = If(JsonData("ShowInPublic"), ShowInPublic)
  471. ShowInSnapshot = If(JsonData("ShowInSnapshot"), ShowInSnapshot)
  472. Types = New List(Of String)
  473. For Each NameOfType In If(JsonData("Types"), New JArray)
  474. Types.Add(NameOfType)
  475. Next
  476. '加载事件信息
  477. If If(JsonData("IsEvent"), False) Then
  478. EventType = JsonData("EventType").ToObject(Of CustomEvent.EventType)
  479. EventData = If(JsonData("EventData"), "")
  480. IsEvent = True
  481. Else
  482. Dim XamlAddress As String = Path.ChangeExtension(FilePath, ".xaml")
  483. If FileUtils.Exists(XamlAddress) Then
  484. XamlContent = FileUtils.ReadAsString(XamlAddress)
  485. IsEvent = False
  486. Else
  487. Throw New FileNotFoundException("未找到帮助条目 .json 对应的 .xaml 文件(" & XamlAddress & ")")
  488. End If
  489. End If
  490. End Sub
  491. ''' <summary>
  492. ''' 获取该 HelpEntry 对应的 MyListItem。
  493. ''' </summary>
  494. Public Function ToListItem() As MyListItem
  495. Return SetToListItem(New MyListItem)
  496. End Function
  497. ''' <summary>
  498. ''' 将属性设置入一个现有的 ListItem。
  499. ''' </summary>
  500. Public Function SetToListItem(Item As MyListItem) As MyListItem
  501. Dim Logo As String
  502. If IsEvent Then
  503. If EventType = CustomEvent.EventType.弹出窗口 Then
  504. Logo = PathImage & "Blocks/GrassPath.png"
  505. Else
  506. Logo = PathImage & "Blocks/CommandBlock.png"
  507. End If
  508. Else
  509. Logo = PathImage & "Blocks/Grass.png"
  510. End If
  511. '设置属性
  512. With Item
  513. .SnapsToDevicePixels = True
  514. .Title = Title
  515. .Info = Desc
  516. .Logo = If(Me.Logo, Logo)
  517. .Height = 42
  518. .Type = MyListItem.CheckType.Clickable
  519. .Tag = Me
  520. End With
  521. CustomEventService.SetEventType(Item, CustomEvent.EventType.None) '清空自定义事件属性,它们会被下面的点击事件处理
  522. CustomEventService.SetEventData(Item, Nothing)
  523. '项目的点击事件
  524. AddHandler Item.Click, Sub(sender, e) PageOtherHelp.OnItemClick(sender.Tag)
  525. Return Item
  526. End Function
  527. End Class
  528. Public HelpLoader As New LoaderTask(Of Integer, List(Of HelpEntry))("Help Page", AddressOf HelpLoad,, ThreadPriority.BelowNormal)
  529. Private ReadOnly HelpLoadLock As New Object
  530. ''' <summary>
  531. ''' 初始化帮助列表对象。
  532. ''' </summary>
  533. Private Sub HelpLoad(Loader As LoaderTask(Of Integer, List(Of HelpEntry)))
  534. SyncLock HelpLoadLock '避免重复解压文件导致出错
  535. Try
  536. '解压内置文件
  537. HelpTryExtract()
  538. '遍历文件
  539. Dim FileList As New List(Of String)
  540. Try
  541. Dim IgnoreList As New List(Of String)
  542. '读取自定义文件
  543. If DirectoryUtils.Exists(Paths.Base & "PCL\Help\") Then
  544. For Each File In DirectoryUtils.EnumerateFiles(Paths.Base & "PCL\Help\", True)
  545. Select Case PathUtils.GetExtension(File)
  546. Case "helpignore"
  547. '加载忽略列表
  548. Logger.Info($"发现 .helpignore 文件:{File}")
  549. For Each Line In FileUtils.ReadAsLines(File, True)
  550. Dim RealString As String = Line.BeforeFirst("#").Trim
  551. If String.IsNullOrWhiteSpace(RealString) Then Continue For
  552. IgnoreList.Add(RealString)
  553. Logger.Trace($"> {RealString}")
  554. Next
  555. Case "json"
  556. FileList.Add(File)
  557. End Select
  558. Next
  559. End If
  560. Logger.Info($"已扫描 PCL 文件夹下的帮助文件,目前总计 {FileList.Count} 条")
  561. '读取自带文件
  562. For Each File In DirectoryUtils.EnumerateFiles(PathTemp & "Help", True)
  563. '跳过非 json 文件与以 . 开头的文件夹
  564. If PathUtils.RemoveLastPart(File).Substring((PathTemp & "Help").Length).Contains("\.") OrElse PathUtils.GetExtension(File) <> "json" Then Continue For
  565. '检查忽略列表
  566. Dim RealPath As String = File.Substring((PathTemp & "Help\").Length)
  567. For Each Ignore In IgnoreList
  568. If RealPath.RegexCheck(Ignore) Then
  569. Logger.Trace($"已忽略 {RealPath}:{Ignore}")
  570. GoTo NextFile
  571. End If
  572. Next
  573. FileList.Add(File)
  574. NextFile:
  575. Next
  576. Logger.Info($"已扫描缓存文件夹下的帮助文件,目前总计 {FileList.Count} 条")
  577. Catch ex As Exception
  578. Logger.Error(ex, "检查帮助文件夹失败", LogBehavior.Alert)
  579. End Try
  580. If Loader.IsCanceled Then Return
  581. '将文件实例化
  582. Dim Dict As New List(Of HelpEntry)
  583. For Each FilePath As String In FileList
  584. Try
  585. Dim Entry As New HelpEntry(FilePath)
  586. Dict.Add(Entry)
  587. Logger.Trace($"已加载的帮助条目:{Entry.Title} ← {FilePath}")
  588. Catch ex As Exception
  589. Logger.Error(ex, $"初始化帮助条目失败({FilePath})", LogBehavior.Alert)
  590. End Try
  591. Next
  592. '回设
  593. If Not Dict.Any() Then Throw New Exception("未找到可用的帮助;若不需要帮助页面,可以在 设置 → 个性化 → 功能隐藏 中将其隐藏")
  594. If Loader.IsCanceled Then Return
  595. Loader.Output = Dict
  596. Catch ex As Exception
  597. Logger.Warn(ex, "帮助列表初始化失败")
  598. Throw
  599. End Try
  600. End SyncLock
  601. End Sub
  602. ''' <summary>
  603. ''' 尝试解压内置帮助文件。
  604. ''' </summary>
  605. Public Sub HelpTryExtract()
  606. If Settings.Get(Of Integer)("SystemHelpVersion") <> VersionCode OrElse Not FileUtils.Exists(PathTemp & "Help\启动器\备份设置.xaml") Then
  607. DirectoryUtils.Delete(PathTemp & "Help")
  608. ExtractResources(PathTemp & "Cache\Help.zip", "Help")
  609. FileUtils.ExtractToDirectory(PathTemp & "Cache\Help.zip", PathTemp & "Help")
  610. Settings.Set("SystemHelpVersion", VersionCode)
  611. Logger.Info($"已解压内置帮助文件,目前状态:{FileUtils.Exists(PathTemp + "Help\启动器\备份设置.xaml")}")
  612. End If
  613. End Sub
  614. #End Region
  615. #Region "愚人节"
  616. Private _IsAprilEnabled As Boolean? = Nothing
  617. Public ReadOnly Property IsAprilEnabled As Boolean
  618. Get
  619. If _IsAprilEnabled Is Nothing Then
  620. _IsAprilEnabled =
  621. Date.Now.Month = 4 AndAlso Date.Now.Day = 1 AndAlso
  622. Settings.Get(Of Integer)("AprilYear") <> Date.Now.Year '成功后同年内则不再触发
  623. End If
  624. Return _IsAprilEnabled.Value
  625. End Get
  626. End Property
  627. Public IsAprilGiveup As Boolean = False
  628. Private AprilDifficultiedDistance As Integer = 0
  629. Private Sub TimerFool()
  630. Try
  631. If FrmLaunchLeft Is Nothing OrElse FrmLaunchLeft.AprilPosTrans Is Nothing OrElse FrmMain.lastMouseArg Is Nothing Then Return
  632. If IsAprilGiveup OrElse FrmMain.PageCurrent <> FormMain.PageType.Launch OrElse AniControlEnabled <> 0 OrElse Not FrmLaunchLeft.BtnLaunch.IsLoaded Then Return
  633. '计算是否空闲
  634. Dim MousePos = FrmMain.lastMouseArg.GetPosition(FrmMain)
  635. Static IdieCount As Integer = 0
  636. Static MousePosLast As New Point(0, 0)
  637. If MousePos = MousePosLast Then
  638. IdieCount += 1
  639. Else
  640. MousePosLast = MousePos
  641. IdieCount = 0
  642. End If
  643. '计算躲避移动
  644. Dim Direction As Vector
  645. Dim Distance As Double
  646. Dim ButtonWidth = FrmLaunchLeft.BtnLaunch.ActualWidth / 2, ButtonHeight = FrmLaunchLeft.BtnLaunch.ActualHeight / 2
  647. Dim Vec As Vector = FrmMain.lastMouseArg.GetPosition(FrmLaunchLeft.BtnLaunch) - New Vector(ButtonWidth, ButtonHeight)
  648. Dim Dir As New Vector(Vec.X, Vec.Y)
  649. Dir.Normalize()
  650. Direction = -Dir
  651. Distance = New Vector(Math.Max(0, Math.Abs(Vec.X) - ButtonWidth), Math.Max(0, Math.Abs(Vec.Y) - ButtonHeight)).Length
  652. Dim BreathScale = Math.Sin(Timer150Count / 37.5 * Math.PI)
  653. Dim Difficulty As Double = 1 / (1 + (AprilDifficultiedDistance / 6000) ^ 2) + 0.25 '难度,初始为 1.25x,6000 距离为 0.75x,12000 为 0.5x,24000 为 0.256x,最低 0.25x
  654. Dim Acc = Math.Max(0, -0.65 - Math.Log((Distance / Difficulty + 0.4) / 200)) * Direction * Difficulty '加速度
  655. 'FrmMain.Title = CInt(AprilTotalDistance) & " - " & Difficulty
  656. '5s 不动时回到起始点
  657. If IdieCount >= 64 * 5 Then
  658. Dim SafeDist As Vector = FrmMain.lastMouseArg.GetPosition(FrmMain.PanMain) - New Vector(ButtonWidth, FrmMain.PanMain.ActualHeight - ButtonHeight * 3)
  659. Dim Back As New Vector(FrmLaunchLeft.AprilPosTrans.X, FrmLaunchLeft.AprilPosTrans.Y)
  660. If SafeDist.Length > 250 AndAlso Back.Length > 0.4 Then
  661. Acc -= Back * 0.0005
  662. Back.Normalize()
  663. Acc -= Back * 0.15
  664. End If
  665. End If
  666. '回到边界
  667. Static Speed As New Vector(0, 0)
  668. Dim Relative As Point = FrmLaunchLeft.BtnLaunch.TranslatePoint(New Point(0, 0), FrmMain.PanForm)
  669. If Relative.X < -ButtonWidth * 2 Then
  670. FrmLaunchLeft.AprilPosTrans.X += FrmMain.PanForm.ActualWidth + ButtonWidth * 2 '离开左边界
  671. Speed.X -= 80
  672. If Relative.Y < 0 Then
  673. FrmLaunchLeft.AprilPosTrans.Y += ButtonHeight * 2.5
  674. ElseIf Relative.Y > FrmMain.PanForm.ActualHeight - ButtonHeight * 2 Then
  675. FrmLaunchLeft.AprilPosTrans.Y -= ButtonHeight * 2.5
  676. End If
  677. ElseIf Relative.X > FrmMain.PanForm.ActualWidth Then
  678. FrmLaunchLeft.AprilPosTrans.X -= FrmMain.PanForm.ActualWidth + ButtonWidth * 2 '离开右边界
  679. Speed.X += 80
  680. If Relative.Y < 0 Then
  681. FrmLaunchLeft.AprilPosTrans.Y += ButtonHeight * 2.5
  682. ElseIf Relative.Y > FrmMain.PanForm.ActualHeight - ButtonHeight * 2 Then
  683. FrmLaunchLeft.AprilPosTrans.Y -= ButtonHeight * 2.5
  684. End If
  685. ElseIf Relative.Y < -ButtonHeight * 2 Then
  686. FrmLaunchLeft.AprilPosTrans.Y += FrmMain.PanForm.ActualHeight + ButtonHeight * 2 '离开上边界
  687. Speed.Y -= 25
  688. If Relative.X < 0 Then
  689. FrmLaunchLeft.AprilPosTrans.X += ButtonWidth * 2
  690. ElseIf Relative.X > FrmMain.PanForm.ActualWidth - ButtonWidth * 2 Then
  691. FrmLaunchLeft.AprilPosTrans.X -= ButtonWidth * 2
  692. End If
  693. ElseIf Relative.Y > FrmMain.PanForm.ActualHeight Then
  694. FrmLaunchLeft.AprilPosTrans.Y -= FrmMain.PanForm.ActualHeight + ButtonHeight * 2 '离开下边界
  695. Speed.Y += 25
  696. If Relative.X < 0 Then
  697. FrmLaunchLeft.AprilPosTrans.X += ButtonWidth * 2
  698. ElseIf Relative.X > FrmMain.PanForm.ActualWidth - ButtonWidth * 2 Then
  699. FrmLaunchLeft.AprilPosTrans.X -= ButtonWidth * 2
  700. End If
  701. End If
  702. '移动
  703. Speed = Speed * 0.8 + Acc
  704. Dim SpeedValue = Math.Min(60, Speed.Length)
  705. If SpeedValue < 0.01 Then Return
  706. Speed.Normalize()
  707. Speed *= SpeedValue
  708. AprilDifficultiedDistance += SpeedValue
  709. FrmLaunchLeft.AprilPosTrans.X += Speed.X
  710. FrmLaunchLeft.AprilPosTrans.Y += Speed.Y
  711. '大小改变
  712. FrmLaunchLeft.AprilScaleTrans.ScaleX = (1 - (Math.Abs(Direction.X) - Math.Abs(Direction.Y)) * (SpeedValue / 160)).Clamp(0.2, 1.8)
  713. FrmLaunchLeft.AprilScaleTrans.ScaleY = (1 - (Math.Abs(Direction.Y) - Math.Abs(Direction.X)) * (SpeedValue / 100)).Clamp(0.2, 1.8)
  714. '放弃提示
  715. Static GiveUpDistance As Double = -1500
  716. GiveUpDistance += SpeedValue
  717. If GiveUpDistance > 2500 Then
  718. GiveUpDistance = 0
  719. Select Case RandomInteger(0, 3)
  720. Case 0
  721. Hint("放弃吧!只需要点一下右下角的小白旗……", HintType.Red)
  722. Case 1
  723. Hint("看到右下角的那面小白旗了吗?", HintType.Red)
  724. Case 2
  725. Hint("这里建议点一下右下角的小白旗投降呢.jpg", HintType.Red)
  726. Case 3
  727. Hint("右下角的小白旗永远等着你……", HintType.Red)
  728. End Select
  729. End If
  730. Catch ex As Exception
  731. Logger.Error(ex, "愚人节移动出错")
  732. End Try
  733. End Sub
  734. #End Region
  735. #Region "系统"
  736. ''' <summary>
  737. ''' 把某个 PCL 窗口拖到最前面。
  738. ''' </summary>
  739. Public Sub ShowWindowToTop(Handle As IntPtr)
  740. Try
  741. PostMessage(Handle, 400 * 16 + 2, 0, 0)
  742. SetForegroundWindow(Handle) '不在这里放不行,神秘 WinAPI,建议别动
  743. Catch ex As Exception
  744. Logger.Error(ex, "设置窗口置顶失败", LogBehavior.Toast)
  745. End Try
  746. End Sub
  747. Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ClassName As String, WindowName As String) As IntPtr
  748. Public Declare Function SetForegroundWindow Lib "user32" (hWnd As IntPtr) As Integer
  749. Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (hWnd As IntPtr, msg As UInteger, wParam As Long, lParam As Long) As Boolean
  750. ''' <summary>
  751. ''' 将特定程序设置为使用高性能显卡启动。
  752. ''' 如果失败,则抛出异常。
  753. ''' </summary>
  754. Public Sub SetGPUPreference(Executeable As String)
  755. Const REG_KEY As String = "HKEY_CURRENT_USER\Software\Microsoft\DirectX\UserGpuPreferences"
  756. Const REG_VALUE As String = "GpuPreference=2;"
  757. '查看现有设置
  758. If RegistryUtils.Read(REG_KEY, Executeable).result?.ToString() = REG_VALUE Then
  759. Logger.Info($"无需调整显卡设置:{Executeable}")
  760. Return
  761. End If
  762. '写入新设置
  763. RegistryUtils.Write(REG_KEY, Executeable, REG_VALUE)
  764. Logger.Info($"已调整显卡设置:{Executeable}")
  765. End Sub
  766. ''' <summary>
  767. ''' 对替换标记进行处理。会对替换内容使用 EscapeHandler 进行转义。
  768. ''' </summary>
  769. Public Function ArgumentReplace(Text As String, Optional EscapeHandler As Func(Of String, String) = Nothing, Optional ReplaceTime As Boolean = True) As String
  770. If Text Is Nothing OrElse Not Text.Contains("{") Then Return Text
  771. '预处理(注意,文件夹必须以 \ 结尾)
  772. Static Replacer As Func(Of String, String) =
  773. Function(s As String) As String
  774. If s Is Nothing Then Return ""
  775. If EscapeHandler Is Nothing Then Return s
  776. If s.Contains(":\") Then
  777. Dim IsFolder = s.EndsWithF("\") OrElse s.EndsWithF("/")
  778. s = PathUtils.ToShortPath(s)
  779. If IsFolder Then s = PathUtils.AddSlashSuffix(s)
  780. End If
  781. Return EscapeHandler(s)
  782. End Function
  783. '基础
  784. Text = Text.Replace("{pcl_version}", Replacer(VersionBaseName))
  785. Text = Text.Replace("{pcl_version_code}", Replacer(VersionCode))
  786. Text = Text.Replace("{pcl_version_branch}", Replacer(BuildTypeDisplay))
  787. Text = Text.Replace("{pcl_build_type}", Replacer(BuildType.ToString))
  788. Text = Text.Replace("{pcl_branch}", Replacer(VersionBranchMain))
  789. Text = Text.Replace("{identify}", Replacer(Identify))
  790. Text = Text.Replace("{path}", Replacer(Paths.Base))
  791. Text = Text.Replace("{path_with_name}", Replacer(PathExe))
  792. Text = Text.Replace("{path_temp}", Replacer(PathTemp))
  793. Text = Text.Replace("{pcl_md5}", Function() Replacer(CryptographyUtils.ComputeFileHash(PathExe, CryptographyUtils.HashMethod.Md5)))
  794. Text = Text.Replace("{pcl_sha1}", Function() Replacer(CryptographyUtils.ComputeFileHash(PathExe, CryptographyUtils.HashMethod.Sha1)))
  795. '时间
  796. If ReplaceTime Then '在窗口标题中,时间会被后续动态替换,所以此时不应该替换
  797. Text = Text.Replace("{date}", Replacer(Date.Now.ToString("yyyy'/'M'/'d")))
  798. Text = Text.Replace("{time}", Replacer(Date.Now.ToString("HH':'mm':'ss")))
  799. End If
  800. 'Minecraft
  801. Text = Text.Replace("{java}", Replacer(McLaunchJavaSelected?.Folder))
  802. Text = Text.Replace("{minecraft}", Replacer(McFolderSelected))
  803. If McInstanceSelected?.IsLoaded Then
  804. Text = Text.Replace("{version_path}", Replacer(McInstanceSelected.PathVersion)) : Text = Text.Replace("{verpath}", Replacer(McInstanceSelected.PathVersion))
  805. Text = Text.Replace("{version_indie}", Replacer(McInstanceSelected.PathIndie)) : Text = Text.Replace("{verindie}", Replacer(McInstanceSelected.PathIndie))
  806. Text = Text.Replace("{name}", Replacer(McInstanceSelected.Name))
  807. If {"unknown", "old", "pending"}.Contains(McInstanceSelected.Version.VanillaName.Lower) Then
  808. Text = Text.Replace("{version}", Replacer(McInstanceSelected.Name))
  809. Else
  810. Text = Text.Replace("{version}", Replacer(McInstanceSelected.Version.VanillaName))
  811. End If
  812. Text = Text.Replace("{forge}", Replacer(If(McInstanceSelected.Version.ModLoaders.HasFlagF(ModLoaders.Forge), McInstanceSelected.Version.ModLoaderVersions(ModLoaders.Forge), "")))
  813. Text = Text.Replace("{fabric}", Replacer(If(McInstanceSelected.Version.ModLoaders.HasFlagF(ModLoaders.Fabric), McInstanceSelected.Version.ModLoaderVersions(ModLoaders.Fabric), "")))
  814. Text = Text.Replace("{neoforge}", Replacer(If(McInstanceSelected.Version.ModLoaders.HasFlagF(ModLoaders.NeoForge), McInstanceSelected.Version.ModLoaderVersions(ModLoaders.NeoForge), "")))
  815. Text = Text.Replace("{liteloader}", Replacer(If(McInstanceSelected.Version.ModLoaders.HasFlagF(ModLoaders.LiteLoader), "true", "")))
  816. Else
  817. Text = Text.Replace("{version_path}", Replacer(Nothing)) : Text = Text.Replace("{verpath}", Replacer(Nothing))
  818. Text = Text.Replace("{version_indie}", Replacer(Nothing)) : Text = Text.Replace("{verindie}", Replacer(Nothing))
  819. Text = Text.Replace("{name}", Replacer(Nothing))
  820. Text = Text.Replace("{version}", Replacer(Nothing))
  821. Text = Text.Replace("{forge}", Replacer(Nothing))
  822. Text = Text.Replace("{fabric}", Replacer(Nothing))
  823. Text = Text.Replace("{neoforge}", Replacer(Nothing))
  824. Text = Text.Replace("{liteloader}", Replacer(Nothing))
  825. End If
  826. '登录信息
  827. If McLoginLoader.State = LoadState.Finished Then
  828. Text = Text.Replace("{user}", Replacer(McLoginLoader.Output.Name))
  829. Text = Text.Replace("{uuid}", Replacer(McLoginLoader.Output.Uuid?.Lower))
  830. Select Case McLoginLoader.Input.Type
  831. Case McLoginType.Legacy
  832. Text = Text.Replace("{login}", Replacer("离线"))
  833. Case McLoginType.Ms
  834. Text = Text.Replace("{login}", Replacer("正版"))
  835. Case McLoginType.Nide
  836. Text = Text.Replace("{login}", Replacer("统一通行证"))
  837. Case McLoginType.Auth
  838. Text = Text.Replace("{login}", Replacer("Authlib-Injector"))
  839. End Select
  840. Else
  841. Text = Text.Replace("{user}", Replacer(Nothing))
  842. Text = Text.Replace("{uuid}", Replacer(Nothing))
  843. Text = Text.Replace("{login}", Replacer(Nothing))
  844. End If
  845. '高级
  846. Text = Text.RegexReplace("\{hint\}", Function() Replacer(PageOtherTest.GetRandomHint()))
  847. Text = Text.RegexReplace("\{cave\}", Function() Replacer(PageOtherTest.GetRandomCave()))
  848. Text = Text.RegexReplace("\{setup:([a-zA-Z0-9]+)\}", Function(m) Replacer(Settings.GetSafe(m.Groups(1).Value, McInstanceSelected)))
  849. Text = Text.RegexReplace("\{varible:([^:\}]+)(?::([^\}]+))?\}", Function(m) Replacer(RegistryUtils.TryRead($"HKEY_CURRENT_USER\Software\{RegFolder}", $"CustomEvent{m.Groups(1).Value}", m.Groups(2).Value)))
  850. Text = Text.RegexReplace("\{variable:([^:\}]+)(?::([^\}]+))?\}", Function(m) Replacer(RegistryUtils.TryRead($"HKEY_CURRENT_USER\Software\{RegFolder}", $"CustomEvent{m.Groups(1).Value}", m.Groups(2).Value)))
  851. Return Text
  852. End Function
  853. #End Region
  854. #Region "任务缓存"
  855. Private IsTaskTempCleared As Boolean = False
  856. Private IsTaskTempClearing As Boolean = False
  857. ''' <summary>
  858. ''' 尝试清理任务缓存文件夹。
  859. ''' 在整次运行中只会实际清理一次。
  860. ''' </summary>
  861. Public Sub TryClearTaskTemp()
  862. If Not IsTaskTempCleared Then
  863. IsTaskTempCleared = True
  864. IsTaskTempClearing = True
  865. Try
  866. Logger.Info("开始清理任务缓存文件夹")
  867. DirectoryUtils.Delete($"{OsDrive}ProgramData\PCL\TaskTemp\")
  868. DirectoryUtils.Delete($"{PathTemp}TaskTemp\")
  869. Logger.Info("已清理任务缓存文件夹")
  870. Catch ex As Exception
  871. Logger.Warn(ex, "清理任务缓存文件夹失败")
  872. Finally
  873. IsTaskTempClearing = False
  874. End Try
  875. ElseIf IsTaskTempClearing Then
  876. '等待另一个清理步骤完成
  877. Do While IsTaskTempClearing
  878. Thread.Sleep(1)
  879. Loop
  880. End If
  881. End Sub
  882. ''' <summary>
  883. ''' 申请一个可用于任务缓存的临时文件夹,以 \ 结尾。这些文件夹无需进行后续清理。
  884. ''' 若所有缓存位置均没有权限,会抛出异常。
  885. ''' </summary>
  886. ''' <param name="RequireNonSpace">是否要求路径不包含空格。</param>
  887. Public Function RequestTaskTempFolder(Optional RequireNonSpace As Boolean = False) As String
  888. TryClearTaskTemp()
  889. Dim ResultFolder As String
  890. Try
  891. ResultFolder = $"{PathTemp}TaskTemp\{GetUuid()}-{RandomInteger(0, 1000000)}\"
  892. If RequireNonSpace AndAlso ResultFolder.Contains(" ") Then Exit Try '带空格
  893. DirectoryUtils.Create(ResultFolder)
  894. CheckPermissionWithException(ResultFolder)
  895. Return ResultFolder
  896. Catch
  897. End Try
  898. '使用备用路径
  899. ResultFolder = $"{OsDrive}ProgramData\PCL\TaskTemp\{GetUuid()}-{RandomInteger(0, 1000000)}\"
  900. DirectoryUtils.Create(ResultFolder)
  901. CheckPermission(ResultFolder)
  902. Return ResultFolder
  903. End Function
  904. #End Region
  905. #Region "反馈与遥测"
  906. '反馈
  907. Public Sub Feedback(Optional ShowMsgbox As Boolean = True, Optional ForceOpenLog As Boolean = False)
  908. On Error Resume Next
  909. FeedbackInfo()
  910. If ForceOpenLog OrElse (ShowMsgbox AndAlso MyMsgBox("若你在汇报一个 Bug,请点击 打开文件夹 按钮,并上传 Log(1~5).txt 中包含错误信息的文件。" & vbCrLf & "游戏崩溃一般与启动器无关,请不要因为游戏崩溃而提交反馈。", "反馈提交提醒", "打开文件夹", "不需要") = 1) Then
  911. OpenExplorer(Paths.Base & "PCL\Log1.txt")
  912. End If
  913. OpenWebsite("https://github.com/Meloong-Git/PCL/issues/")
  914. End Sub
  915. ''' <summary>
  916. ''' 在日志中输出系统诊断信息。
  917. ''' </summary>
  918. Public Sub FeedbackInfo()
  919. On Error Resume Next
  920. Logger.Warn($"诊断信息:{vbCrLf}" &
  921. "操作系统:" & My.Computer.Info.OSFullName & vbCrLf &
  922. "剩余内存:" & Int(My.Computer.Info.AvailablePhysicalMemory / 1024 / 1024) & " M / " & Int(My.Computer.Info.TotalPhysicalMemory / 1024 / 1024) & " M" & vbCrLf &
  923. "DPI:" & DPI & "(" & Math.Round(DPI / 96, 2) * 100 & "%)" & vbCrLf &
  924. "MC 文件夹:" & If(McFolderSelected, "Nothing") & vbCrLf &
  925. "文件位置:" & Paths.Base)
  926. End Sub
  927. '遥测
  928. Public Sub Telemetry([Event] As String, ParamArray Datas As String())
  929. If BuildType = BuildTypes.Debug Then Return '开发版不上传遥测
  930. If Not Settings.Get(Of Boolean)("SystemSystemTelemetry") Then Return '用户关闭了遥测
  931. If Not ClsBaseUrl.StartsWithF("http") Then Return '开源版没有设置遥测地址
  932. RunInNewThread(
  933. Sub()
  934. Try
  935. Logger.Info($"匿名数据上报:{[Event]}")
  936. Dim Url As String = $"{ClsBaseUrl}&Event={StringUtils.UrlEscape([Event])}"
  937. For i = 0 To Datas.Length - 1 Step 2
  938. Url &= "&" & StringUtils.UrlEscape(Datas(i)) & "=" & StringUtils.UrlEscape(Datas(i + 1).ReplaceLineEndings(vbLf, mergeMultiple:=True))
  939. Next
  940. NetRequestByClient(Url, MakeLog:=False)
  941. Catch ex As Exception
  942. Logger.Warn(ex, "匿名数据上报失败")
  943. End Try
  944. End Sub, "Telemetry", ThreadPriority.Lowest)
  945. End Sub
  946. #End Region
  947. Public DragControl = Nothing
  948. Private Timer4Count As Integer = 0
  949. Private Timer150Count As Integer = 0
  950. Private Sub TimerMain()
  951. Try
  952. #Region "每 50ms 执行一次的代码"
  953. HintTick()
  954. MyMsgBoxTick()
  955. FrmMain.DragTick()
  956. LoaderTaskbarProgressRefresh()
  957. If ThemeDontClick = 2 Then ThemeRefresh()
  958. #End Region
  959. Catch ex As Exception
  960. Logger.Error(ex, "短程主时钟执行异常", LogBehavior.AlertThenCrash)
  961. End Try
  962. Timer4Count += 1
  963. If Timer4Count = 4 Then
  964. Timer4Count = 0
  965. Try
  966. #Region "每 250ms 执行一次的代码"
  967. If ThemeNow = 12 Then ThemeRefresh()
  968. #End Region
  969. Catch ex As Exception
  970. Logger.Warn(ex, "中程主时钟执行异常")
  971. End Try
  972. End If
  973. Timer150Count += 1
  974. If Timer150Count = 150 Then
  975. Timer150Count = 0
  976. Try
  977. #Region "每 7.5s 执行一次的代码"
  978. If FrmMain.BtnExtraApril_ShowCheck AndAlso AprilDifficultiedDistance <> 0 Then FrmMain.BtnExtraApril.Ribble()
  979. '以未知原因窗口被丢到一边去的修复(Top、Left = -25600),还有 #745
  980. RunInUi(
  981. Sub()
  982. If Not FrmMain.Hidden Then
  983. If FrmMain.Top < -9000 Then FrmMain.Top = 100
  984. If FrmMain.Left < -9000 Then FrmMain.Left = 100 '窗口拉至最大时 Left = -18.8
  985. End If
  986. End Sub)
  987. #End Region
  988. Catch ex As Exception
  989. Logger.Error(ex, "长程主时钟执行异常", LogBehavior.AlertThenCrash)
  990. End Try
  991. End If
  992. End Sub
  993. Public Sub TimerMainStart()
  994. RunInNewThread(
  995. Sub()
  996. Try
  997. Do While True
  998. RunInUiWait(AddressOf TimerMain)
  999. Thread.Sleep(50 * 0.98)
  1000. Loop
  1001. Catch ex As Exception
  1002. Logger.Error(ex, "程序主时钟出错")
  1003. End Try
  1004. End Sub, "Timer Main")
  1005. If Not IsAprilEnabled Then Return
  1006. RunInNewThread(
  1007. Sub()
  1008. Try
  1009. Dim LastTime = My.Computer.Clock.TickCount
  1010. Do While True
  1011. If LastTime <> My.Computer.Clock.TickCount Then
  1012. LastTime = My.Computer.Clock.TickCount
  1013. RunInUiWait(AddressOf TimerFool)
  1014. End If
  1015. Thread.Sleep(1)
  1016. Loop
  1017. Catch ex As Exception
  1018. Logger.Error(ex, "愚人节主时钟出错")
  1019. End Try
  1020. End Sub, "Timer Main Fool")
  1021. End Sub
  1022. End Module