using System;
using System.Linq;
using System.Threading.Tasks;
using AI.AgentIntegration;
using DevExpress.XtraBars.Docking2010.Views.Tabbed;
namespace PcgDrawR.Services
{
///
/// 负责文件和标签页相关的具体操作。
///
public class FileTabService
{
private readonly IAppEnvironment env;
public FileTabService(IAppEnvironment env)
{
this.env = env ?? throw new ArgumentNullException(nameof(env));
}
public Task SaveFileAsync(AppAction action)
{
var edit = env.ActiveUCDrawEdit;
if (edit == null)
{
return Task.FromResult(Fail("当前没有打开任何图件"));
}
bool result = env.MainForm.Invoke(() => edit.SaveFile());
if (result)
{
env.State.File.HasUnsavedChanges = false;
return Task.FromResult(Success());
}
return Task.FromResult(Fail("保存失败"));
}
public Task CloseAllFilesAsync(AppAction action)
{
env.MainForm.Invoke(() =>
{
foreach (Document doc in env.MainForm.TabbedView1.Documents.Cast().ToList())
{
env.MainForm.TabbedView1.Controller.Close(doc);
}
});
env.State.File.HasUnsavedChanges = false;
env.State.File.ActiveFilePath = string.Empty;
return Task.FromResult(Success());
}
public Task CloseFileAsync(AppAction action)
{
env.MainForm.Invoke(() =>
{
var doc = env.MainForm.TabbedView1?.ActiveDocument;
if (doc != null)
{
env.MainForm.TabbedView1.Controller.Close(doc);
}
});
env.State.File.HasUnsavedChanges = false;
env.State.File.ActiveFilePath = string.Empty;
return Task.FromResult(Success());
}
public Task SaveAllAsync(AppAction action)
{
env.MainForm.Invoke(() => env.MainForm.SaveAll());
return Task.FromResult(Success());
}
public AppActionResult OpenFile(AppAction action)
{
if (!action.Parameters.TryGetValue("path", out var pathObj))
{
return Fail("缺少 'path' 参数");
}
var path = pathObj.ToString();
bool result = env.MainForm.Invoke(() => env.MainForm.OpenFile(path));
if (!result)
{
return Fail("打开图件失败");
}
env.State.File.ActiveFilePath = path;
env.State.File.FileType = System.IO.Path.GetExtension(path).TrimStart('.');
env.State.File.HasUnsavedChanges = false;
return Success();
}
public AppActionResult ReloadFile(AppAction action)
{
env.MainForm.Invoke(() => env.MainForm.ReloadFile());
return Success();
}
public Task RenameFileAsync(AppAction action)
{
if (!action.Parameters.TryGetValue("newName", out var nameObj))
{
return Task.FromResult(Fail("缺少 'newName' 参数"));
}
string newName = nameObj.ToString();
env.State.File.ActiveFilePath = newName;
return Task.FromResult(Success($"已重命名为 {newName}"));
}
private AppActionResult Success(object data = null)
{
return new AppActionResult { Success = true, Data = data };
}
private AppActionResult Fail(string message)
{
return new AppActionResult { Success = false, Message = message };
}
}
}