com.soviby.unity.ui.ugui-to.../Assets/Editor/Helper/CommandHelper.cs
2024-12-06 18:46:00 +08:00

92 lines
3.8 KiB
C#

#if UNITY_EDITOR
using UnityEngine;
using System.IO;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System;
namespace UguiToolkit.Editor
{
public static class CommandHelper
{
public static void CalcRotScale(string srcImgDirPath, string targetImgDirPath, float distanceDifference, Action<RotScaleJsonData> callback)
{
var rotScaleInfoFilePath = Path.GetFullPath(EditorConst.RotScaleInfoFilePath);
var rotScaleInfoToolFilePath = Path.GetFullPath(EditorConst.RotScaleInfoToolFilePath);
if (File.Exists(rotScaleInfoFilePath)) File.Delete(rotScaleInfoFilePath);
var cmd = string.Format("{0} -src {1} -target {2} -distance_difference {3} -output_path {4} -filter __background__.png",
rotScaleInfoToolFilePath,
Path.GetFullPath(srcImgDirPath),
Path.GetFullPath(targetImgDirPath),
distanceDifference,
Path.GetFullPath(rotScaleInfoFilePath));
Debug.Log("cmd: " + cmd);
_ = RunCmdAsync(cmd, (output, error) =>
{
Debug.Log(output);
if (!File.Exists(rotScaleInfoFilePath))
{
Debug.LogError($"[E] 文件{rotScaleInfoFilePath} 未能正确获得");
Debug.LogError(error);
return;
}
using (StreamReader reader = File.OpenText(rotScaleInfoFilePath))
{
var jsonData = reader.ReadToEnd();
RotScaleJsonData rotScaleJsonData = JsonConvert.DeserializeObject<RotScaleJsonData>(jsonData);
callback(rotScaleJsonData);
}
});
}
// 执行 cmd 命令
public static void RunCmd(in string cmd)
{
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + cmd; // 使用 /c 参数执行命令并关闭 cmd 窗口
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
p.StartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;
p.Start();
var output = p.StandardOutput.ReadToEnd();
var error = p.StandardError.ReadToEnd();
p.WaitForExit();
UnityEngine.Debug.Log("cmd output : " + output);
UnityEngine.Debug.Log("cmd error : " + error);
}
// 异步执行 cmd 命令
public static async Task RunCmdAsync(string cmd, Action<string, string> callback = null)
{
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + cmd; // 使用 /c 参数执行命令并关闭 cmd 窗口
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
p.StartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;
p.Start();
var output = await p.StandardOutput.ReadToEndAsync();
var error = await p.StandardError.ReadToEndAsync();
// 异步等待进程退出
await Task.Run(() => p.WaitForExit());
// 在主线程上调用回调函数
UnityMainThreadDispatcher.Instance().Enqueue(() => callback?.Invoke(output, error));
}
}
}
#endif