Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e831d0dfe0 | ||
|
|
5d549ff66a |
No files matched your search
@@ -0,0 +1,87 @@
|
||||
name: Release PCL-ISE
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Register a Windows host runner with the label windows:host.
|
||||
runs-on: ${{ vars.PCL_WINDOWS_RUNNER_LABEL || 'windows' }}
|
||||
permissions:
|
||||
contents: read
|
||||
releases: write
|
||||
env:
|
||||
PCL_BUILD_CONFIGURATION: ${{ vars.PCL_BUILD_CONFIGURATION || 'Snapshot' }}
|
||||
defaults:
|
||||
run:
|
||||
shell: pwsh
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: https://github.com/actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup .NET SDK
|
||||
uses: https://github.com/actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '9.0.x'
|
||||
|
||||
- name: Prepare build configuration
|
||||
env:
|
||||
PCL_MS_CLIENT_ID: ${{ vars.PCL_MS_CLIENT_ID || '4609f0a4-9d6f-40f0-918e-6d3a00413903' }}
|
||||
PCL_CURSEFORGE_API_KEY: ${{ secrets.PCL_CURSEFORGE_API_KEY }}
|
||||
run: ./scripts/Write-BuildCredentials.ps1 -RequireMicrosoftClientId
|
||||
|
||||
- name: Restore NuGet packages
|
||||
run: |
|
||||
dotnet restore PCLCS/PCLCS.csproj
|
||||
if ($LASTEXITCODE -ne 0) { throw 'NuGet restore failed.' }
|
||||
|
||||
- name: Build launcher
|
||||
run: |
|
||||
& ./.vscode/build.ps1 -Configuration $env:PCL_BUILD_CONFIGURATION
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Release build failed.' }
|
||||
|
||||
- name: Verify packaged configuration
|
||||
env:
|
||||
PCL_MS_CLIENT_ID: ${{ vars.PCL_MS_CLIENT_ID || '4609f0a4-9d6f-40f0-918e-6d3a00413903' }}
|
||||
PCL_CURSEFORGE_API_KEY: ${{ secrets.PCL_CURSEFORGE_API_KEY }}
|
||||
run: |
|
||||
$checker = Join-Path $env:RUNNER_TEMP 'Check-BuildCredentials.exe'
|
||||
$compiler = Join-Path $env:WINDIR 'Microsoft.NET\Framework\v4.0.30319\csc.exe'
|
||||
$source = Join-Path (Get-Location) 'tests\Check-BuildCredentials.cs'
|
||||
& $compiler /nologo /target:exe "/out:$checker" $source
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Configuration checker compilation failed.' }
|
||||
& $checker 'Plain Craft Launcher 2/bin/Plain Craft Launcher 2.exe' packaged
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Packaged configuration verification failed.' }
|
||||
|
||||
- name: Verify update replacement
|
||||
run: ./tests/Test-LauncherUpdate.ps1 -LauncherPath 'Plain Craft Launcher 2/bin/Plain Craft Launcher 2.exe'
|
||||
|
||||
- name: Prepare release assets
|
||||
run: |
|
||||
$artifactDirectory = Join-Path (Get-Location) 'artifacts/release'
|
||||
[IO.Directory]::CreateDirectory($artifactDirectory) | Out-Null
|
||||
$exePath = Join-Path $artifactDirectory 'PCL-ISE.exe'
|
||||
Copy-Item -LiteralPath 'Plain Craft Launcher 2/bin/Plain Craft Launcher 2.exe' -Destination $exePath -Force
|
||||
$hash = (Get-FileHash -LiteralPath $exePath -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
[IO.File]::WriteAllText(($exePath + '.sha256'), "$hash PCL-ISE.exe`n", [Text.UTF8Encoding]::new($false))
|
||||
|
||||
- name: Publish release
|
||||
env:
|
||||
PCL_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITEA_TOKEN }}
|
||||
PCL_GITEA_SERVER_URL: ${{ gitea.server_url }}
|
||||
PCL_GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
PCL_RELEASE_TAG: ${{ gitea.ref_name }}
|
||||
run: |
|
||||
./scripts/Publish-GiteaRelease.ps1 -ServerUrl $env:PCL_GITEA_SERVER_URL -Repository $env:PCL_GITEA_REPOSITORY -Tag $env:PCL_RELEASE_TAG
|
||||
|
||||
- name: Clean generated configuration
|
||||
if: ${{ always() }}
|
||||
run: |
|
||||
$path = 'Plain Craft Launcher 2/obj/BuildCredentials.json'
|
||||
if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force }
|
||||
@@ -4,10 +4,12 @@ on:
|
||||
paths:
|
||||
- 'Plain Craft Launcher 2/**'
|
||||
- '.github/workflows/**'
|
||||
- 'scripts/**'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'Plain Craft Launcher 2/**'
|
||||
- '.github/workflows/**'
|
||||
- 'scripts/**'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -50,10 +52,15 @@ jobs:
|
||||
Set-Location ${{ GITHUB.WORKSPACE }}
|
||||
|
||||
|
||||
- name: Replace
|
||||
- name: Prepare build configuration
|
||||
shell: pwsh
|
||||
env:
|
||||
PCL_MS_CLIENT_ID: ${{ vars.PCL_MS_CLIENT_ID || secrets.CLIENT_ID }}
|
||||
PCL_CURSEFORGE_API_KEY: ${{ secrets.PCL_CURSEFORGE_API_KEY || secrets.CURSEFORGE_API_KEY }}
|
||||
run: ./scripts/Write-BuildCredentials.ps1
|
||||
|
||||
- name: Set commit hash
|
||||
run: |
|
||||
(gc "Plain Craft Launcher 2\Modules\ModSecret.vb") -replace 'Public OAuthClientId As String = If(Environment.GetEnvironmentVariable("PCL_MS_CLIENT_ID"), "")', 'Public OAuthClientId As String = If(Environment.GetEnvironmentVariable("PCL_MS_CLIENT_ID"), "${{ secrets.CLIENT_ID }}")' | Out-File "Plain Craft Launcher 2\Modules\ModSecret.vb"
|
||||
(gc "Plain Craft Launcher 2\Modules\ModSecret.vb") -replace 'Public CurseForgeAPIKey As String = If(Environment.GetEnvironmentVariable("PCL_CURSEFORGE_API_KEY"), "")', 'Public CurseForgeAPIKey As String = If(Environment.GetEnvironmentVariable("PCL_CURSEFORGE_API_KEY"), "${{ secrets.CURSEFORGE_API_KEY }}")' | Out-File "Plain Craft Launcher 2\Modules\ModSecret.vb"
|
||||
(gc "Plain Craft Launcher 2\Modules\Base\ModBase.vb") -replace 'Public Const CommitHash As String = ""', 'Public Const CommitHash As String = "${{ github.sha }}"' | Out-File "Plain Craft Launcher 2\Modules\Base\ModBase.vb"
|
||||
|
||||
- name: Restore NuGet Packages
|
||||
@@ -67,3 +74,10 @@ jobs:
|
||||
with:
|
||||
name: ${{ matrix.configuration }} ${{ env.describe }}
|
||||
path: Plain Craft Launcher 2\obj\${{ matrix.configuration }}\Plain Craft Launcher 2.exe
|
||||
|
||||
- name: Clean generated configuration
|
||||
if: ${{ always() }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$path = 'Plain Craft Launcher 2/obj/BuildCredentials.json'
|
||||
if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force }
|
||||
@@ -13,6 +13,17 @@ Public Class Application
|
||||
WaitingMutex(e)
|
||||
Logger.Instance = New PclLogger With {.logFolder = Paths.BaseThenName, .MinLevel = If(ModeDebug, LogLevel.Trace, LogLevel.Info)}
|
||||
End If
|
||||
'更新助手在界面、字体和开发测试初始化前执行,保持旧版的五参数调用兼容。
|
||||
If e.Args.Length > 0 AndAlso e.Args(0) = "--update" Then
|
||||
Dim PreviousProcessId As Integer
|
||||
Dim RestartAfterUpdate As Boolean
|
||||
If e.Args.Length <> 5 OrElse Not Integer.TryParse(e.Args(1), PreviousProcessId) OrElse Not Boolean.TryParse(e.Args(4), RestartAfterUpdate) Then
|
||||
Environment.Exit(ProcessReturnValues.Fail)
|
||||
Return
|
||||
End If
|
||||
Environment.Exit(If(UpdateReplace(PreviousProcessId, e.Args(2), e.Args(3), RestartAfterUpdate), ProcessReturnValues.TaskDone, ProcessReturnValues.Fail))
|
||||
Return
|
||||
End If
|
||||
'提升主线程优先级
|
||||
Thread.CurrentThread.Priority = ThreadPriority.Highest
|
||||
'执行开发版测试
|
||||
@@ -38,16 +49,7 @@ Public Class Application
|
||||
End Try
|
||||
'检查参数调用
|
||||
If e.Args.Length > 0 Then
|
||||
If e.Args(0) = "--update" Then
|
||||
'自动更新
|
||||
Dim PreviousProcessId As Integer
|
||||
Dim RestartAfterUpdate As Boolean
|
||||
If e.Args.Length <> 5 OrElse Not Integer.TryParse(e.Args(1), PreviousProcessId) OrElse Not Boolean.TryParse(e.Args(4), RestartAfterUpdate) Then
|
||||
Environment.Exit(ProcessReturnValues.Fail)
|
||||
Return
|
||||
End If
|
||||
Environment.Exit(If(UpdateReplace(PreviousProcessId, e.Args(2), e.Args(3), RestartAfterUpdate), ProcessReturnValues.TaskDone, ProcessReturnValues.Fail))
|
||||
ElseIf e.Args(0) = "--gpu" Then
|
||||
If e.Args(0) = "--gpu" Then
|
||||
'调整显卡设置
|
||||
Try
|
||||
SetGPUPreference(e.Args(1).Trim(""""))
|
||||
|
||||
@@ -439,17 +439,17 @@ Public Class FormMain
|
||||
Catch ex As Exception
|
||||
Logger.Error(ex, "初始化加载池运行失败")
|
||||
End Try
|
||||
'清理自动更新文件
|
||||
Try
|
||||
FileUtils.Delete(Paths.Base & "PCL\Plain Craft Launcher 2.exe")
|
||||
Catch ex As Exception
|
||||
Logger.Warn(ex, "清理自动更新文件失败")
|
||||
End Try
|
||||
'反馈上次更新结果,并在更新助手退出后清理受管理的下载文件。
|
||||
ShowLauncherUpdateResult()
|
||||
'上报
|
||||
Telemetry("启动")
|
||||
'开源版本提示
|
||||
If VersionBranchMain = "OpenSource" Then
|
||||
MyMsgBox($"PCL-ISE 是 InfstarMC 基于 PCL 开发的第三方修改版。{vbCrLf}可在设置中检查 InfstarMC 仓库发布的启动器更新。{vbCrLf}{vbCrLf}当前仍需单独配置:{vbCrLf}- 正版登录:申请并设置环境变量 PCL_MS_CLIENT_ID。{vbCrLf}- CurseForge:申请并设置环境变量 PCL_CURSEFORGE_API_KEY。{vbCrLf}设置后请重新启动启动器。", "PCL-ISE 开发版说明")
|
||||
Dim MissingConfig As New List(Of String)
|
||||
If String.IsNullOrWhiteSpace(OAuthClientId) Then MissingConfig.Add("- 正版登录:申请并设置环境变量 PCL_MS_CLIENT_ID。")
|
||||
If String.IsNullOrWhiteSpace(CurseForgeAPIKey) Then MissingConfig.Add("- CurseForge:申请并设置环境变量 PCL_CURSEFORGE_API_KEY。")
|
||||
Dim ConfigHint As String = If(MissingConfig.Any(), vbCrLf & vbCrLf & "当前仍需单独配置:" & vbCrLf & String.Join(vbCrLf, MissingConfig) & vbCrLf & "设置后请重新启动启动器。", "")
|
||||
MyMsgBox($"PCL-ISE 是 InfstarMC 基于 PCL 开发的第三方修改版。{vbCrLf}可在设置中检查 InfstarMC 仓库发布的启动器更新。{ConfigHint}", "PCL-ISE 开发版说明")
|
||||
End If
|
||||
End Sub, "初始化", ThreadPriority.Lowest)
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Public Module ModBase
|
||||
'PCL-ISE 版本规则:主版本.次版本.修订版本;内部 VersionCode 继续用于更新兼容判断。
|
||||
Public Const ProductName As String = "Plain Craft Launcher (PCL) InfstarMC Edition"
|
||||
Public Const ProductShortName As String = "PCL-ISE"
|
||||
Public Const VersionBaseName As String = "0.1.1" '显示用版本名
|
||||
Public Const VersionBaseName As String = "0.1.2" '显示用版本名
|
||||
Public Const CommitHash As String = "" 'Commit Hash,由 GitHub Workflow 自动替换
|
||||
#If RELEASE Then
|
||||
Public Const VersionCode As Integer = 413 '正式版
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
Imports System
|
||||
Imports System.Diagnostics
|
||||
Imports System.IO
|
||||
Imports System.Security.Cryptography
|
||||
Imports System.Threading
|
||||
|
||||
'只依赖 .NET,供启动器与独立的更新功能测试共同使用。
|
||||
Public Module ModLauncherUpdate
|
||||
@@ -18,9 +20,12 @@ Public Module ModLauncherUpdate
|
||||
Return New Version(Numbers(0), Numbers(1), Numbers(2), 0)
|
||||
End Function
|
||||
|
||||
Public Sub ReplaceLauncherFile(ProcessId As Integer, OldFileName As String, NewFileName As String, Optional WaitTimeout As Integer = 30000)
|
||||
Public Sub ReplaceLauncherFile(ProcessId As Integer, OldFileName As String, NewFileName As String, Optional WaitTimeout As Integer = 30000,
|
||||
Optional Operations As LauncherUpdateFileOperations = Nothing)
|
||||
Dim Target = Path.GetFullPath(OldFileName)
|
||||
Dim Source = Path.GetFullPath(NewFileName)
|
||||
If Operations Is Nothing Then Operations = New LauncherUpdateFileOperations()
|
||||
If WaitTimeout < 0 Then Throw New ArgumentOutOfRangeException("WaitTimeout")
|
||||
If String.Equals(Target, Source, StringComparison.OrdinalIgnoreCase) Then Throw New IOException("更新文件与目标文件不能相同")
|
||||
If Not File.Exists(Source) Then Throw New FileNotFoundException("找不到已下载的更新文件", Source)
|
||||
If ProcessId > 0 Then
|
||||
@@ -37,17 +42,98 @@ Public Module ModLauncherUpdate
|
||||
End Using
|
||||
End If
|
||||
End If
|
||||
'在目标目录暂存副本,再进行原子替换;失败时保留旧程序和下载文件。
|
||||
'先验证下载副本和旧文件备份,再删除并复制;任何复制或校验失败都尝试恢复旧文件。
|
||||
Dim Staged = Target & "." & Guid.NewGuid().ToString("N") & ".new"
|
||||
Dim Backup = Target & ".bak"
|
||||
Dim OriginalHash As String = Nothing
|
||||
Dim BackupReady = False
|
||||
Dim ReplacementStarted = False
|
||||
Try
|
||||
File.Copy(Source, Staged)
|
||||
Dim NewHash = GetLauncherFileHash(Source)
|
||||
RetryLauncherFileOperation(Sub() Operations.CopyFile(Source, Staged, True), Operations)
|
||||
If GetLauncherFileHash(Staged) <> NewHash Then Throw New IOException("更新暂存文件的 SHA256 校验失败")
|
||||
If File.Exists(Target) Then
|
||||
File.Replace(Staged, Target, Target & ".bak", True)
|
||||
Else
|
||||
File.Move(Staged, Target)
|
||||
OriginalHash = GetLauncherFileHash(Target)
|
||||
RetryLauncherFileOperation(Sub() Operations.CopyFile(Target, Backup, True), Operations)
|
||||
If GetLauncherFileHash(Backup) <> OriginalHash Then Throw New IOException("旧版本备份的 SHA256 校验失败,已停止更新")
|
||||
BackupReady = True
|
||||
End If
|
||||
|
||||
ReplacementStarted = True
|
||||
RetryLauncherFileOperation(Sub() Operations.DeleteFile(Target), Operations)
|
||||
RetryLauncherFileOperation(Sub() Operations.CopyFile(Staged, Target, True), Operations)
|
||||
If GetLauncherFileHash(Target) <> NewHash Then Throw New IOException("替换后的启动器 SHA256 校验失败")
|
||||
Catch UpdateError As Exception
|
||||
If Not ReplacementStarted Then Throw
|
||||
Try
|
||||
If BackupReady Then
|
||||
RetryLauncherFileOperation(Sub() Operations.CopyFile(Backup, Target, True), Operations)
|
||||
If GetLauncherFileHash(Target) <> OriginalHash Then Throw New IOException("恢复后的旧程序 SHA256 校验失败")
|
||||
Else
|
||||
'首次写入失败时,移除不完整的目标文件。
|
||||
RetryLauncherFileOperation(Sub() Operations.DeleteFile(Target), Operations)
|
||||
End If
|
||||
Catch RestoreError As Exception
|
||||
Throw New AggregateException("更新失败,自动恢复也未完成。请保留下载文件,并从备份手动恢复:" & Backup,
|
||||
New Exception() {UpdateError, RestoreError})
|
||||
End Try
|
||||
Throw New IOException(If(BackupReady, "更新失败,旧程序已恢复:", "更新失败,未保留不完整的程序:") & UpdateError.Message, UpdateError)
|
||||
Finally
|
||||
If File.Exists(Staged) Then File.Delete(Staged)
|
||||
Try
|
||||
If File.Exists(Staged) Then Operations.DeleteFile(Staged)
|
||||
Catch CleanupError As Exception
|
||||
'暂存文件清理失败不能掩盖替换或恢复的真实结果。
|
||||
Trace.TraceWarning("清理更新暂存文件失败:" & CleanupError.Message)
|
||||
End Try
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
Private Sub RetryLauncherFileOperation(Operation As Action, Operations As LauncherUpdateFileOperations)
|
||||
Dim Timer = Stopwatch.StartNew()
|
||||
Do
|
||||
Try
|
||||
Operation()
|
||||
Return
|
||||
Catch ex As Exception When TypeOf ex Is IOException OrElse TypeOf ex Is UnauthorizedAccessException
|
||||
If Timer.ElapsedMilliseconds >= Operations.RetryTimeoutMilliseconds Then Throw
|
||||
Thread.Sleep(100)
|
||||
End Try
|
||||
Loop
|
||||
End Sub
|
||||
|
||||
Private Function GetLauncherFileHash(FileName As String) As String
|
||||
Using Algorithm = SHA256.Create()
|
||||
Using Stream = File.OpenRead(FileName)
|
||||
Return BitConverter.ToString(Algorithm.ComputeHash(Stream))
|
||||
End Using
|
||||
End Using
|
||||
End Function
|
||||
|
||||
Public Function GetLauncherUpdateResultPath(TargetPath As String) As String
|
||||
Return Path.Combine(Path.GetDirectoryName(Path.GetFullPath(TargetPath)), "PCL", "UpdateResult-" & Path.GetFileName(TargetPath) & ".json")
|
||||
End Function
|
||||
End Module
|
||||
|
||||
'文件操作单独封装,使恢复流程可以在隔离目录内模拟真实的 I/O 失败。
|
||||
Public Class LauncherUpdateFileOperations
|
||||
Public Property RetryTimeoutMilliseconds As Integer = 5000
|
||||
|
||||
Public Overridable Sub CopyFile(Source As String, Target As String, Overwrite As Boolean)
|
||||
File.Copy(Source, Target, Overwrite)
|
||||
End Sub
|
||||
|
||||
Public Overridable Sub DeleteFile(Target As String)
|
||||
File.Delete(Target)
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Public Class LauncherUpdateResult
|
||||
Public Property Succeeded As Boolean
|
||||
Public Property TargetPath As String
|
||||
Public Property DownloadPath As String
|
||||
Public Property BackupPath As String
|
||||
Public Property VersionName As String
|
||||
Public Property ErrorMessage As String
|
||||
Public Property HelperProcessId As Integer
|
||||
Public Property CompletedUtc As Date
|
||||
End Class
|
||||
@@ -9,13 +9,28 @@ Friend Module ModSecret
|
||||
Public Const VersionBranchMain As String = "OpenSource"
|
||||
'在开源版的注册表与常规版的注册表隔离,以防数据冲突
|
||||
Public Const RegFolder As String = "PCLDebug"
|
||||
'用于微软登录的 ClientId
|
||||
Public OAuthClientId As String = If(Environment.GetEnvironmentVariable("PCL_MS_CLIENT_ID"), "")
|
||||
'CurseForge API Key
|
||||
Public CurseForgeAPIKey As String = If(Environment.GetEnvironmentVariable("PCL_CURSEFORGE_API_KEY"), "")
|
||||
'发布构建可内嵌配置,运行时环境变量优先。
|
||||
Private ReadOnly BuildCredentials As JObject = LoadBuildCredentials()
|
||||
Public OAuthClientId As String = GetBuildCredential("PCL_MS_CLIENT_ID")
|
||||
Public CurseForgeAPIKey As String = GetBuildCredential("PCL_CURSEFORGE_API_KEY")
|
||||
'用于匿名数据收集的腾讯云日志服务上报 URL,形如 https://{region}.cls.tencentcs.com/track?topic_id={topic_id}
|
||||
Public Const ClsBaseUrl As String = ""
|
||||
|
||||
Private Function LoadBuildCredentials() As JObject
|
||||
Using Stream = GetType(ModSecret).Assembly.GetManifestResourceStream("PCL.BuildCredentials.json")
|
||||
If Stream Is Nothing Then Return New JObject()
|
||||
Using Reader As New StreamReader(Stream)
|
||||
Return JObject.Parse(Reader.ReadToEnd())
|
||||
End Using
|
||||
End Using
|
||||
End Function
|
||||
|
||||
Private Function GetBuildCredential(Name As String) As String
|
||||
Dim OverrideValue As String = Environment.GetEnvironmentVariable(Name)
|
||||
If Not String.IsNullOrWhiteSpace(OverrideValue) Then Return OverrideValue
|
||||
Return If(BuildCredentials(Name)?.ToString(), "")
|
||||
End Function
|
||||
|
||||
#Region "网络鉴权"
|
||||
|
||||
'PCL-ISE 提供 Mojang 官方版本清单以及现有的 Minecraft 下载链路。
|
||||
@@ -65,15 +80,15 @@ Friend Module ModSecret
|
||||
Public ColorGray8 As New MyColor(245, 245, 245)
|
||||
Public ColorSemiTransparent As New MyColor(1, Color8)
|
||||
|
||||
Public ThemeNow As Integer = -1
|
||||
Public ColorHue As Integer = 210, ColorSat As Integer = 85, ColorLightAdjust As Integer = 0, ColorHueTopbarDelta As OneOf(Of Integer, Integer()) = 0
|
||||
Public ThemeDontClick As Integer = 0
|
||||
'PCL-ISE 仅提供龙猫蓝;旧主题编号和自定义调色均不参与渲染。
|
||||
Public Const ThemeNow As Integer = 0
|
||||
Public Const ColorHue As Integer = 210, ColorSat As Integer = 85, ColorLightAdjust As Integer = 0
|
||||
Public ReadOnly ColorHueTopbarDelta As OneOf(Of Integer, Integer()) = 0
|
||||
Public Const ThemeDontClick As Integer = 0
|
||||
|
||||
Public Sub ThemeRefresh(Optional NewTheme As Integer = -1)
|
||||
Try
|
||||
If ThemeNow = NewTheme AndAlso NewTheme >= 0 Then Return
|
||||
If NewTheme >= 0 Then ThemeNow = NewTheme
|
||||
|
||||
'保留旧调用签名以兼容设置回调,始终使用固定的龙猫蓝配色。
|
||||
Color1 = New MyColor().FromHSL2(ColorHue, ColorSat * 0.2, 25 + ColorLightAdjust * 0.3)
|
||||
Color2 = New MyColor().FromHSL2(ColorHue, ColorSat, 45 + ColorLightAdjust)
|
||||
Color3 = New MyColor().FromHSL2(ColorHue, ColorSat, 55 + ColorLightAdjust)
|
||||
@@ -114,7 +129,7 @@ Friend Module ModSecret
|
||||
Public Sub ThemeRefreshMain()
|
||||
RunInUi(
|
||||
Sub()
|
||||
If Not FrmMain.IsLoaded Then Return
|
||||
If FrmMain Is Nothing OrElse Not FrmMain.IsLoaded Then Return
|
||||
'顶部条背景
|
||||
Dim Brush = New LinearGradientBrush With {.EndPoint = New Point(1, 0), .StartPoint = New Point(0, 0)}
|
||||
Dim Deltas = ColorHueTopbarDelta.Switch(Function(d) New Integer() {-d, 0, d}, Function(d) d)
|
||||
@@ -137,9 +152,13 @@ Friend Module ModSecret
|
||||
End Sub)
|
||||
End Sub
|
||||
Friend Sub ThemeCheckAll(EffectSetup As Boolean)
|
||||
'仅重置旧主题选择和调色配置,不影响背景、透明度、音乐等个性化设置。
|
||||
For Each Key In {"UiLauncherTheme", "UiLauncherHue", "UiLauncherSat", "UiLauncherDelta", "UiLauncherLight"}
|
||||
Settings.Reset(Key)
|
||||
Next
|
||||
End Sub
|
||||
Friend Function ThemeCheckOne(Id As Integer) As Boolean
|
||||
Return True
|
||||
Return Id = 0
|
||||
End Function
|
||||
Friend Function ThemeUnlock(Id As Integer, Optional ShowDoubleHint As Boolean = True, Optional UnlockHint As String = Nothing) As Boolean
|
||||
Return False
|
||||
@@ -151,8 +170,10 @@ Friend Module ModSecret
|
||||
|
||||
'更新源使用 InfstarMC 自己的 Gitea Release API,不会从上游 PCL 下载启动器。
|
||||
Public Const UpdateApiUrl As String = "https://git.infstar.cn/api/v1/repos/InfStarMC/PCL-ISE/releases/latest"
|
||||
Private Const UpdateReleasesApiUrl As String = "https://git.infstar.cn/api/v1/repos/InfStarMC/PCL-ISE/releases"
|
||||
Public Const UpdateRepositoryUrl As String = "https://git.infstar.cn/InfStarMC/PCL-ISE/releases"
|
||||
Private Const UpdateCacheFile As String = "Cache\PclIseUpdate.json"
|
||||
Private Const SnapshotUpdateCacheFile As String = "Cache\PclIseSnapshotUpdate.json"
|
||||
Private Const UpdateAssetFileName As String = "PCL-ISE.exe"
|
||||
Private Const UpdateAssetMinSize As Long = 64 * 1024
|
||||
|
||||
@@ -169,10 +190,49 @@ Friend Module ModSecret
|
||||
|
||||
Private UpdateFilePath As String = Nothing
|
||||
Private UpdateCheckRunning As Integer = 0
|
||||
Private UpdateRestartRunning As Integer = 0
|
||||
Friend IsUpdateWaitingRestart As Boolean = False
|
||||
|
||||
Private Function GetLatestLauncherUpdate() As LauncherUpdateInfo
|
||||
Dim Json As JObject = NetRequestByClientRetry(UpdateApiUrl, RequireJson:=True).DeserializeJson()
|
||||
Return ParseLauncherUpdate(Json, Snapshot:=False)
|
||||
End Function
|
||||
|
||||
Private Function GetLatestSnapshotLauncherUpdate() As LauncherUpdateInfo
|
||||
Dim Json = GetLatestSnapshotRelease()
|
||||
If Json Is Nothing Then Return Nothing
|
||||
Return ParseLauncherUpdate(Json, Snapshot:=True)
|
||||
End Function
|
||||
|
||||
'按三位版本号选择最新的公开快照发布,不依赖 Gitea 返回的创建时间顺序。
|
||||
'分页请求可替换为隔离的测试数据,实际调用始终访问 InfstarMC Release API。
|
||||
Private Function GetLatestSnapshotRelease(Optional FetchPage As Func(Of Integer, String) = Nothing) As JObject
|
||||
If FetchPage Is Nothing Then
|
||||
FetchPage = Function(PageNumber) NetRequestByClientRetry(UpdateReleasesApiUrl & "?limit=50&page=" & PageNumber, RequireJson:=True).ToString()
|
||||
End If
|
||||
Dim Latest As JObject = Nothing
|
||||
Dim LatestVersion As Version = Nothing
|
||||
For PageNumber As Integer = 1 To 100
|
||||
Dim Releases = JArray.Parse(FetchPage(PageNumber))
|
||||
'即使服务器限制每页条数,也继续读取到空页,避免遗漏较早发布的高版本。
|
||||
If Releases.Count = 0 Then Return Latest
|
||||
For Each Candidate As JObject In Releases.OfType(Of JObject)()
|
||||
If Candidate.Value(Of Boolean)("draft") OrElse Not Candidate.Value(Of Boolean)("prerelease") Then Continue For
|
||||
Dim CandidateVersion = ParseLauncherVersion(If(Candidate("tag_name"), "").ToString())
|
||||
If CandidateVersion Is Nothing Then Continue For
|
||||
If LatestVersion Is Nothing OrElse CandidateVersion > LatestVersion Then
|
||||
Latest = Candidate
|
||||
LatestVersion = CandidateVersion
|
||||
End If
|
||||
Next
|
||||
Next
|
||||
Throw New IOException("发布列表过长,未能完成快照版本检查,请前往发布页查看。")
|
||||
End Function
|
||||
|
||||
Private Function ParseLauncherUpdate(Json As JObject, Snapshot As Boolean) As LauncherUpdateInfo
|
||||
If Json.Value(Of Boolean)("draft") OrElse Json.Value(Of Boolean)("prerelease") <> Snapshot Then
|
||||
Throw New FormatException("PCL-ISE 发布类型与本次检查不符")
|
||||
End If
|
||||
Dim TagName = If(Json("tag_name"), "").ToString
|
||||
Dim VersionNumber = ParseLauncherVersion(TagName)
|
||||
If VersionNumber Is Nothing Then Throw New FormatException("PCL-ISE 发布信息中的版本号无效")
|
||||
@@ -215,7 +275,7 @@ Friend Module ModSecret
|
||||
.VersionNumber = VersionNumber
|
||||
}
|
||||
DirectoryUtils.Create(PathTemp & "Cache\")
|
||||
FileUtils.Write(PathTemp & UpdateCacheFile, Json.ToString)
|
||||
FileUtils.Write(PathTemp & If(Snapshot, SnapshotUpdateCacheFile, UpdateCacheFile), Json.ToString)
|
||||
Return Info
|
||||
End Function
|
||||
|
||||
@@ -237,7 +297,7 @@ Friend Module ModSecret
|
||||
End Try
|
||||
End Function
|
||||
|
||||
Friend Sub UpdateCheckByButton()
|
||||
Friend Sub UpdateCheckByButton(Optional CheckSnapshot As Boolean = False)
|
||||
If Interlocked.Exchange(UpdateCheckRunning, 1) <> 0 Then
|
||||
Hint("正在检查更新,请稍候……")
|
||||
Return
|
||||
@@ -245,28 +305,35 @@ Friend Module ModSecret
|
||||
RunInNewThread(
|
||||
Sub()
|
||||
Try
|
||||
RunInUi(Sub() Hint("正在检查 PCL-ISE 更新……", Log:=False))
|
||||
Dim Info = GetLatestLauncherUpdate()
|
||||
Dim ChannelName = If(CheckSnapshot, "快照版", "正式版")
|
||||
RunInUi(Sub() Hint("正在检查 PCL-ISE " & ChannelName & "更新……", Log:=False))
|
||||
Dim Info = If(CheckSnapshot, GetLatestSnapshotLauncherUpdate(), GetLatestLauncherUpdate())
|
||||
If Info Is Nothing Then
|
||||
RunInUi(Sub() Hint("目前没有可用的 PCL-ISE " & ChannelName & "发布。"))
|
||||
Return
|
||||
End If
|
||||
If Not IsUpdateNewer(Info) Then
|
||||
RunInUi(Sub() Hint("当前已经是最新版本!", HintType.Green))
|
||||
RunInUi(Sub() Hint("当前版本不低于最新" & ChannelName & ",无需更新。", HintType.Green))
|
||||
Return
|
||||
End If
|
||||
|
||||
Dim Summary = If(String.IsNullOrWhiteSpace(Info.ReleaseBody), "该版本没有提供更新说明。", Info.ReleaseBody)
|
||||
If Summary.Length > 1200 Then Summary = Summary.Substring(0, 1200) & "……"
|
||||
Dim Confirm = RunInUiWait(Function() MyMsgBox($"发现 PCL-ISE {Info.TagName}。" & vbCrLf & vbCrLf & Summary,
|
||||
Dim SnapshotNotice = If(CheckSnapshot, "这是开发测试版本,可能包含尚未稳定的功能。" & vbCrLf & vbCrLf, "")
|
||||
Dim Confirm = RunInUiWait(Function() MyMsgBox($"发现 PCL-ISE {ChannelName} {Info.TagName}。" & vbCrLf & vbCrLf & SnapshotNotice & Summary,
|
||||
"发现新版本", "下载并更新", "查看发布页", "取消",
|
||||
Button2Action:=Sub() OpenWebsite(UpdateRepositoryUrl)))
|
||||
If Confirm = 2 Then Return
|
||||
If Confirm <> 1 Then Return
|
||||
|
||||
Dim SafeVersion = Info.VersionNumber.ToString(3)
|
||||
UpdateFilePath = PathTemp & "Update\PCL-ISE-" & SafeVersion & ".exe"
|
||||
Dim DownloadPath = PathTemp & "Update\PCL-ISE-" & SafeVersion & ".exe"
|
||||
Dim Checker As New FileChecker With {.MinSize = UpdateAssetMinSize, .ActualSize = Info.AssetSize, .Hash = If(String.IsNullOrWhiteSpace(Info.AssetHash), Nothing, Info.AssetHash)}
|
||||
RunInUi(Sub() Hint("正在下载更新……", Log:=False))
|
||||
NetDownloadByLoader(Info.DownloadUrl, UpdateFilePath, Check:=Checker)
|
||||
Dim DownloadedAssembly = Reflection.AssemblyName.GetAssemblyName(UpdateFilePath)
|
||||
NetDownloadByLoader(Info.DownloadUrl, DownloadPath, Check:=Checker)
|
||||
Dim DownloadedAssembly = Reflection.AssemblyName.GetAssemblyName(DownloadPath)
|
||||
If DownloadedAssembly.Name <> "Plain Craft Launcher 2" OrElse DownloadedAssembly.Version <> Info.VersionNumber Then Throw New FormatException("更新文件的程序集版本与发布版本不符")
|
||||
UpdateFilePath = DownloadPath
|
||||
IsUpdateWaitingRestart = True
|
||||
RunInUi(
|
||||
Sub()
|
||||
@@ -290,29 +357,110 @@ Friend Module ModSecret
|
||||
IsUpdateWaitingRestart = False
|
||||
Return
|
||||
End If
|
||||
If Interlocked.Exchange(UpdateRestartRunning, 1) <> 0 Then Return
|
||||
Try
|
||||
Dim Arguments = $"--update {Process.GetCurrentProcess.Id} ""{PathExe}"" ""{NewFile}"" {TriggerRestartAndByEnd.ToString.ToLowerInvariant()}"
|
||||
StartProcess(New ProcessStartInfo With {.FileName = NewFile, .Arguments = Arguments, .WorkingDirectory = Paths.Base, .UseShellExecute = True})
|
||||
StartProcess(New ProcessStartInfo With {.FileName = NewFile, .Arguments = Arguments, .WorkingDirectory = Paths.Base,
|
||||
.UseShellExecute = True, .WindowStyle = ProcessWindowStyle.Hidden})
|
||||
IsUpdateWaitingRestart = False
|
||||
If TriggerRestartAndByEnd Then FormMain.EndProgramForce()
|
||||
Catch ex As Exception
|
||||
Interlocked.Exchange(UpdateRestartRunning, 0)
|
||||
Logger.Error(ex, "启动更新替换进程失败", LogBehavior.Toast)
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
Public Function UpdateReplace(ProcessId As Integer, OldFileName As String, NewFileName As String, TriggerRestart As Boolean) As Boolean
|
||||
Dim Result As New LauncherUpdateResult With {
|
||||
.TargetPath = OldFileName, .DownloadPath = NewFileName, .VersionName = VersionBaseName,
|
||||
.HelperProcessId = Process.GetCurrentProcess().Id
|
||||
}
|
||||
Try
|
||||
ReplaceLauncherFile(ProcessId, OldFileName, NewFileName)
|
||||
Result.TargetPath = Path.GetFullPath(OldFileName)
|
||||
Result.DownloadPath = Path.GetFullPath(NewFileName)
|
||||
Result.BackupPath = Result.TargetPath & ".bak"
|
||||
ReplaceLauncherFile(ProcessId, Result.TargetPath, Result.DownloadPath)
|
||||
Result.Succeeded = True
|
||||
Logger.Info("PCL-ISE 更新文件替换完成")
|
||||
If TriggerRestart Then StartProcess(OldFileName)
|
||||
Return True
|
||||
Catch ex As Exception
|
||||
Result.ErrorMessage = ex.GetDisplay(False)
|
||||
Logger.Error(ex, "替换 PCL-ISE 更新文件失败")
|
||||
MsgBox("PCL-ISE 更新失败:" & ex.GetDisplay(False), MsgBoxStyle.Critical, "更新失败")
|
||||
Return False
|
||||
End Try
|
||||
Result.CompletedUtc = Date.UtcNow
|
||||
Try
|
||||
Dim ResultPath = GetLauncherUpdateResultPath(Result.TargetPath)
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(ResultPath))
|
||||
File.WriteAllText(ResultPath, Newtonsoft.Json.JsonConvert.SerializeObject(Result), System.Text.Encoding.UTF8)
|
||||
Catch ex As Exception
|
||||
Logger.Warn(ex, "保存 PCL-ISE 更新结果失败")
|
||||
End Try
|
||||
|
||||
If TriggerRestart Then
|
||||
If Result.Succeeded Then
|
||||
Try
|
||||
StartProcess(New ProcessStartInfo With {
|
||||
.FileName = Result.TargetPath, .Arguments = "--update-result",
|
||||
.WorkingDirectory = Path.GetDirectoryName(Result.TargetPath), .UseShellExecute = True
|
||||
})
|
||||
Catch ex As Exception
|
||||
Logger.Error(ex, "更新完成,但自动重启失败")
|
||||
MsgBox("文件已更新,请手动启动 PCL-ISE。" & vbCrLf & ex.GetDisplay(False), MsgBoxStyle.Exclamation, "自动重启失败")
|
||||
End Try
|
||||
Else
|
||||
MsgBox("PCL-ISE 更新失败:" & Result.ErrorMessage & vbCrLf & "可查看旧版备份(如有):" & Result.BackupPath,
|
||||
MsgBoxStyle.Critical, "更新失败")
|
||||
End If
|
||||
End If
|
||||
Return Result.Succeeded
|
||||
End Function
|
||||
|
||||
'在主窗口加载后的后台初始化线程调用,显示上一次更新结果。
|
||||
Friend Sub ShowLauncherUpdateResult()
|
||||
Try
|
||||
Dim ResultPath = GetLauncherUpdateResultPath(PathExe)
|
||||
If Not File.Exists(ResultPath) Then Return
|
||||
Dim Result = JObject.Parse(File.ReadAllText(ResultPath)).ToObject(Of LauncherUpdateResult)()
|
||||
If Result Is Nothing OrElse Not String.Equals(Path.GetFullPath(Result.TargetPath), Path.GetFullPath(PathExe), StringComparison.OrdinalIgnoreCase) Then Return
|
||||
If Result.Succeeded AndAlso Result.VersionName <> VersionBaseName Then Return
|
||||
If Result.HelperProcessId > 0 AndAlso Result.HelperProcessId <> Process.GetCurrentProcess().Id Then
|
||||
Dim Helper As Process = Nothing
|
||||
Try
|
||||
Helper = Process.GetProcessById(Result.HelperProcessId)
|
||||
Catch ex As ArgumentException
|
||||
'更新进程已退出。
|
||||
End Try
|
||||
If Helper IsNot Nothing Then
|
||||
Using Helper
|
||||
If Not Helper.WaitForExit(5000) Then Return
|
||||
End Using
|
||||
End If
|
||||
End If
|
||||
|
||||
If Result.Succeeded Then
|
||||
'只清理此启动器管理的当前版本下载文件,其他路径保持原样。
|
||||
Dim ManagedDownload = Path.GetFullPath(PathTemp & "Update\PCL-ISE-" & VersionBaseName & ".exe")
|
||||
If Not String.IsNullOrWhiteSpace(Result.DownloadPath) AndAlso
|
||||
String.Equals(Path.GetFullPath(Result.DownloadPath), ManagedDownload, StringComparison.OrdinalIgnoreCase) AndAlso
|
||||
Not String.Equals(ManagedDownload, Path.GetFullPath(PathExe), StringComparison.OrdinalIgnoreCase) Then
|
||||
Try
|
||||
File.Delete(ManagedDownload)
|
||||
Catch ex As Exception
|
||||
Logger.Warn(ex, "清理已安装的更新下载文件失败")
|
||||
End Try
|
||||
End If
|
||||
Logger.Info("PCL-ISE 已更新至 " & Result.VersionName & ",旧版本备份:" & Result.BackupPath)
|
||||
Dim BackupHint = If(File.Exists(Result.BackupPath), ",旧版本备份已保留", "")
|
||||
RunInUi(Sub() Hint("PCL-ISE 已更新至 " & VersionDisplay & BackupHint & "。", HintType.Green))
|
||||
Else
|
||||
Logger.Warn("上次 PCL-ISE 更新未完成:" & Result.ErrorMessage & ",备份位置:" & Result.BackupPath)
|
||||
RunInUi(Sub() Hint("上次更新未完成,请查看日志后重试或手动安装。", HintType.Red))
|
||||
End If
|
||||
File.Delete(ResultPath)
|
||||
Catch ex As Exception
|
||||
Logger.Warn(ex, "处理 PCL-ISE 更新结果失败")
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' 下载 InfstarMC 发布的启动器,用于整合包打包。
|
||||
''' 如果不是,则下载一个。
|
||||
|
||||
@@ -51,6 +51,6 @@ Imports System.Runtime.InteropServices
|
||||
' 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
|
||||
' 方法是按如下所示使用“*”
|
||||
|
||||
<Assembly: AssemblyVersion("0.1.1")>
|
||||
<Assembly: AssemblyFileVersion("0.1.1")>
|
||||
<Assembly: AssemblyVersion("0.1.2")>
|
||||
<Assembly: AssemblyFileVersion("0.1.2")>
|
||||
<Assembly: NeutralResourcesLanguage("")>
|
||||
@@ -529,12 +529,10 @@
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="Button" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="Button" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="Button" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<local:MyButton x:Name="BtnDonateOutput" Grid.Column="0" MinWidth="140" Text="生成土豆码" Padding="13,0" Margin="0,0,20,0" HorizontalAlignment="Left" ColorType="Highlight" Visibility="Collapsed" />
|
||||
<local:MyButton x:Name="BtnDonateDonate" Grid.Column="0" MinWidth="140" Text="赞助作者" Padding="13,0" Margin="0,0,20,0" HorizontalAlignment="Left" ColorType="Highlight" local:CustomEventService.EventType="打开网页" local:CustomEventService.EventData="https://meloong.com/afd/a/LTCat" />
|
||||
<local:MyButton x:Name="BtnDonateCopy" Grid.Column="1" MinWidth="140" Text="复制识别码" Padding="13,0" Margin="0,0,20,0" HorizontalAlignment="Left" />
|
||||
<local:MyButton x:Name="BtnDonateInput" Grid.Column="2" MinWidth="140" Text="输入土豆码" Padding="13,0" Margin="0,0,20,0" HorizontalAlignment="Left" />
|
||||
<local:MyButton x:Name="BtnAboutSnapshotUpdate" Grid.Column="1" MinWidth="140" Text="检查快照更新" Padding="13,0" Margin="0,0,20,0" HorizontalAlignment="Left"
|
||||
ToolTip="检查开发测试版本,可能包含尚未稳定的功能。" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</local:MyCard>
|
||||
|
||||
@@ -11,24 +11,13 @@ Public Class PageOtherAbout
|
||||
IsLoaded = True
|
||||
|
||||
ItemAboutPcl.Info = ItemAboutPcl.Info.Replace("%VERSION%", VersionDisplay).Replace("%VERSIONCODE%", VersionCode).Replace("%BRANCH%", CInt(BuildType))
|
||||
If BuildType = BuildTypes.Debug Then
|
||||
BtnDonateDonate.Visibility = Visibility.Collapsed
|
||||
BtnDonateOutput.Visibility = Visibility.Visible
|
||||
End If
|
||||
|
||||
End Sub
|
||||
|
||||
Public Shared Sub CopyIdentify() Handles BtnDonateCopy.Click
|
||||
ClipboardSet(Identify)
|
||||
End Sub
|
||||
Private Sub BtnDonateCodeInput_Click() Handles BtnDonateInput.Click
|
||||
InputPotatoCode(False)
|
||||
End Sub
|
||||
Private Sub BtnDonateOutput_Click(sender As Object, e As EventArgs) Handles BtnDonateOutput.Click
|
||||
GeneratePotatoCode()
|
||||
End Sub
|
||||
Private Sub BtnAboutUpdate_Click(sender As Object, e As MouseButtonEventArgs) Handles BtnAboutUpdate.Click
|
||||
UpdateCheckByButton()
|
||||
End Sub
|
||||
Private Sub BtnAboutSnapshotUpdate_Click(sender As Object, e As MouseButtonEventArgs) Handles BtnAboutSnapshotUpdate.Click
|
||||
UpdateCheckByButton(CheckSnapshot:=True)
|
||||
End Sub
|
||||
|
||||
End Class
|
||||
@@ -154,14 +154,9 @@
|
||||
<local:MyButton Grid.Column="1" x:Name="BtnSystemSettingExp" MinWidth="140" Text="导出设置" Padding="13,0" Margin="0,0,20,0" />
|
||||
<local:MyButton Grid.Column="2" x:Name="BtnSystemSettingImp" MinWidth="140" Text="导入设置" Padding="13,0" Margin="0,0,20,0" />
|
||||
</Grid>
|
||||
<Grid Height="35" Grid.Row="8" Grid.ColumnSpan="5" Margin="0,12,0,0" x:Name="PanDonate">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="Button" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="Button" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<local:MyButton Grid.Column="0" x:Name="BtnSystemIdentify" MinWidth="140" Text="复制识别码" Padding="13,0" Margin="0,0,20,0" />
|
||||
<local:MyButton Grid.Column="1" x:Name="BtnSystemUnlock" MinWidth="140" Text="输入土豆码" Padding="13,0" Margin="0,0,20,0" />
|
||||
</Grid>
|
||||
<local:MyButton Grid.Row="8" Grid.ColumnSpan="2" x:Name="BtnSystemSnapshotUpdate" MinWidth="140" Height="35"
|
||||
Text="检查快照更新" Padding="13,0" Margin="0,12,0,0" HorizontalAlignment="Left"
|
||||
ToolTip="检查开发测试版本,可能包含尚未稳定的功能。" />
|
||||
</Grid>
|
||||
</local:MyCard>
|
||||
|
||||
|
||||
@@ -6,13 +6,6 @@ Public Class PageSetupSystem
|
||||
'重复加载部分
|
||||
PanBack.ScrollToHome()
|
||||
|
||||
If BuildType = BuildTypes.Release Then
|
||||
PanDonate.Visibility = Visibility.Collapsed
|
||||
Else
|
||||
PanDonate.Visibility = Visibility.Visible
|
||||
ItemSystemUpdateDownload.Content = "在有新版本时自动下载(更新快照版前需要先输入土豆码)"
|
||||
End If
|
||||
|
||||
'非重复加载部分
|
||||
Static IsLoaded As Boolean = False
|
||||
If IsLoaded Then Return
|
||||
@@ -65,14 +58,6 @@ Public Class PageSetupSystem
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'识别码/土豆码替代入口
|
||||
Private Sub BtnSystemIdentify_Click(sender As Object, e As MouseButtonEventArgs) Handles BtnSystemIdentify.Click
|
||||
PageOtherAbout.CopyIdentify()
|
||||
End Sub
|
||||
Private Sub BtnSystemUnlock_Click(sender As Object, e As MouseButtonEventArgs) Handles BtnSystemUnlock.Click
|
||||
InputPotatoCode(False)
|
||||
End Sub
|
||||
|
||||
'调试模式
|
||||
Private Sub CheckDebugMode_Change() Handles CheckDebugMode.Change
|
||||
If AniControlEnabled = 0 Then Hint("部分调试信息将在刷新或启动器重启后切换显示!",, False)
|
||||
@@ -102,6 +87,9 @@ Public Class PageSetupSystem
|
||||
Private Sub BtnSystemUpdate_Click(sender As Object, e As EventArgs) Handles BtnSystemUpdate.Click
|
||||
UpdateCheckByButton()
|
||||
End Sub
|
||||
Private Sub BtnSystemSnapshotUpdate_Click(sender As Object, e As EventArgs) Handles BtnSystemSnapshotUpdate.Click
|
||||
UpdateCheckByButton(CheckSnapshot:=True)
|
||||
End Sub
|
||||
''' <summary>
|
||||
''' 启动器是否已经是最新版?
|
||||
''' 若返回 Nothing,则代表无更新缓存文件或出错。
|
||||
|
||||
@@ -9,96 +9,26 @@
|
||||
<local:MyCard Margin="0,15" Title="基础" x:Name="CardLauncher">
|
||||
<Grid Margin="25,40,25,17">
|
||||
<StackPanel>
|
||||
<Grid Margin="0,0,0,6">
|
||||
<Grid Height="22" Margin="0,0,0,10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="Name1" />
|
||||
<ColumnDefinition Width="1*" />
|
||||
<ColumnDefinition Width="30" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="1*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" Text="不透明度" Margin="0,0,20,0" />
|
||||
<local:MySlider local:SettingService.Key="UiLauncherTransparent"
|
||||
MaxValue="600" ValueByKey="10" Grid.ColumnSpan="5" x:Name="SliderLauncherTransparent" Grid.Column="1" />
|
||||
<TextBlock Grid.Row="1" VerticalAlignment="Center" Name="LabLauncherHue" Visibility="Collapsed" HorizontalAlignment="Left" Text="色调" Margin="0,10,20,0" />
|
||||
<local:MySlider local:SettingService.Key="UiLauncherHue"
|
||||
Grid.Row="1" Grid.Column="1" x:Name="SliderLauncherHue" Visibility="Collapsed" MaxValue="360" ValueByKey="10" Margin="0,10,0,0" />
|
||||
<TextBlock Grid.Row="2" VerticalAlignment="Center" Name="LabLauncherDelta" Visibility="Collapsed" HorizontalAlignment="Left" Text="色调渐变" Margin="0,10,20,0" />
|
||||
<local:MySlider local:SettingService.Key="UiLauncherDelta"
|
||||
Grid.Row="2" Grid.Column="1" x:Name="SliderLauncherDelta" Visibility="Collapsed" MaxValue="180" ValueByKey="5" Margin="0,10,0,0" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="3" VerticalAlignment="Center" Name="LabLauncherSat" Visibility="Collapsed" HorizontalAlignment="Left" Text="饱和度" Margin="0,10,20,0" />
|
||||
<local:MySlider local:SettingService.Key="UiLauncherSat"
|
||||
Grid.Row="1" Grid.Column="4" x:Name="SliderLauncherSat" Visibility="Collapsed" MaxValue="100" ValueByKey="5" Margin="0,10,0,0" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="3" VerticalAlignment="Center" Name="LabLauncherLight" Visibility="Collapsed" HorizontalAlignment="Left" Text="亮度" Margin="0,10,20,0" />
|
||||
<local:MySlider local:SettingService.Key="UiLauncherLight"
|
||||
Grid.Row="2" Grid.Column="4" x:Name="SliderLauncherLight" Visibility="Collapsed" MaxValue="40" ValueByKey="5" Margin="0,10,0,0" />
|
||||
MaxValue="600" ValueByKey="10" x:Name="SliderLauncherTransparent" Grid.Column="1" />
|
||||
</Grid>
|
||||
<Grid x:Name="PanLauncherTheme" Height="90" Margin="0,0,0,7">
|
||||
<Grid Height="22" Margin="0,0,0,7">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="Name1" />
|
||||
<ColumnDefinition />
|
||||
<ColumnDefinition />
|
||||
<ColumnDefinition />
|
||||
<ColumnDefinition />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" Text="主题" Margin="0,0,20,0" />
|
||||
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" Text="隐藏主题" Margin="0,0,20,0" Grid.Row="1" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="0"
|
||||
Grid.Column="1" Grid.Row="0" Text="龙猫蓝" x:Name="RadioLauncherTheme0" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="1"
|
||||
Grid.Column="2" Grid.Row="0" Text="甜柠青" x:Name="RadioLauncherTheme1" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="2"
|
||||
Grid.Column="3" Grid.Row="0" Text="小草绿" x:Name="RadioLauncherTheme2" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="3"
|
||||
Grid.Column="4" Grid.Row="0" Text="菠萝黄" x:Name="RadioLauncherTheme3" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="4"
|
||||
Grid.Column="5" Grid.Row="0" Text="橡木棕" x:Name="RadioLauncherTheme4" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="5"
|
||||
Grid.Column="1" Grid.Row="1" Text="玄素黑" x:Name="RadioLauncherTheme5" Opacity="0" ToolTip="灰色是个谎言" />
|
||||
<local:MyRadioBox Grid.Column="1" Grid.Row="1" Text="玄素黑" x:Name="RadioLauncherTheme5Gray" IsEnabled="False" Opacity="1" />
|
||||
<TextBlock Grid.Column="1" Grid.Row="1" x:Name="LabLauncherTheme5Unlock" Background="{StaticResource ColorBrushSemiTransparent}" ToolTip="灰色是个谎言" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="12"
|
||||
Grid.Column="2" Grid.Row="1" Text="滑稽彩" x:Name="RadioLauncherTheme12" IsEnabled="False" ToolTip="滑稽树上滑稽果,滑稽树下你和我,滑稽之日搞事情,欢乐多又多" ToolTipService.ShowOnDisabled="True" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="6"
|
||||
Grid.Column="3" Grid.Row="1" Text="铁杆粉" x:Name="RadioLauncherTheme6" IsEnabled="False" ToolTip="99 次重逢的喜悦" ToolTipService.ShowOnDisabled="True" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="7"
|
||||
Grid.Column="4" Grid.Row="1" Text="神秘紫" x:Name="RadioLauncherTheme7" IsEnabled="False" ToolTip="072 101 108 112 032 068 101 118 032 048 046 052 046 052" ToolTipService.ShowOnDisabled="True" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="13"
|
||||
Grid.Column="5" Grid.Row="1" Text="欧皇彩" x:Name="RadioLauncherTheme13" IsEnabled="False" ToolTip="这就是传说中的欧皇了吧" ToolTipService.ShowOnDisabled="True" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="8"
|
||||
Grid.Column="1" Grid.Row="2" Text="秋仪金" x:Name="RadioLauncherTheme8" IsEnabled="False" />
|
||||
<TextBlock Grid.Column="1" Grid.Row="2" x:Name="LabLauncherTheme8Copy" Background="{StaticResource ColorBrushSemiTransparent}" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="9"
|
||||
Grid.Column="2" Grid.Row="2" Text="活跃橙" x:Name="RadioLauncherTheme9" IsEnabled="False" />
|
||||
<TextBlock Grid.Column="2" Grid.Row="2" x:Name="LabLauncherTheme9Copy" Background="{StaticResource ColorBrushSemiTransparent}" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="10"
|
||||
Grid.Column="3" Grid.Row="2" Text="跳票红" x:Name="RadioLauncherTheme10" IsEnabled="False" ToolTip="进行一次正版登录,支持正版游戏!" ToolTipService.ShowOnDisabled="True" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="11"
|
||||
Grid.Column="4" Grid.Row="2" Text="极客蓝" x:Name="RadioLauncherTheme11" IsEnabled="False" ToolTip="右键打开解密游戏入口" />
|
||||
<TextBlock Grid.Column="4" Grid.Row="2" x:Name="LabLauncherTheme11Click" Background="{StaticResource ColorBrushSemiTransparent}" />
|
||||
<local:MyRadioBox local:SettingService.Key="UiLauncherTheme" local:SettingService.Value="14"
|
||||
Grid.Column="5" Grid.Row="2" Text="自定义" x:Name="RadioLauncherTheme14" IsEnabled="False" ToolTip="需要解锁五个隐藏主题" ToolTipService.ShowOnDisabled="True" />
|
||||
<TextBlock Grid.Column="1" VerticalAlignment="Center" Text="龙猫蓝" Foreground="{DynamicResource ColorBrush3}"
|
||||
ToolTip="此版本使用固定的龙猫蓝配色。" />
|
||||
</Grid>
|
||||
<local:MyCheckBox local:SettingService.Key="UiLauncherLogo" Text="打开启动器时显示 PCL 图标" Margin="-1,0,0,1" Height="22" />
|
||||
</StackPanel>
|
||||
<Border Background="#DDDDDDDD" Margin="-8,23,-5,28" CornerRadius="4" Name="PanLauncherHide" Visibility="Collapsed">
|
||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||
<TextBlock Text="如果可以小小赞助一下 PCL,就能解锁主题颜色更换功能啦……
多亏了大家的支持,PCL 才能在免费、无任何广告的情况下维持数年的更新(磕头)!" FontSize="13" Margin="0,0,0,0" />
|
||||
<local:MyButton Height="32" MinWidth="140" Text="支持 PCL 开发!" Padding="13,0" HorizontalAlignment="Center" Margin="0,9,0,0" ColorType="Highlight"
|
||||
local:CustomEventService.EventType="打开网页" local:CustomEventService.EventData="https://meloong.com/afd/a/LTCat" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</local:MyCard>
|
||||
<local:MyCard x:Name="CardBackground" Margin="0,0,0,15" Title="背景图片">
|
||||
|
||||
@@ -4,18 +4,6 @@ Public Class PageSetupUI
|
||||
'重复加载部分
|
||||
PanBack.ScrollToHome()
|
||||
ThemeCheckAll(True)
|
||||
If ThemeDontClick <> 0 Then
|
||||
Dim NewText As String = Nothing
|
||||
Select Case ThemeDontClick
|
||||
Case 1
|
||||
NewText = "眼瞎白"
|
||||
Case 2
|
||||
NewText = "真·滑稽彩"
|
||||
End Select
|
||||
For Each Control In PanLauncherTheme.Children
|
||||
If (TypeOf Control Is MyRadioBox) AndAlso CType(Control, MyRadioBox).IsEnabled Then CType(Control, MyRadioBox).Text = NewText
|
||||
Next
|
||||
End If
|
||||
|
||||
AniControlEnabled += 1
|
||||
Refresh() '#4826
|
||||
@@ -28,15 +16,6 @@ Public Class PageSetupUI
|
||||
|
||||
SliderLoad()
|
||||
|
||||
If BuildType = BuildTypes.Release Then PanLauncherHide.Visibility = Visibility.Visible
|
||||
|
||||
'设置解锁
|
||||
If Not RadioLauncherTheme8.IsEnabled Then LabLauncherTheme8Copy.ToolTip = $"累积赞助达到 ¥23.33 后,在爱发电私信发送【土豆 {Identify}】以解锁。" & vbCrLf & "右键打开赞助页面,如果觉得 PCL 做得还不错就支持一下吧 =w=!"
|
||||
RadioLauncherTheme8.ToolTip = $"累积赞助达到 ¥23.33 后,在爱发电私信发送【土豆 {Identify}】以解锁"
|
||||
If Not RadioLauncherTheme9.IsEnabled Then LabLauncherTheme9Copy.ToolTip = "· 反馈一个 Bug,在标记为 [完成] 后回复识别码要求解锁(右键打开反馈页面)" & vbCrLf & "· 提交一个 Pull Request 或主页预设,在标记为 [完成] 后回复识别码要求解锁"
|
||||
RadioLauncherTheme9.ToolTip = "· 反馈一个 Bug,在标记为 [完成] 后回复识别码要求解锁" & vbCrLf & "· 提交一个 Pull Request 或主页预设,在标记为 [完成] 后回复识别码要求解锁"
|
||||
'极客蓝的处理在 ThemeCheck 中
|
||||
|
||||
End Sub
|
||||
Public Sub Refresh()
|
||||
Try
|
||||
@@ -350,70 +329,6 @@ Refresh:
|
||||
End If
|
||||
End Sub
|
||||
|
||||
'主题
|
||||
Private Sub LabLauncherTheme5Unlock_MouseLeftButtonUp(sender As Object, e As MouseButtonEventArgs) Handles LabLauncherTheme5Unlock.MouseLeftButtonUp
|
||||
RadioLauncherTheme5Gray.Opacity -= 0.7
|
||||
RadioLauncherTheme5.Opacity += 0.7
|
||||
AniStart({
|
||||
AaOpacity(RadioLauncherTheme5Gray, 1, 1000 * AniSpeed, 500 * AniSpeed, New AniEaseInFluent),
|
||||
AaOpacity(RadioLauncherTheme5, -1, 1000 * AniSpeed, 500 * AniSpeed, New AniEaseInFluent)
|
||||
}, "ThemeUnlock")
|
||||
If RadioLauncherTheme5Gray.Opacity < 0.02 Then
|
||||
ThemeUnlock(5, UnlockHint:="隐藏主题 玄素黑 已解锁!")
|
||||
AniStop("ThemeUnlock")
|
||||
RadioLauncherTheme5.Checked = True
|
||||
End If
|
||||
End Sub
|
||||
Private Sub LabLauncherTheme11Click_MouseLeftButtonUp() Handles LabLauncherTheme11Click.MouseLeftButtonUp, RadioLauncherTheme11.MouseRightButtonUp
|
||||
If LabLauncherTheme11Click.Visibility = Visibility.Collapsed OrElse If(LabLauncherTheme11Click.ToolTip, "").ToString.Contains("点击") Then
|
||||
If MyMsgBox(
|
||||
"1. 不爬取或攻击相关服务或网站,不盗取相关账号,没有谜题可以或需要以此来解决。" & vbCrLf &
|
||||
"2. 不得篡改或损毁相关公开信息,请尽量让它们保持原状。" & vbCrLf &
|
||||
"3. 在你感到迷茫的时候,看看回声洞可能会给你带来惊喜。" & vbCrLf & vbCrLf &
|
||||
"若违规,可能会被从任意相关群中踢出!",
|
||||
"解密游戏的基本规则", "我知道了", "恕我拒绝") = 1 Then
|
||||
MyMsgBox("你需要用自己的智慧来找到下一步的线索……" & vbCrLf &
|
||||
"初始线索:gnp.dorC61\60\20\0202\moc.x1xa.2s\\:sp" & "T".Lower & "th", "解密游戏") '防止触发病毒检测规则
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
Private Sub LabLauncherTheme8Copy_MouseRightButtonUp() Handles LabLauncherTheme8Copy.MouseRightButtonUp, RadioLauncherTheme8.MouseRightButtonUp
|
||||
OpenWebsite("https://meloong.com/afd/a/LTCat")
|
||||
End Sub
|
||||
Private Sub LabLauncherTheme9Copy_MouseRightButtonUp() Handles LabLauncherTheme9Copy.MouseRightButtonUp, RadioLauncherTheme9.MouseRightButtonUp
|
||||
PageOtherLeft.TryFeedback()
|
||||
End Sub
|
||||
|
||||
'主题自定义
|
||||
Private Sub RadioLauncherTheme14_Change(sender As Object, e As RouteEventArgs) Handles RadioLauncherTheme14.Changed
|
||||
If RadioLauncherTheme14.Checked Then
|
||||
If LabLauncherHue.Visibility = Visibility.Visible Then Return
|
||||
LabLauncherHue.Visibility = Visibility.Visible
|
||||
SliderLauncherHue.Visibility = Visibility.Visible
|
||||
LabLauncherSat.Visibility = Visibility.Visible
|
||||
SliderLauncherSat.Visibility = Visibility.Visible
|
||||
LabLauncherDelta.Visibility = Visibility.Visible
|
||||
SliderLauncherDelta.Visibility = Visibility.Visible
|
||||
LabLauncherLight.Visibility = Visibility.Visible
|
||||
SliderLauncherLight.Visibility = Visibility.Visible
|
||||
Else
|
||||
If LabLauncherHue.Visibility = Visibility.Collapsed Then Return
|
||||
LabLauncherHue.Visibility = Visibility.Collapsed
|
||||
SliderLauncherHue.Visibility = Visibility.Collapsed
|
||||
LabLauncherSat.Visibility = Visibility.Collapsed
|
||||
SliderLauncherSat.Visibility = Visibility.Collapsed
|
||||
LabLauncherDelta.Visibility = Visibility.Collapsed
|
||||
SliderLauncherDelta.Visibility = Visibility.Collapsed
|
||||
LabLauncherLight.Visibility = Visibility.Collapsed
|
||||
SliderLauncherLight.Visibility = Visibility.Collapsed
|
||||
End If
|
||||
CardLauncher.TriggerForceResize()
|
||||
End Sub
|
||||
Private Sub HSL_Change() Handles SliderLauncherHue.Change, SliderLauncherLight.Change, SliderLauncherSat.Change, SliderLauncherDelta.Change
|
||||
If AniControlEnabled <> 0 OrElse SliderLauncherSat Is Nothing OrElse Not SliderLauncherSat.IsLoaded Then Return
|
||||
ThemeRefresh()
|
||||
End Sub
|
||||
|
||||
#Region "功能隐藏"
|
||||
|
||||
Private Shared _HiddenForceShow As Boolean = False
|
||||
@@ -595,28 +510,6 @@ Refresh:
|
||||
Private Sub SliderLoad()
|
||||
SliderMusicVolume.GetHintText = Function(v) Math.Ceiling(v * 0.1) & "%"
|
||||
SliderLauncherTransparent.GetHintText = Function(v) Math.Round(40 + v * 0.1) & "%"
|
||||
SliderLauncherHue.GetHintText = Function(v) v & "°"
|
||||
SliderLauncherSat.GetHintText = Function(v) v & "%"
|
||||
SliderLauncherDelta.GetHintText =
|
||||
Function(Value As Integer) As String
|
||||
If Value > 90 Then
|
||||
Return "+" & (Value - 90)
|
||||
ElseIf Value = 90 Then
|
||||
Return 0
|
||||
Else
|
||||
Return Value - 90
|
||||
End If
|
||||
End Function
|
||||
SliderLauncherLight.GetHintText =
|
||||
Function(Value As Integer) As String
|
||||
If Value > 20 Then
|
||||
Return "+" & (Value - 20)
|
||||
ElseIf Value = 20 Then
|
||||
Return 0
|
||||
Else
|
||||
Return Value - 20
|
||||
End If
|
||||
End Function
|
||||
SliderBackgroundOpacity.GetHintText = Function(v) Math.Round(v * 0.1) & "%"
|
||||
SliderBackgroundBlur.GetHintText = Function(v) v & " 像素"
|
||||
End Sub
|
||||
|
||||
@@ -723,6 +723,9 @@
|
||||
<DependentUpon>Settings.settings</DependentUpon>
|
||||
<DesignTimeSharedInput>True</DesignTimeSharedInput>
|
||||
</Compile>
|
||||
<EmbeddedResource Include="obj\BuildCredentials.json" Condition="Exists('obj\BuildCredentials.json')">
|
||||
<LogicalName>PCL.BuildCredentials.json</LogicalName>
|
||||
</EmbeddedResource>
|
||||
<EmbeddedResource Include="My Project\Resources.resx">
|
||||
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
|
||||
<CustomToolNamespace>My.Resources</CustomToolNamespace>
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
代码并不是实时更新的,它会在每次 PCL 发布更新时同步一次。<br/>
|
||||
非常感谢社区的大力支持!
|
||||
|
||||
PCL-ISE 的构建配置和发布流程见 [Gitea 自动构建与发布](docs/gitea-release.md)。
|
||||
|
||||
<br/>
|
||||
|
||||
### 相关资源
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# PCL-ISE 0.1.2 开发测试版
|
||||
|
||||
Plain Craft Launcher (PCL) InfstarMC Edition 是 InfstarMC 基于 PCL 独立修改的第三方版本。本版本主要用于测试从 0.1.1 升级至 0.1.2,功能仍在开发中。
|
||||
|
||||
## 本次变化
|
||||
|
||||
- 改进更新文件替换:等待旧进程退出,校验暂存文件与旧版备份,替换失败时恢复旧程序,并在下次启动时反馈结果。
|
||||
- 新增“检查快照更新”:仅检查仓库中公开的 Pre-release,按三位版本号选择最高版本;普通“检查更新”继续读取普通 Release。
|
||||
- 移除“复制识别码”和“输入土豆码”入口,不再使用上游赞助资格控制本项目更新。
|
||||
- 主题固定为龙猫蓝,移除其他主题、自定义调色和主题解锁入口;迁移旧主题设置时保留背景、音乐和透明度偏好。
|
||||
- 支持构建时内嵌微软 Client ID 等配置,保留运行时环境变量覆盖方式。
|
||||
|
||||
## 下载与更新测试
|
||||
|
||||
- `PCL-ISE.exe`:0.1.2 开发构建(Snapshot 配置),程序集版本为 `0.1.2.0`。
|
||||
- `PCL-ISE.exe.sha256`:与可执行文件匹配的 SHA256 校验值。
|
||||
- 使用现有 0.1.1,在“设置 → 其他 → 启动器 → 检查更新”中下载并更新,确认重启后显示 0.1.2,并检查旧程序的 `.bak` 备份。
|
||||
- 建议先在独立目录中测试。若旧版更新失败,保留日志并手动下载本版本。
|
||||
|
||||
为让现有 0.1.1 的 `/releases/latest` 更新入口发现本版本,此开发测试版使用普通 Release 发布,不代表功能已稳定。“检查快照更新”只读取 Pre-release,不会将本次普通发布作为快照提供。
|
||||
|
||||
## 配置与限制
|
||||
|
||||
- 本次发布包内置 InfstarMC 微软应用的公共 Client ID,实际正版登录仍取决于微软应用及 Xbox / Minecraft 服务的访问许可。
|
||||
- 若 CI 未配置 CurseForge API Key,可通过运行时环境变量 `PCL_CURSEFORGE_API_KEY` 自行配置。
|
||||
- 更新仍由按钮手动触发,尚未实现后台自动检查。
|
||||
- 完整的用户界面操作和真实账户登录仍需人工测试。
|
||||
|
||||
## 源码与署名
|
||||
|
||||
源码及子模块配置见 `v0.1.2` 标签。克隆请使用 `git clone --recurse-submodules https://git.infstar.cn/InfStarMC/PCL-ISE`。
|
||||
|
||||
上游项目:[Meloong-Git/PCL](https://github.com/Meloong-Git/PCL)。原作者:龙腾猫跃;[赞助原作者](https://meloong.com/afd/a/LTCat)。使用与分发请遵守仓库中的 `LICENCE`。
|
||||
@@ -0,0 +1,60 @@
|
||||
# Gitea 自动构建与发布
|
||||
|
||||
工作流位于 `.gitea/workflows/release.yml`。推送 `v主版本.次版本.修订版本` 标签后,自动编译并发布 `PCL-ISE.exe` 和 `PCL-ISE.exe.sha256`。两个附件上传完成后才公开 Release,现有 Release 不会被覆盖。当前开发阶段默认使用 `Snapshot` 构建配置,但仍发布为普通 Release,让已有版本的“检查更新”能够发现它;构建配置和 Gitea 的 Pre-release 标记是两个独立设置。
|
||||
|
||||
## 仓库配置
|
||||
|
||||
在仓库设置中开启 Actions,并在“Actions → 变量 / 密钥”中添加:
|
||||
|
||||
| 类型 | 名称 | 内容 |
|
||||
| --- | --- | --- |
|
||||
| Variable | `PCL_MS_CLIENT_ID` | 可选;默认使用 InfstarMC 微软应用的公共客户端 ID:`4609f0a4-9d6f-40f0-918e-6d3a00413903` |
|
||||
| Variable | `PCL_BUILD_CONFIGURATION` | 可选;默认为 `Snapshot`,需要正式构建时设置为 `Release` |
|
||||
| Variable | `PCL_WINDOWS_RUNNER_LABEL` | 可选;默认为 `windows`,应匹配已具备 Windows 构建环境的主机 Runner 标签 |
|
||||
| Secret | `PCL_CURSEFORGE_API_KEY` | 你申请的 CurseForge API Key;可不填,此时发布包不包含该配置 |
|
||||
| Secret | `RELEASE_TOKEN` | 可选;默认使用 Gitea 自动提供的、仅作用于当前仓库的临时 `GITEA_TOKEN`;仅当服务器不允许任务令牌发布时,才配置专用发布令牌 |
|
||||
|
||||
微软应用需要支持个人 Microsoft 账户、开启公共客户端流,并具备 Xbox / Minecraft 服务要求的访问许可。设备码登录不需要微软客户端密钥,**不要添加或打包 Microsoft Client Secret**。
|
||||
|
||||
任务令牌及可选的 `RELEASE_TOKEN` 只用于 CI 发布,不会打入启动器。工作流申请代码只读和发布写入权限,服务器配置的最大任务权限仍可能限制发布。仓库 Secrets 可以防止 API Key 出现在源码和普通 CI 日志中;**内嵌到 exe 的 API Key 仍能被提取**。只打包服务商允许随桌面客户端分发的凭据,需要保密的密钥应保存在服务端。
|
||||
|
||||
## Windows Runner
|
||||
|
||||
此项目使用 WPF 和 .NET Framework 4.8,需要 Windows 主机 Runner。注册时配置标签 `windows:host`,并预装:
|
||||
|
||||
- PowerShell 7、Git 和 Node.js 20 或更新版本。
|
||||
- Visual Studio / Build Tools,包含 .NET 桌面构建工具及 .NET Framework 4.8 目标包;MSBuild 需支持 .NET 9 SDK。
|
||||
- 工作流会安装 .NET 9 SDK;Runner 需能访问 GitHub、NuGet 和子模块仓库。
|
||||
|
||||
Docker 部署的 Linux Runner 不能直接承担此 WPF / .NET Framework 构建,只有同名标签不足以提供 Windows 环境。如果已有 Windows 主机 Runner 使用其他标签,请设置 `PCL_WINDOWS_RUNNER_LABEL`。主机 Runner 会直接执行仓库代码,应只运行可信仓库的任务。
|
||||
|
||||
## 发布步骤
|
||||
|
||||
1. 更新 `ModBase.vb` 的 `VersionBaseName`,以及 `My Project/AssemblyInfo.vb` 的两个程序集版本。
|
||||
2. 添加对应的 `docs/changelog/版本号.md`,提交修改。
|
||||
3. 推送相同版本的标签,例如:
|
||||
|
||||
```powershell
|
||||
git tag v0.1.2
|
||||
git push origin v0.1.2
|
||||
```
|
||||
|
||||
标签必须与程序集版本一致。上面的 `v0.1.2` 仅是示例,请使用实际的新版本号;已有的 `v0.1.1` Release 不会被覆盖。构建和发布脚本不会自动提交修改或创建标签。
|
||||
|
||||
发布失败时,已创建的 Release 会保留为草稿。检查并清理该草稿后可重跑任务;流程不会自动覆盖已存在的发布。
|
||||
|
||||
## 配置打包方式
|
||||
|
||||
`scripts/Write-BuildCredentials.ps1` 从进程环境变量读取配置,在被 Git 忽略的 `obj/BuildCredentials.json` 中生成 UTF-8 JSON。编译器将其作为资源嵌入 exe,构建结束后工作流删除该 JSON。密钥通过环境变量传递,不拼接到 PowerShell 源码或命令行中。
|
||||
|
||||
启动器优先使用玩家电脑上的非空环境变量,未设置时使用内嵌配置。内嵌 Client ID 后,玩家无需再设置 `PCL_MS_CLIENT_ID`。自行编译时,不生成 JSON 也能构建,仍可使用运行时环境变量。
|
||||
|
||||
本地验证打包:在当前 PowerShell 进程设置 `PCL_MS_CLIENT_ID` 和可选的 `PCL_CURSEFORGE_API_KEY`,然后依次执行:
|
||||
|
||||
```powershell
|
||||
./scripts/Write-BuildCredentials.ps1 -RequireMicrosoftClientId
|
||||
dotnet restore PCLCS/PCLCS.csproj
|
||||
./.vscode/build.ps1 -Configuration Release
|
||||
```
|
||||
|
||||
完成后删除 `Plain Craft Launcher 2/obj/BuildCredentials.json`,避免后续本地构建沿用这些配置。不要提交、上传完整 `obj` 目录或包含凭据的诊断日志。
|
||||
@@ -0,0 +1,23 @@
|
||||
# PCL-ISE 快照更新入口
|
||||
|
||||
“设置 → 其他 → 启动器”和“更多 → 关于”均提供两个独立入口:
|
||||
|
||||
- **检查更新**:检查 InfstarMC Gitea 的最新普通 Release。
|
||||
- **检查快照更新**:读取发布列表,仅检查非草稿的 Pre-release,按三位版本号选择最高版本。快照对应 PCL-ISE 的开发测试版。
|
||||
|
||||
原有“复制识别码”“输入土豆码”入口及相关更新提示已移除。此功能不使用上游 PCL 的赞助资格,也未接入此前暂缓的资格验证服务。原作者署名、赞助链接保留。
|
||||
|
||||
两个入口都是手动触发,不改变后台自动更新策略。快照检查不会覆盖正式版检查缓存。选择下载后共用文件大小、SHA256、程序集版本检查及备份恢复流程,只有发布版本号高于当前版本时才会提供更新;切换入口不会自动降级。
|
||||
|
||||
## 发布约定
|
||||
|
||||
- 快照构建使用 `Snapshot` 配置,发布时必须勾选 Gitea 的“预发布 / Pre-release”;不要勾选草稿。
|
||||
- 每个发布使用新的三位版本号,标签如 `v0.1.2`,对应程序集版本 `0.1.2.0`。不同包不要复用同一版本号。
|
||||
- 附件继续使用 `PCL-ISE.exe`,并提供匹配的 `PCL-ISE.exe.sha256`。
|
||||
- 仓库暂无 Pre-release 时,启动器明确提示没有可用的快照发布。
|
||||
|
||||
现有标签自动发布工作流仍按普通 Release 发布,尚未加入快照发布选项。发布快照需要另行准备 Pre-release 流程,不应先公开为正式版再改标记,以免被正式版客户端下载。此改动不发布新版本,也不修改已有的 `v0.1.1` 发布。
|
||||
|
||||
## 验证
|
||||
|
||||
`tests/Check-SnapshotUpdates.cs` 使用独立合成发布数据验证跨页筛选、数字版本排序、草稿排除、正式/快照类型隔离、空列表和请求失败。`tests/Test-LauncherUpdate.ps1` 验证共用的文件替换和恢复流程。
|
||||
@@ -0,0 +1,37 @@
|
||||
# PCL-ISE 更新文件替换
|
||||
|
||||
更新检查、附件下载、SHA256 和程序集版本校验继续使用 InfstarMC Gitea Release。文件替换参考 PCL-CE 的“备份、删除、复制、恢复”流程,兼容原有的五参数命令:
|
||||
|
||||
```text
|
||||
--update 旧进程ID "安装位置.exe" "已下载的新版.exe" 是否立即重启
|
||||
```
|
||||
|
||||
更新由下载好的新版 EXE 执行,旧版调用方不需要支持新的参数格式。
|
||||
|
||||
## 替换顺序
|
||||
|
||||
1. 等待旧进程退出,最长 30 秒;超时不修改安装位置。
|
||||
2. 在安装目录暂存新版副本,并比对 SHA256。
|
||||
3. 将旧程序复制到 `安装位置.exe.bak`,验证备份 SHA256,成功后才允许删除旧程序。
|
||||
4. 删除旧程序,复制新版,再次校验安装位置的 SHA256。
|
||||
5. 复制或校验失败时,从备份覆盖恢复目标文件,包括已经生成了不完整目标文件的情况;恢复后再次校验。
|
||||
|
||||
文件写入和删除遇到 I/O 或权限错误时进行有界重试,每一步最长约 5 秒。若恢复同样失败,保留备份和下载文件,并同时报告更新、恢复两次失败。成功后保留 `.bak`,下一次成功备份会覆盖它。
|
||||
|
||||
更新助手在加载界面、字体检查和开发测试之前执行。启动助手有重复调用保护。
|
||||
|
||||
## 结果反馈
|
||||
|
||||
更新助手在目标目录的 `PCL/UpdateResult-程序名.exe.json` 中保存结果,包含成功状态、备份位置、错误原因和助手进程 ID。
|
||||
|
||||
- 立即更新:替换成功后重启安装位置的程序;自动重启失败时提示手动启动。
|
||||
- 退出时更新:不自动打开窗口,下次手动启动时读取结果。
|
||||
- 主窗口初始化后,在后台等待助手退出,显示成功或失败提示,记录日志并消费结果文件。
|
||||
- 成功安装后仅清理当前版本位于启动器更新缓存目录内的下载文件;其他来源路径保留。旧版备份保留。
|
||||
- 静默执行失败时保存结果并返回失败码,不弹出阻塞助手退出的对话框。立即更新失败会显示错误和备份位置。
|
||||
|
||||
## 验证
|
||||
|
||||
`tests/Test-LauncherUpdate.ps1` 覆盖正常替换、退出等待、备份失败、复制中断、目标校验失败、恢复失败、临时 I/O 错误重试,以及真实 EXE 助手的成功和失败结果记录。故障模拟仅作用于独立测试目录,不修改已安装的启动器。
|
||||
|
||||
发布新版需使用新的三位版本号。此次机制调整不修改既有 `v0.1.1` 的发布附件。
|
||||
@@ -0,0 +1,57 @@
|
||||
#Requires -Version 7.0
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$ServerUrl,
|
||||
[Parameter(Mandatory)][string]$Repository,
|
||||
[Parameter(Mandatory)][string]$Tag,
|
||||
[string]$ArtifactDirectory = (Join-Path $PSScriptRoot '..\artifacts\release')
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ([string]::IsNullOrWhiteSpace($env:PCL_RELEASE_TOKEN)) {
|
||||
throw 'Provide the job token GITEA_TOKEN or repository secret RELEASE_TOKEN with permission to publish releases.'
|
||||
}
|
||||
if ($Tag -cnotmatch '^v\d+\.\d+\.\d+$') { throw 'Release tags must use vMAJOR.MINOR.PATCH, for example v0.1.2.' }
|
||||
if ($Repository -notmatch '^[^/]+/[^/]+$') { throw 'Repository must use owner/repository format.' }
|
||||
|
||||
$exePath = Join-Path $ArtifactDirectory 'PCL-ISE.exe'
|
||||
$hashPath = Join-Path $ArtifactDirectory 'PCL-ISE.exe.sha256'
|
||||
foreach ($path in @($exePath, $hashPath)) {
|
||||
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw 'A release asset is missing.' }
|
||||
}
|
||||
$version = [Reflection.AssemblyName]::GetAssemblyName($exePath).Version
|
||||
if ($version -ne [Version]($Tag.Substring(1) + '.0')) { throw 'Release tag does not match the executable assembly version.' }
|
||||
$expectedHash = (Get-FileHash -LiteralPath $exePath -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
$checksum = [IO.File]::ReadAllText($hashPath).Trim()
|
||||
if ($checksum -cne "$expectedHash PCL-ISE.exe") { throw 'The release checksum does not match the executable.' }
|
||||
|
||||
$repositoryPath = ($Repository.Split('/') | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/'
|
||||
$apiUrl = $ServerUrl.TrimEnd('/') + '/api/v1/repos/' + $repositoryPath + '/releases'
|
||||
$headers = @{ Authorization = 'token ' + $env:PCL_RELEASE_TOKEN }
|
||||
try {
|
||||
$null = Invoke-RestMethod -Method Get -Uri "$apiUrl/tags/$Tag" -Headers $headers
|
||||
throw 'A release already exists for this tag. Existing releases are never overwritten.'
|
||||
} catch {
|
||||
if (-not $_.Exception.Response -or [int]$_.Exception.Response.StatusCode -ne 404) { throw }
|
||||
}
|
||||
|
||||
$notesPath = Join-Path $PSScriptRoot ('..\docs\changelog\' + $Tag.Substring(1) + '.md')
|
||||
if (-not (Test-Path -LiteralPath $notesPath -PathType Leaf)) {
|
||||
throw 'Add docs/changelog/MAJOR.MINOR.PATCH.md before publishing a release.'
|
||||
}
|
||||
$payload = @{
|
||||
tag_name = $Tag
|
||||
name = "PCL-ISE $Tag"
|
||||
body = [IO.File]::ReadAllText($notesPath)
|
||||
draft = $true
|
||||
prerelease = $false
|
||||
} | ConvertTo-Json
|
||||
$release = Invoke-RestMethod -Method Post -Uri $apiUrl -Headers $headers -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($payload))
|
||||
|
||||
# Keep the release as a draft if either asset upload fails.
|
||||
foreach ($path in @($exePath, $hashPath)) {
|
||||
$name = [Uri]::EscapeDataString([IO.Path]::GetFileName($path))
|
||||
$null = Invoke-RestMethod -Method Post -Uri "$apiUrl/$($release.id)/assets?name=$name" -Headers $headers -Form @{ attachment = Get-Item -LiteralPath $path }
|
||||
}
|
||||
$published = Invoke-RestMethod -Method Patch -Uri "$apiUrl/$($release.id)" -Headers $headers -ContentType 'application/json' -Body '{"draft":false}'
|
||||
Write-Host ('Published release: ' + $published.html_url)
|
||||
@@ -0,0 +1,31 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$OutputPath = (Join-Path $PSScriptRoot '..\Plain Craft Launcher 2\obj\BuildCredentials.json'),
|
||||
[switch]$RequireMicrosoftClientId
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$OutputPath = [IO.Path]::GetFullPath($OutputPath)
|
||||
# Remove credentials from a previous run before validating new input.
|
||||
if (Test-Path -LiteralPath $OutputPath) { Remove-Item -LiteralPath $OutputPath -Force }
|
||||
|
||||
$clientId = $env:PCL_MS_CLIENT_ID
|
||||
if ($clientId) { $clientId = $clientId.Trim() }
|
||||
if ($RequireMicrosoftClientId -and [string]::IsNullOrWhiteSpace($clientId)) {
|
||||
throw 'Set the repository variable PCL_MS_CLIENT_ID before building a release.'
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($clientId)) {
|
||||
$parsedId = [Guid]::Empty
|
||||
if (-not [Guid]::TryParse($clientId, [ref]$parsedId) -or $parsedId -eq [Guid]::Empty) {
|
||||
throw 'PCL_MS_CLIENT_ID must be a non-empty application client GUID.'
|
||||
}
|
||||
}
|
||||
|
||||
$credentials = [ordered]@{
|
||||
PCL_MS_CLIENT_ID = [string]$clientId
|
||||
PCL_CURSEFORGE_API_KEY = [string]$env:PCL_CURSEFORGE_API_KEY
|
||||
}
|
||||
[IO.Directory]::CreateDirectory((Split-Path $OutputPath -Parent)) | Out-Null
|
||||
[IO.File]::WriteAllText($OutputPath, ($credentials | ConvertTo-Json -Compress), [Text.UTF8Encoding]::new($false))
|
||||
Write-Host ('Microsoft Client ID embedded: ' + (-not [string]::IsNullOrWhiteSpace($clientId)))
|
||||
Write-Host ('CurseForge API key embedded: ' + (-not [string]::IsNullOrWhiteSpace($env:PCL_CURSEFORGE_API_KEY)))
|
||||
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
|
||||
// Compile with the .NET Framework csc.exe. No UI startup or network calls.
|
||||
internal static class CheckBuildCredentials {
|
||||
[STAThread]
|
||||
private static int Main(string[] args) {
|
||||
try {
|
||||
string expectedClientId = (Environment.GetEnvironmentVariable("PCL_MS_CLIENT_ID") ?? "").Trim();
|
||||
string expectedApiKey = Environment.GetEnvironmentVariable("PCL_CURSEFORGE_API_KEY") ?? "";
|
||||
string mode = args[1];
|
||||
if (mode == "override") {
|
||||
expectedClientId = "11111111-1111-4111-8111-111111111111";
|
||||
expectedApiKey = "synthetic-override-only-$\"&\\";
|
||||
Environment.SetEnvironmentVariable("PCL_MS_CLIENT_ID", expectedClientId);
|
||||
Environment.SetEnvironmentVariable("PCL_CURSEFORGE_API_KEY", expectedApiKey);
|
||||
} else if (mode == "blank-override") {
|
||||
Environment.SetEnvironmentVariable("PCL_MS_CLIENT_ID", " ");
|
||||
Environment.SetEnvironmentVariable("PCL_CURSEFORGE_API_KEY", " ");
|
||||
} else if (mode == "packaged" || mode == "empty") {
|
||||
Environment.SetEnvironmentVariable("PCL_MS_CLIENT_ID", null);
|
||||
Environment.SetEnvironmentVariable("PCL_CURSEFORGE_API_KEY", null);
|
||||
if (mode == "empty") { expectedClientId = ""; expectedApiKey = ""; }
|
||||
} else {
|
||||
throw new ArgumentException("Unknown test mode");
|
||||
}
|
||||
|
||||
Assembly launcher = Assembly.LoadFrom(Path.GetFullPath(args[0]));
|
||||
using (Stream resource = launcher.GetManifestResourceStream("PCL.BuildCredentials.json")) {
|
||||
if ((resource == null) != (mode == "empty"))
|
||||
throw new InvalidDataException("Unexpected build configuration resource");
|
||||
}
|
||||
Activator.CreateInstance(launcher.GetType("PCL.Application", true), true);
|
||||
Type module = launcher.GetType("PCL.ModSecret", true);
|
||||
string actualClientId = (string)module.GetField("OAuthClientId").GetValue(null);
|
||||
string actualApiKey = (string)module.GetField("CurseForgeAPIKey").GetValue(null);
|
||||
if (actualClientId != expectedClientId || actualApiKey != expectedApiKey)
|
||||
throw new InvalidDataException("Build configuration did not match expected values");
|
||||
Console.WriteLine("PASS: build configuration " + mode);
|
||||
return 0;
|
||||
} catch (Exception ex) {
|
||||
// Never include credential values in diagnostic output.
|
||||
Console.Error.WriteLine(ex.GetType().Name + ": build configuration check failed");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
[assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
|
||||
|
||||
// Run from a fresh ThemeTest_* directory. Only that directory's synthetic
|
||||
// Setup.ini is migrated; no launcher window, registry writes or network calls.
|
||||
internal static class CheckFixedTheme {
|
||||
private static int passed;
|
||||
|
||||
private static void Assert(bool condition, string description) {
|
||||
if (!condition) throw new Exception("FAIL: " + description);
|
||||
passed++;
|
||||
Console.WriteLine("PASS: " + description);
|
||||
}
|
||||
|
||||
[STAThread]
|
||||
private static int Main(string[] args) {
|
||||
try {
|
||||
string isolatedRoot = AppDomain.CurrentDomain.BaseDirectory;
|
||||
if (!new DirectoryInfo(isolatedRoot).Name.StartsWith("ThemeTest_", StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("Run the checker from a fresh ThemeTest_* directory");
|
||||
string configDirectory = Path.Combine(isolatedRoot, "PCL");
|
||||
Directory.CreateDirectory(configDirectory);
|
||||
string configPath = Path.Combine(configDirectory, "Setup.ini");
|
||||
if (File.Exists(configPath)) throw new InvalidOperationException("Use a fresh test directory");
|
||||
File.WriteAllText(configPath,
|
||||
"UiLauncherTheme:14\r\nUiLauncherHue:345\r\nUiLauncherSat:25\r\nUiLauncherDelta:175\r\nUiLauncherLight:40\r\n" +
|
||||
"UiMusicRandom:False\r\nUiBackgroundColorful:False\r\nUiLauncherTransparent:321\r\nSyntheticThemeTestMarker:keep\r\n");
|
||||
|
||||
Assembly launcher = Assembly.LoadFrom(Path.GetFullPath(args[0]));
|
||||
Type appType = launcher.GetType("PCL.Application", true);
|
||||
Application app = (Application)Activator.CreateInstance(appType, true);
|
||||
Assembly core = Assembly.Load("MeloongCore");
|
||||
core.GetType("MeloongCore.Main", true).GetMethod("Init").Invoke(null, new object[] { "PCL" });
|
||||
string actualRoot = (string)core.GetType("MeloongCore.Paths", true).GetProperty("Base").GetValue(null, null);
|
||||
if (!string.Equals(Path.GetFullPath(actualRoot), Path.GetFullPath(isolatedRoot), StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException("Launcher configuration directory is not isolated");
|
||||
appType.GetMethod("InitializeComponent").Invoke(app, null);
|
||||
launcher.GetType("PCL.ModBase", true).GetMethod("RunInUi", Type.EmptyTypes).Invoke(null, null);
|
||||
|
||||
Type settings = launcher.GetType("PCL.Settings", true);
|
||||
MethodInfo get = settings.GetMethods().Single(m => m.Name == "Get" && !m.IsGenericMethodDefinition);
|
||||
Func<string, object> read = key => get.Invoke(null, new object[] { key, null });
|
||||
Assert((int)read("UiLauncherTheme") == 14, "load a real legacy custom-theme setting from the isolated configuration");
|
||||
|
||||
Type theme = launcher.GetType("PCL.ModSecret", true);
|
||||
MethodInfo migrate = theme.GetMethod("ThemeCheckAll", BindingFlags.NonPublic | BindingFlags.Static);
|
||||
migrate.Invoke(null, new object[] { false });
|
||||
Assert((int)read("UiLauncherTheme") == 0, "legacy theme selection migrates to Cat Blue");
|
||||
string afterMigration = File.ReadAllText(configPath);
|
||||
string[] legacyKeys = { "UiLauncherTheme:", "UiLauncherHue:", "UiLauncherSat:", "UiLauncherDelta:", "UiLauncherLight:" };
|
||||
Assert(legacyKeys.All(key => !afterMigration.Contains(key)), "remove only obsolete theme and tuning overrides from Setup.ini");
|
||||
Assert(!(bool)read("UiMusicRandom") && !(bool)read("UiBackgroundColorful") && (int)read("UiLauncherTransparent") == 321 && afterMigration.Contains("SyntheticThemeTestMarker:keep"), "preserve background, music, opacity and unrelated configuration");
|
||||
|
||||
MethodInfo refresh = theme.GetMethod("ThemeRefresh");
|
||||
refresh.Invoke(null, new object[] { 0 });
|
||||
Color blue = ((SolidColorBrush)app.Resources["ColorBrush3"]).Color;
|
||||
Assert(blue.B > blue.R && blue.B > blue.G, "render the default palette with a blue primary color");
|
||||
foreach (int legacyTheme in new[] { 1, 5, 8, 12, 14 }) {
|
||||
refresh.Invoke(null, new object[] { legacyTheme });
|
||||
Assert(((SolidColorBrush)app.Resources["ColorBrush3"]).Color == blue, "legacy theme argument " + legacyTheme + " retains Cat Blue");
|
||||
}
|
||||
migrate.Invoke(null, new object[] { true });
|
||||
Assert(File.ReadAllText(configPath) == afterMigration, "repeated initialization leaves migrated configuration unchanged");
|
||||
|
||||
Console.WriteLine(passed + " fixed-theme checks passed. Isolated configuration: " + configPath);
|
||||
return 0;
|
||||
} catch (Exception ex) {
|
||||
Console.Error.WriteLine(ex);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@ using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
[assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
|
||||
|
||||
// Run under .NET Framework after compiling with the framework's csc.exe.
|
||||
// Uses the launcher's real release API parser without starting its main window.
|
||||
@@ -9,12 +12,18 @@ internal static class CheckLauncherRelease {
|
||||
[STAThread]
|
||||
private static int Main(string[] args) {
|
||||
try {
|
||||
if (args.Length < 3) throw new ArgumentException("Usage: Check-LauncherRelease.exe <installed launcher> <expected release exe> <expected tag>");
|
||||
string expectedTag = args[2];
|
||||
string expectedVersion = AssemblyName.GetAssemblyName(Path.GetFullPath(args[1])).Version.ToString();
|
||||
Assembly launcher = Assembly.LoadFrom(Path.GetFullPath(args[0]));
|
||||
Activator.CreateInstance(launcher.GetType("PCL.Application", true), true);
|
||||
Assembly core = Assembly.Load("MeloongCore");
|
||||
core.GetType("MeloongCore.Main", true).GetMethod("Init").Invoke(null, new object[] { "PCL" });
|
||||
// Initialize the launcher's UI-thread identity on the main thread,
|
||||
// as normal application startup does, before starting network work.
|
||||
launcher.GetType("PCL.ModBase", true).GetMethod("RunInUi", Type.EmptyTypes).Invoke(null, null);
|
||||
Type module = launcher.GetType("PCL.ModSecret", true);
|
||||
object info = module.GetMethod("GetLatestLauncherUpdate", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null);
|
||||
object info = Task.Run(() => module.GetMethod("GetLatestLauncherUpdate", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null)).GetAwaiter().GetResult();
|
||||
Type infoType = info.GetType();
|
||||
string tag = (string)infoType.GetField("TagName").GetValue(info);
|
||||
string hash = (string)infoType.GetField("AssetHash").GetValue(info);
|
||||
@@ -31,7 +40,11 @@ internal static class CheckLauncherRelease {
|
||||
throw new InvalidDataException("Release SHA256 does not match local build");
|
||||
}
|
||||
}
|
||||
if (tag != "v0.1.1" || version != "0.1.1.0") throw new InvalidDataException("Unexpected test release version");
|
||||
if (tag != expectedTag || version != expectedVersion) throw new InvalidDataException("Unexpected test release version");
|
||||
bool newer = (bool)module.GetMethod("IsUpdateNewer", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { info });
|
||||
bool expectedNewer = new Version(version) > launcher.GetName().Version;
|
||||
if (newer != expectedNewer) throw new InvalidDataException("Unexpected update comparison result");
|
||||
Console.WriteLine("Installed: " + launcher.GetName().Version + ", update offered: " + newer);
|
||||
Console.WriteLine("PASS: launcher resolves published test release and checksum");
|
||||
return 0;
|
||||
} catch (Exception ex) {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
[assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
|
||||
|
||||
// Exercises the real selector with isolated synthetic release pages. No release is
|
||||
// created or downloaded, and the main launcher window is never started.
|
||||
// Optional --live also queries the configured public Gitea endpoints.
|
||||
internal static class CheckSnapshotUpdates {
|
||||
private static int passed;
|
||||
|
||||
private static void Assert(bool condition, string description) {
|
||||
if (!condition) throw new Exception("FAIL: " + description);
|
||||
passed++;
|
||||
Console.WriteLine("PASS: " + description);
|
||||
}
|
||||
|
||||
private static string Tag(object release) {
|
||||
if (release == null) return null;
|
||||
return release.GetType().GetProperty("Item", new[] { typeof(string) })
|
||||
.GetValue(release, new object[] { "tag_name" }).ToString();
|
||||
}
|
||||
|
||||
private static bool Throws<T>(Action action) where T : Exception {
|
||||
try { action(); }
|
||||
catch (TargetInvocationException ex) { return ex.InnerException is T; }
|
||||
return false;
|
||||
}
|
||||
|
||||
[STAThread]
|
||||
private static int Main(string[] args) {
|
||||
try {
|
||||
Assembly launcher = Assembly.LoadFrom(Path.GetFullPath(args[0]));
|
||||
Activator.CreateInstance(launcher.GetType("PCL.Application", true), true);
|
||||
Assembly.Load("MeloongCore").GetType("MeloongCore.Main", true).GetMethod("Init")
|
||||
.Invoke(null, new object[] { "PCL" });
|
||||
launcher.GetType("PCL.ModBase", true).GetMethod("RunInUi", Type.EmptyTypes).Invoke(null, null);
|
||||
Type module = launcher.GetType("PCL.ModSecret", true);
|
||||
MethodInfo select = module.GetMethod("GetLatestSnapshotRelease", BindingFlags.NonPublic | BindingFlags.Static);
|
||||
|
||||
int requests = 0;
|
||||
Func<int, string> pages = page => {
|
||||
requests++;
|
||||
switch (page) {
|
||||
case 1: return "[{\"tag_name\":\"v9.0.0\",\"prerelease\":false,\"draft\":false},{\"tag_name\":\"v0.2.9\",\"prerelease\":true,\"draft\":false},{\"tag_name\":\"v99.0.0\",\"prerelease\":true,\"draft\":true}]";
|
||||
case 2: return "[{\"tag_name\":\"v0.2.10\",\"prerelease\":true,\"draft\":false},{\"tag_name\":\"invalid\",\"prerelease\":true,\"draft\":false},{\"tag_name\":\"v0.1.2\",\"prerelease\":true,\"draft\":false}]";
|
||||
default: return "[]";
|
||||
}
|
||||
};
|
||||
object selected = select.Invoke(null, new object[] { pages });
|
||||
Assert(Tag(selected) == "v0.2.10", "select highest numeric snapshot version across unsorted pages; ignore stable, draft and invalid releases");
|
||||
Assert(requests == 3, "continue short server pages until the first empty page");
|
||||
|
||||
selected = select.Invoke(null, new object[] { new Func<int, string>(page => "[]") });
|
||||
Assert(selected == null, "empty release list has no snapshot update");
|
||||
selected = select.Invoke(null, new object[] { new Func<int, string>(page => page == 1 ? "[{\"tag_name\":\"v0.1.1\",\"prerelease\":false,\"draft\":false}]" : "[]") });
|
||||
Assert(selected == null, "stable-only repository is not offered as a snapshot update");
|
||||
selected = select.Invoke(null, new object[] { new Func<int, string>(page => page == 1 ? "[{\"tag_name\":\"v0.3.0\",\"prerelease\":true,\"draft\":true}]" : "[]") });
|
||||
Assert(selected == null, "unpublished draft snapshot is never offered");
|
||||
|
||||
MethodInfo compare = launcher.GetType("PCL.ModLauncherUpdate", true).GetMethod("ParseLauncherVersion");
|
||||
Version installed = (Version)compare.Invoke(null, new object[] { launcher.GetType("PCL.ModBase", true).GetField("VersionBaseName").GetRawConstantValue() });
|
||||
Type infoType = module.GetNestedType("LauncherUpdateInfo", BindingFlags.NonPublic);
|
||||
object info = Activator.CreateInstance(infoType, true);
|
||||
MethodInfo isNewer = module.GetMethod("IsUpdateNewer", BindingFlags.NonPublic | BindingFlags.Static);
|
||||
infoType.GetField("VersionNumber").SetValue(info, new Version(0, 0, 0, 0));
|
||||
Assert(!(bool)isNewer.Invoke(null, new[] { info }), "older release never triggers an automatic downgrade");
|
||||
infoType.GetField("VersionNumber").SetValue(info, installed);
|
||||
Assert(!(bool)isNewer.Invoke(null, new[] { info }), "same version is not offered as an update");
|
||||
infoType.GetField("VersionNumber").SetValue(info, new Version(installed.Major + 1, 0, 0, 0));
|
||||
Assert((bool)isNewer.Invoke(null, new[] { info }), "newer release is offered through the shared update comparison");
|
||||
|
||||
Assert(Throws<IOException>(() => select.Invoke(null, new object[] { new Func<int, string>(page => { throw new IOException("Synthetic network failure"); }) })), "network failure is reported instead of claiming there are no updates");
|
||||
requests = 0;
|
||||
Assert(Throws<IOException>(() => select.Invoke(null, new object[] { new Func<int, string>(page => { requests++; return "[{\"tag_name\":\"v0.2.0\",\"prerelease\":true,\"draft\":false}]"; }) })), "bounded pagination never offers a partially inspected release list");
|
||||
Assert(requests == 100, "pagination has a finite request limit");
|
||||
|
||||
Assembly json = Assembly.Load("Newtonsoft.Json");
|
||||
MethodInfo parseJson = json.GetType("Newtonsoft.Json.Linq.JObject", true).GetMethod("Parse", new[] { typeof(string) });
|
||||
MethodInfo parseInfo = module.GetMethod("ParseLauncherUpdate", BindingFlags.NonPublic | BindingFlags.Static);
|
||||
object stableJson = parseJson.Invoke(null, new object[] { "{\"prerelease\":false,\"draft\":false}" });
|
||||
object snapshotJson = parseJson.Invoke(null, new object[] { "{\"prerelease\":true,\"draft\":false}" });
|
||||
object draftJson = parseJson.Invoke(null, new object[] { "{\"prerelease\":true,\"draft\":true}" });
|
||||
Assert(Throws<FormatException>(() => parseInfo.Invoke(null, new[] { stableJson, (object)true })), "snapshot parser rejects a stable release");
|
||||
Assert(Throws<FormatException>(() => parseInfo.Invoke(null, new[] { snapshotJson, (object)false })), "stable parser rejects a snapshot release");
|
||||
Assert(Throws<FormatException>(() => parseInfo.Invoke(null, new[] { draftJson, (object)true })), "release parser rejects drafts before downloading or caching");
|
||||
|
||||
if (args.Length > 1 && args[1] == "--live") {
|
||||
object stable = Task.Run(() => module.GetMethod("GetLatestLauncherUpdate", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null)).GetAwaiter().GetResult();
|
||||
Assert(stable != null, "live stable endpoint resolves a release with verified checksum metadata");
|
||||
object snapshot = Task.Run(() => module.GetMethod("GetLatestSnapshotLauncherUpdate", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null)).GetAwaiter().GetResult();
|
||||
if (snapshot == null) {
|
||||
Console.WriteLine("Live snapshot endpoint: no published pre-release.");
|
||||
} else {
|
||||
Console.WriteLine("Live snapshot endpoint: " + infoType.GetField("TagName").GetValue(snapshot));
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine(passed + " snapshot update checks passed.");
|
||||
return 0;
|
||||
} catch (Exception ex) {
|
||||
Console.Error.WriteLine(ex);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
// Faults affect only the named target in an isolated functional test directory.
|
||||
public sealed class TestLauncherUpdateFileOperations : LauncherUpdateFileOperations {
|
||||
public string TargetPath;
|
||||
public int CopyFailuresRemaining;
|
||||
public bool LeavePartialFile;
|
||||
public bool CorruptInstalledFile;
|
||||
public bool FailBackup;
|
||||
public bool FailRestore;
|
||||
public bool FailCleanup;
|
||||
|
||||
public override void CopyFile(string source, string target, bool overwrite) {
|
||||
bool installsTarget = string.Equals(target, TargetPath, StringComparison.OrdinalIgnoreCase)
|
||||
&& source.EndsWith(".new", StringComparison.OrdinalIgnoreCase);
|
||||
if (FailBackup && string.Equals(target, TargetPath + ".bak", StringComparison.OrdinalIgnoreCase))
|
||||
throw new IOException("Test: backup could not be written");
|
||||
if (FailRestore && string.Equals(source, TargetPath + ".bak", StringComparison.OrdinalIgnoreCase))
|
||||
throw new IOException("Test: restore could not be written");
|
||||
if (installsTarget && CopyFailuresRemaining > 0) {
|
||||
CopyFailuresRemaining--;
|
||||
if (LeavePartialFile) File.WriteAllText(target, "incomplete new program");
|
||||
throw new IOException("Test: new program copy interrupted");
|
||||
}
|
||||
base.CopyFile(source, target, overwrite);
|
||||
if (installsTarget && CorruptInstalledFile) File.WriteAllText(target, "incomplete new program");
|
||||
}
|
||||
|
||||
public override void DeleteFile(string target) {
|
||||
if (FailCleanup && target.EndsWith(".new", StringComparison.OrdinalIgnoreCase))
|
||||
throw new IOException("Test: staged file temporarily busy");
|
||||
base.DeleteFile(target);
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,11 @@ $testRoot = Join-Path $repoRoot ('artifacts\update-tests\' + [Guid]::NewGuid().T
|
||||
[IO.Directory]::CreateDirectory($testRoot) | Out-Null
|
||||
|
||||
$framework = Join-Path $env:WINDIR 'Microsoft.NET\Framework\v4.0.30319'
|
||||
$testLibrary = Join-Path $testRoot 'LauncherUpdateTests.dll'
|
||||
$testLibrary = Join-Path $testRoot ('LauncherUpdateTests_' + (Split-Path $testRoot -Leaf) + '.dll')
|
||||
& (Join-Path $framework 'vbc.exe') /nologo /target:library "/out:$testLibrary" $sourcePath
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Update module compilation failed' }
|
||||
$updateType = [Reflection.Assembly]::LoadFile($testLibrary).GetType('ModLauncherUpdate')
|
||||
$testAssembly = [Reflection.Assembly]::LoadFrom($testLibrary)
|
||||
$updateType = $testAssembly.GetType('ModLauncherUpdate')
|
||||
$parse = $updateType.GetMethod('ParseLauncherVersion')
|
||||
$replace = $updateType.GetMethod('ReplaceLauncherFile')
|
||||
$testState = @{ Passed = 0 }
|
||||
@@ -20,8 +21,8 @@ function Assert-True([bool]$Condition, [string]$Description) {
|
||||
$testState.Passed++
|
||||
Write-Host "PASS: $Description"
|
||||
}
|
||||
function Replace-File([int]$PreviousId, [string]$Target, [string]$Source, [int]$Timeout = 30000) {
|
||||
$replace.Invoke($null, @($PreviousId, $Target, $Source, $Timeout))
|
||||
function Replace-File([int]$PreviousId, [string]$Target, [string]$Source, [int]$Timeout = 30000, $Operations = $null) {
|
||||
$replace.Invoke($null, @($PreviousId, $Target, $Source, $Timeout, $Operations))
|
||||
}
|
||||
|
||||
foreach ($inputVersion in @('0.1.1', 'v0.1.1', '0.1.1-dev', '0.1.1+build')) {
|
||||
@@ -63,6 +64,78 @@ Replace-File 0 $newTarget $download
|
||||
Assert-True ([IO.File]::ReadAllText($newTarget) -eq 'new version') 'install into absent target'
|
||||
Assert-True (@(Get-ChildItem $testRoot -Filter '*.new').Count -eq 0) 'no staged files left behind'
|
||||
|
||||
$faultLibrary = Join-Path $testRoot 'UpdateFileOperationsTests.dll'
|
||||
& $csc /nologo /target:library "/reference:$testLibrary" "/out:$faultLibrary" (Join-Path $repoRoot 'tests\LauncherUpdateFileOperations.cs')
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Fault operation compilation failed' }
|
||||
$faultType = [Reflection.Assembly]::LoadFrom($faultLibrary).GetType('TestLauncherUpdateFileOperations')
|
||||
function New-FaultOperations([string]$TargetPath) {
|
||||
$operations = [Activator]::CreateInstance($faultType)
|
||||
$operations.TargetPath = $TargetPath
|
||||
$operations.RetryTimeoutMilliseconds = 0
|
||||
return $operations
|
||||
}
|
||||
function Get-ReplaceFailure([string]$TargetPath, $Operations) {
|
||||
try { Replace-File 0 $TargetPath $download 30000 $Operations } catch { return $_.Exception.InnerException }
|
||||
throw 'Expected a file operation failure'
|
||||
}
|
||||
|
||||
$backupFailureTarget = Join-Path $testRoot 'backup-failure.exe'
|
||||
[IO.File]::WriteAllText($backupFailureTarget, 'old version')
|
||||
$fault = New-FaultOperations $backupFailureTarget
|
||||
$fault.FailBackup = $true
|
||||
$failure = Get-ReplaceFailure $backupFailureTarget $fault
|
||||
Assert-True ([IO.File]::ReadAllText($backupFailureTarget) -eq 'old version') 'backup failure never deletes old program'
|
||||
|
||||
$copyFailureTarget = Join-Path $testRoot 'copy-failure.exe'
|
||||
[IO.File]::WriteAllText($copyFailureTarget, 'old version')
|
||||
$fault = New-FaultOperations $copyFailureTarget
|
||||
$fault.CopyFailuresRemaining = 1
|
||||
$fault.LeavePartialFile = $true
|
||||
$failure = Get-ReplaceFailure $copyFailureTarget $fault
|
||||
Assert-True ([IO.File]::ReadAllText($copyFailureTarget) -eq 'old version') 'interrupted copy restores old program over a partial target'
|
||||
Assert-True ([IO.File]::ReadAllText($copyFailureTarget + '.bak') -eq 'old version') 'rollback retains backup'
|
||||
|
||||
$hashFailureTarget = Join-Path $testRoot 'hash-failure.exe'
|
||||
[IO.File]::WriteAllText($hashFailureTarget, 'old version')
|
||||
$fault = New-FaultOperations $hashFailureTarget
|
||||
$fault.CorruptInstalledFile = $true
|
||||
$failure = Get-ReplaceFailure $hashFailureTarget $fault
|
||||
Assert-True ([IO.File]::ReadAllText($hashFailureTarget) -eq 'old version') 'installed file hash failure restores old program'
|
||||
|
||||
$restoreFailureTarget = Join-Path $testRoot 'restore-failure.exe'
|
||||
[IO.File]::WriteAllText($restoreFailureTarget, 'old version')
|
||||
$fault = New-FaultOperations $restoreFailureTarget
|
||||
$fault.CopyFailuresRemaining = 1
|
||||
$fault.LeavePartialFile = $true
|
||||
$fault.FailRestore = $true
|
||||
$failure = Get-ReplaceFailure $restoreFailureTarget $fault
|
||||
Assert-True ($failure -is [AggregateException]) 'failed restore reports installation and restoration failures'
|
||||
Assert-True ([IO.File]::ReadAllText($restoreFailureTarget + '.bak') -eq 'old version') 'failed restore retains backup for manual recovery'
|
||||
Assert-True ([IO.File]::ReadAllText($download) -eq 'new version') 'failed restore retains source download'
|
||||
|
||||
$retryTarget = Join-Path $testRoot 'retry.exe'
|
||||
[IO.File]::WriteAllText($retryTarget, 'old version')
|
||||
$fault = New-FaultOperations $retryTarget
|
||||
$fault.CopyFailuresRemaining = 1
|
||||
$fault.LeavePartialFile = $true
|
||||
$fault.RetryTimeoutMilliseconds = 1000
|
||||
Replace-File 0 $retryTarget $download 30000 $fault
|
||||
Assert-True ([IO.File]::ReadAllText($retryTarget) -eq 'new version') 'temporary copy failure retries successfully'
|
||||
|
||||
$newFailedTarget = Join-Path $testRoot 'failed-first-install.exe'
|
||||
$fault = New-FaultOperations $newFailedTarget
|
||||
$fault.CopyFailuresRemaining = 1
|
||||
$fault.LeavePartialFile = $true
|
||||
$failure = Get-ReplaceFailure $newFailedTarget $fault
|
||||
Assert-True (-not [IO.File]::Exists($newFailedTarget)) 'failed first install removes partial target'
|
||||
|
||||
$cleanupTarget = Join-Path $testRoot 'cleanup.exe'
|
||||
[IO.File]::WriteAllText($cleanupTarget, 'old version')
|
||||
$fault = New-FaultOperations $cleanupTarget
|
||||
$fault.FailCleanup = $true
|
||||
Replace-File 0 $cleanupTarget $download 30000 $fault
|
||||
Assert-True ([IO.File]::ReadAllText($cleanupTarget) -eq 'new version') 'cleanup failure does not report a successful installation as failed'
|
||||
|
||||
if ($LauncherPath) {
|
||||
$LauncherPath = (Resolve-Path $LauncherPath).Path
|
||||
$liveTarget = Join-Path $testRoot 'RunningLauncher.exe'
|
||||
@@ -76,6 +149,25 @@ if ($LauncherPath) {
|
||||
Assert-True ($helper.ExitCode -eq 5) 'real launcher update helper exits successfully'
|
||||
Assert-True ((Get-FileHash $liveTarget).Hash -eq (Get-FileHash $LauncherPath).Hash) 'real helper replaces running old launcher after it exits'
|
||||
Assert-True ((Get-FileHash ($liveTarget + '.bak')).Hash -eq (Get-FileHash $oldExe).Hash) 'real helper preserves previous launcher'
|
||||
$resultPath = $updateType.GetMethod('GetLauncherUpdateResultPath').Invoke($null, @([string]$liveTarget))
|
||||
$receipt = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json
|
||||
Assert-True ($receipt.Succeeded -and $receipt.HelperProcessId -eq $helper.Id -and $receipt.TargetPath -eq $liveTarget) 'real helper saves a successful update receipt for the next startup'
|
||||
|
||||
$lockedTarget = Join-Path $testRoot 'locked-target.exe'
|
||||
Copy-Item -LiteralPath $oldExe -Destination $lockedTarget
|
||||
$originalHash = (Get-FileHash $lockedTarget).Hash
|
||||
$lockStream = [IO.File]::Open($lockedTarget, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
|
||||
try {
|
||||
$arguments = '--update 0 "{0}" "{1}" false' -f $lockedTarget, $LauncherPath
|
||||
$helper = Start-Process -FilePath $LauncherPath -ArgumentList $arguments -WorkingDirectory $testRoot -WindowStyle Hidden -PassThru
|
||||
if (-not $helper.WaitForExit(20000)) { throw 'Failed update helper did not finish within 20 seconds' }
|
||||
$helper.Refresh()
|
||||
Assert-True ($helper.ExitCode -ne 5) 'real helper reports file replacement failure without a modal dialog'
|
||||
} finally { $lockStream.Dispose() }
|
||||
Assert-True ((Get-FileHash $lockedTarget).Hash -eq $originalHash) 'real helper failure leaves old executable intact'
|
||||
$resultPath = $updateType.GetMethod('GetLauncherUpdateResultPath').Invoke($null, @([string]$lockedTarget))
|
||||
$receipt = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json
|
||||
Assert-True (-not $receipt.Succeeded -and -not [string]::IsNullOrWhiteSpace($receipt.ErrorMessage)) 'real helper saves an error receipt for the next startup'
|
||||
}
|
||||
|
||||
Write-Host "$($testState.Passed) checks passed. Artifacts: $testRoot"
|
||||
Reference in new issue
Block a user