using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using Newtonsoft.Json.Linq;
namespace AlicizaX.PackageManager.Editor
{
///
/// 更新包帮助类
///
internal static class UpdateAllPackageHelper
{
private static AddRequest _addRequest;
private static readonly Queue PackagesToUpdate = new Queue();
private static int _allPackagesCount = 0;
private static int _updatingPackagesIndex = 0;
public static void UpdatePackages()
{
var result = EditorUtility.DisplayDialog("更新包提示", "是否更新所有包?\n 更新完成之后可能需要重启Unity", "是", "否");
if (result)
{
UpdatePackagesFromManifest(FrameworkPackageManagerWindow.Instance.RepositoryPackageDatas);
}
}
///
/// 更新指定包
///
/// 包名
/// 包地址
public static void UpdatePackages(RepositoryPackageData repositoryPackageData)
{
PackagesToUpdate.Enqueue(repositoryPackageData);
}
private static void UpdatePackagesFromManifest(List RepositoryPackageDatas)
{
foreach (var package in RepositoryPackageDatas)
{
string packageUrl = package.cloneUrl;
if (packageUrl.EndsWith(".git") && package.PackageState == PackageState.Update)
{
UpdatePackages(package);
}
}
StartUpdate();
}
///
/// 开始更新
///
public static void StartUpdate()
{
_allPackagesCount = PackagesToUpdate.Count;
_updatingPackagesIndex = 0;
if (PackagesToUpdate.Count > 0)
{
UpdateNextPackage();
}
else
{
UnityEngine.Debug.Log("No packages to update.");
}
}
private static void UpdateNextPackage()
{
if (PackagesToUpdate.Count > 0)
{
_updatingPackagesIndex++;
var repositoryPackageData = PackagesToUpdate.Dequeue();
_addRequest = Client.Add(repositoryPackageData.cloneUrl);
EditorApplication.update += UpdatingProgressHandler;
var isCancelableProgressBar = EditorUtility.DisplayCancelableProgressBar("正在更新包", $"{_updatingPackagesIndex}/{_allPackagesCount} ({repositoryPackageData.name})", (float)_updatingPackagesIndex / _allPackagesCount);
if (isCancelableProgressBar)
{
EditorUtility.DisplayProgressBar("正在取消更新", "请等待...", 0.5f);
PackagesToUpdate.Clear();
EditorUtility.ClearProgressBar();
EditorApplication.update -= UpdatingProgressHandler;
AssetDatabase.Refresh();
}
}
else
{
EditorUtility.ClearProgressBar();
UnityEngine.Debug.Log("All packages updated.");
AssetDatabase.Refresh();
}
}
private static void UpdatingProgressHandler()
{
if (_addRequest.IsCompleted)
{
if (_addRequest.Status == StatusCode.Success)
{
FrameworkPackageManagerWindow.Instance.RefreshPackage(_addRequest.Result.name);
UnityEngine.Debug.Log($"Updated package: {_addRequest.Result.name}");
}
else if (_addRequest.Status >= StatusCode.Failure)
{
UnityEngine.Debug.LogError($"Failed to update package: {_addRequest.Error.message}");
}
EditorApplication.update -= UpdatingProgressHandler;
UpdateNextPackage();
}
}
}
}