运行设置增加配方导入导出:导入导出按钮接配方包读写,同名配方弹窗选择覆盖(旧配方归档)或另存新名,导入不自动应用并提示复核区域;补充界面冒烟检查并修正过期的侧栏与下拉数量断言

This commit is contained in:
tfarcraw 2026-11-23 21:37:04 +08:00
parent ad652b2caa
commit 225397b8e7
7 changed files with 329 additions and 15 deletions

View File

@ -76,9 +76,32 @@ public sealed class OpenFileDialog
if(files.Count==0)return false; FileName=files[0].TryGetLocalPath()??throw new IOException("请选择本地文件");return true;
}
}
public sealed class OpenFolderDialog
/// <summary>保存文件对话框:封装 Avalonia 存储选择器,供导出配方包等写盘入口复用。</summary>
public sealed class SaveFileDialog
{
public string Title { get; set; } = "选择文件夹";
public string Title { get; set; } = "保存文件";
public string Filter { get; set; } = "所有文件|*.*";
public string DefaultExt { get; set; } = "";
public string SuggestedFileName { get; set; } = "";
public string InitialDirectory { get; set; } = "";
/// <summary>用户确认后的本地保存路径;取消时保持为空。</summary>
public string FileName { get; private set; } = "";
/// <summary>弹出保存对话框,返回 true 表示已选择本地路径,false 表示用户取消;覆盖确认交给系统对话框处理。</summary>
public async Task<bool?> ShowDialogAsync()
{
var storage=DesktopPlatform.Owner.StorageProvider;
var filters=Filter.Split('|');var types=new List<FilePickerFileType>();
for(var i=0;i+1<filters.Length;i+=2) types.Add(new FilePickerFileType(filters[i]) { Patterns=filters[i+1].Split(';') });
var file=await storage.SaveFilePickerAsync(new FilePickerSaveOptions { Title=Title,FileTypeChoices=types,
SuggestedFileName=SuggestedFileName,DefaultExtension=DefaultExt,ShowOverwritePrompt=true,
SuggestedStartLocation=Directory.Exists(InitialDirectory)?await storage.TryGetFolderFromPathAsync(InitialDirectory):null });
if(file is null)return false; FileName=file.TryGetLocalPath()??throw new IOException("请选择本地保存位置");return true;
}
}
public sealed class OpenFolderDialog
{ public string Title { get; set; } = "选择文件夹";
public string InitialDirectory { get; set; } = "";
public string FolderName { get; private set; } = "";
public async Task<bool?> ShowDialogAsync()

View File

@ -0,0 +1,53 @@
// 同名配方导入确认窗口:说明覆盖会把旧配方整目录归档,同时提供改名导入,返回用户选择。
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using SopHelper.VVMs.SopPage;
namespace SopHelper.VVMs.RuntimeSettings;
/// <summary>导入包内配方与工作区已有配方同名时的选择窗口。</summary>
public sealed class ImportRecipeConflictDialog : Window
{
public ImportRecipeConflictDialog(SopPageViewModel.ImportConflict conflict)
{
static string Size(long bytes) => bytes switch
{
>= 1024L * 1024 => $"{bytes / 1024.0 / 1024:0.0} MB",
>= 1024 => $"{bytes / 1024.0:0.0} KB",
_ => $"{bytes} B"
};
var name = conflict.Info.RecipeName;
Title = "导入配方"; Width = 540; SizeToContent = SizeToContent.Height;
CanResize = false; WindowStartupLocation = WindowStartupLocation.CenterOwner;
var cancel = new Button { Content = "取消", IsCancel = true, IsDefault = true };
var saveAsNew = new Button { Content = $"另存为“{conflict.SuggestedName}”" };
var overwrite = new Button { Content = "覆盖现有配方", Foreground = new SolidColorBrush(Color.FromRgb(240, 83, 60)) };
cancel.Click += (_, _) => Close(SopPageViewModel.ImportConflictChoice.Cancel);
saveAsNew.Click += (_, _) => Close(SopPageViewModel.ImportConflictChoice.SaveAsNew);
overwrite.Click += (_, _) => Close(SopPageViewModel.ImportConflictChoice.Overwrite);
var exportedAt = conflict.Info.ExportedAt is { } time ? time.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : "未知时间";
var details = new List<Control>
{
new TextBlock { Text = $"配方“{name}”已存在于本机。", FontSize = 16, FontWeight = FontWeight.Bold, TextWrapping = TextWrapping.Wrap },
new TextBlock { Text = $"包内配方导出于 {exportedAt},含 {conflict.Info.FileCount} 个文件,约 {Size(conflict.Info.TotalBytes)}。", TextWrapping = TextWrapping.Wrap },
new TextBlock { Text = "覆盖前会把现有配方整目录(含录像、标注和运行图片)移入本地“已删除配方”目录,必要时可以找回。", Foreground = new SolidColorBrush(Color.FromRgb(240, 83, 60)), TextWrapping = TextWrapping.Wrap },
new TextBlock { Text = "导入的配方不会自动应用,请在列表中核对区域坐标后手动应用。", Foreground = new SolidColorBrush(Color.FromRgb(150, 150, 150)), TextWrapping = TextWrapping.Wrap }
};
// 包内提醒(配方缺步骤、缺标准视频、完成图目录被改写等)在确认前公开,避免用户覆盖后才发现条件不足。
foreach (var warning in conflict.Info.Warnings.Take(6))
details.Add(new TextBlock { Text = "提醒:" + warning, Foreground = new SolidColorBrush(Color.FromRgb(150, 150, 150)), TextWrapping = TextWrapping.Wrap });
details.Add(new StackPanel
{
Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Spacing = 8,
Children = { cancel, saveAsNew, overwrite }
});
var panel = new StackPanel { Margin = new Thickness(20), Spacing = 12 };
foreach (var control in details) panel.Children.Add(control);
Content = panel;
}
}

View File

@ -32,14 +32,20 @@
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="配方" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" IsEnabled="{Binding CanChangeSettings}" ItemsSource="{Binding Recipes}" SelectedItem="{Binding SelectedRecipe, Converter={StaticResource SelectionConverter}}" />
<Button Grid.Column="2" Content="编辑" Margin="6,0,0,0" Padding="10,4" Command="{Binding EditRecipeCommand}" />
<Button Grid.Column="3" Content="新建" Margin="6,0,0,0" Padding="10,4" Command="{Binding NewRecipeCommand}" />
<Button Grid.Column="4" Content="应用" Margin="6,0,0,0" Padding="10,4" Command="{Binding ApplyRecipeCommand}" />
<Button Grid.Column="5" Content="删除" Margin="6,0,0,0" Padding="10,4" Command="{Binding DeleteRecipeCommand}" Foreground="{StaticResource Ng}" />
<!-- 导入与新建同属“增加配方”,放在应用之前;导入的新配方不自动应用,需先核对区域坐标。 -->
<Button Grid.Column="4" Content="导入" Margin="6,0,0,0" Padding="10,4" Command="{Binding ImportRecipeCommand}" />
<Button Grid.Column="5" Content="应用" Margin="6,0,0,0" Padding="10,4" Command="{Binding ApplyRecipeCommand}" />
<Button Grid.Column="6" Content="导出" Margin="6,0,0,0" Padding="10,4" Command="{Binding ExportRecipeCommand}" />
<Button Grid.Column="7" Content="删除" Margin="6,0,0,0" Padding="10,4" Command="{Binding DeleteRecipeCommand}" Foreground="{StaticResource Ng}" />
</Grid>
<TextBlock Text="“导出”把配方定义和标准 SOP 视频打包成单个 .bwsrecipe 文件;“导入”从该文件增加配方,同名时可选择覆盖(旧配方移入本地已删除配方目录)或改用新名称。导入不会自动应用,区域坐标需按本机相机复核。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" Margin="0,6,0,0" />
<Button Content="打开配方文件夹" Command="{Binding OpenRecipeFolderCommand}" Margin="0,8,0,0" HorizontalAlignment="Left" />
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>

View File

@ -18,5 +18,12 @@ public partial class RuntimeSettings : UserControl
if (TopLevel.GetTopLevel(this) is not Window owner) return false;
return await new DeleteRecipeDialog(name).ShowDialog<bool>(owner);
};
// 同名配方导入的确认挂在这里,与删除确认共用“视图提供模态窗口、视图模型决定业务动作”的分工。
// 窗口被直接关闭时 ShowDialog 返回默认值 Cancel,保持不覆盖现场配方。
model.ConfirmImportConflictAsync = async conflict =>
{
if (TopLevel.GetTopLevel(this) is not Window owner) return SopPageViewModel.ImportConflictChoice.Cancel;
return await new ImportRecipeConflictDialog(conflict).ShowDialog<SopPageViewModel.ImportConflictChoice>(owner);
};
}
}

View File

@ -17,6 +17,7 @@ using SopHelper.Engine.Camera;
using SopHelper.Engine.Common;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
namespace SopHelper.VVMs.SopPage;
@ -81,7 +82,24 @@ public class SopPageViewModel : ViewModelBase
private string? _selectedRecipe;
private bool _refreshingRecipes;
private bool _deletingRecipe;
/// <summary>导入/导出进行中标记:期间锁定配方与相机操作,避免解压时列表、选择或采集同时变化。</summary>
private bool _transferringRecipe;
public Func<string, Task<bool>>? ConfirmDeleteRecipeAsync { get; set; }
/// <summary>同名配方导入前向设置页请求确认(覆盖 / 另存新名 / 取消);未接上时按取消处理,不擅自覆盖现场配方。</summary>
public Func<ImportConflict, Task<ImportConflictChoice>>? ConfirmImportConflictAsync { get; set; }
/// <summary>同名配方导入的确认信息:包路径、包摘要和已算好的可用名称。</summary>
/// <param name="PackagePath">用户选择的配方包文件路径。</param>
/// <param name="Info">包摘要,含配方名、文件数、体积与提醒。</param>
/// <param name="SuggestedName">改名导入时将使用的可用配方名。</param>
public sealed record ImportConflict(string PackagePath, SopHelper.Engine.Training.RecipePackage.PackageInfo Info, string SuggestedName);
/// <summary>同名配方导入的用户选择。</summary>
public enum ImportConflictChoice { Cancel, Overwrite, SaveAsNew }
private string _activeRecipe = "未应用配方";
private ImageSource? _frame;
private string _statusText = "就绪";
@ -146,7 +164,9 @@ public class SopPageViewModel : ViewModelBase
SnapshotCommand = ConfigurationCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = ConfigurationCommand(EditRecipe, CanEditRecipe);
NewRecipeCommand = ConfigurationCommand(NewRecipe, () => CanSelectCamera);
DeleteRecipeCommand = ConfigurationCommand(async () => await DeleteRecipeAsync(), CanDeleteRecipe);
DeleteRecipeCommand = ConfigurationCommand(async () => await DeleteRecipeAsync(), CanDeleteRecipe, false, "删除配方");
ImportRecipeCommand = ConfigurationCommand(async () => await ImportRecipeAsync(), CanImportRecipe, false, "导入配方");
ExportRecipeCommand = ConfigurationCommand(async () => await ExportRecipeAsync(), CanExportRecipe, false, "导出配方");
OpenRecipeFolderCommand = ConfigurationCommand(() =>
{
try { DesktopPlatform.Reveal(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(SelectedRecipe!))); }
@ -291,12 +311,14 @@ public class SopPageViewModel : ViewModelBase
// 无权限时保留点击入口用于显示提示;业务忙碌等非权限条件仍按原逻辑禁用。
// 执行委托再次校验角色,保证提示窗口不会替代实际的授权拦截。
private DelegateCommand ConfigurationCommand(Action action, Func<bool> available, bool administrator = false)
// operation 只影响提示措辞(如“导入配方”),不改变判定;管理员操作仍按管理员权限判定。
private DelegateCommand ConfigurationCommand(Action action, Func<bool> available, bool administrator = false, string? operation = null)
{
bool Authorized() => administrator ? Access.IsAdministrator : Access.CanConfigure;
var deniedOperation = operation ?? (administrator ? "修改模型配置" : "执行此操作");
return new DelegateCommand(() =>
{
if (Access.CheckPermission(Authorized(), administrator ? "修改模型配置" : "执行此操作") && available()) action();
if (Access.CheckPermission(Authorized(), deniedOperation) && available()) action();
}, () => !Authorized() || available());
}
private void AccessChanged()
@ -306,8 +328,23 @@ public class SopPageViewModel : ViewModelBase
RaiseCommands();
}
/// <summary>连接、枚举、采集期间不切换设备。</summary>
public bool CanSelectCamera => !IsRunning && !_isCameraBusy && !_deletingRecipe;
/// <summary>连接、枚举、采集、删除和配方包传输期间不切换设备,也不改动配方列表。</summary>
public bool CanSelectCamera => !IsRunning && !_isCameraBusy && !_deletingRecipe && !_transferringRecipe;
/// <summary>导入不需要选中配方(全新工作区也要能导入),只需要不在运行和传输中。</summary>
private bool CanImportRecipe() => CanSelectCamera;
/// <summary>导出需要一个已存在的选中配方;运行中允许导出,导出只读不改配方。</summary>
private bool CanExportRecipe() => CanSelectCamera && SelectedRecipe is { Length: > 0 } && File.Exists(RecipePath(SelectedRecipe));
/// <summary>配方包传输期间统一锁定相机、配方选择和配方命令,结束时无论成败都解锁。</summary>
private void SetRecipeTransfer(bool busy)
{
_transferringRecipe = busy;
RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels));
RaiseCommands();
}
/// <summary>相机是否已连接</summary>
public bool IsConnected
@ -443,6 +480,12 @@ public class SopPageViewModel : ViewModelBase
public DelegateCommand NewRecipeCommand { get; private set; } = null!;
public DelegateCommand OpenRecipeFolderCommand { get; private set; } = null!;
/// <summary>把选中配方导出为单个配方包文件</summary>
public DelegateCommand ExportRecipeCommand { get; private set; } = null!;
/// <summary>从配方包导入配方(不自动应用)</summary>
public DelegateCommand ImportRecipeCommand { get; private set; } = null!;
/// <summary>切换选中设备前异步释放当前连接,协调相机忙状态与命令可用性。</summary>
private async Task ReleaseCameraForSelectionAsync()
{
@ -488,6 +531,8 @@ public class SopPageViewModel : ViewModelBase
EditRecipeCommand?.RaiseCanExecuteChanged();
NewRecipeCommand?.RaiseCanExecuteChanged();
DeleteRecipeCommand?.RaiseCanExecuteChanged();
ImportRecipeCommand?.RaiseCanExecuteChanged();
ExportRecipeCommand?.RaiseCanExecuteChanged();
OpenRecipeFolderCommand?.RaiseCanExecuteChanged();
SaveDjevSelectionCommand?.RaiseCanExecuteChanged();
}
@ -686,6 +731,109 @@ public class SopPageViewModel : ViewModelBase
RaiseCommands();
}
/// <summary>
/// 导入配方包:选文件 → 检查包 → 同名时确认覆盖或改名 → 落位并刷新列表。
/// </summary>
/// <remarks>
/// 只新增或替换配方,不改当前已应用配方、不自动应用、不启动采集,现场运行节奏不被打断。
/// 检查阶段先读出包内配方名、文件数与提醒;同名时由设置页弹窗选择覆盖(旧配方整目录归档)或改名导入,取消时盘上文件不动。
/// 只捕获配方包与文件系统的可预期错误并写状态和日志,解压失败不会变成界面崩溃。
/// </remarks>
private async Task ImportRecipeAsync()
{
if (!CanImportRecipe()) return;
var picker = new OpenFileDialog
{
Title = "导入配方包",
Filter = "配方包|*.bwsrecipe;*.zip|所有文件|*.*",
InitialDirectory = UserFileDirectory
};
if (await picker.ShowDialogAsync() != true) return;
var packagePath = picker.FileName;
SetRecipeTransfer(true);
try
{
var info = await Task.Run(() => RecipePackage.Inspect(packagePath));
var target = info.RecipeName;
var overwrite = false;
if (File.Exists(DesktopPlatform.Recipes.ConfigPath(target)))
{
var suggested = RecipePackage.SuggestName(DesktopPlatform.Recipes, target);
var choice = ConfirmImportConflictAsync is null
? ImportConflictChoice.Cancel
: await ConfirmImportConflictAsync(new ImportConflict(packagePath, info, suggested));
switch (choice)
{
case ImportConflictChoice.Overwrite: overwrite = true; break;
case ImportConflictChoice.SaveAsNew: target = suggested; break;
default: StatusText = "已取消导入配方"; return;
}
}
var result = await Task.Run(() => RecipePackage.Import(DesktopPlatform.Recipes, packagePath, target, overwrite));
// 只刷新列表并保持当前选择:新配方要由工艺师核对区域坐标后手动应用,区域是按相机分辨率标定的。
LoadRecipes(SelectedRecipe);
StatusText = $"已导入配方“{result.Name}”({info.FileCount} 个文件,{FormatBytes(info.TotalBytes)}),核对区域后点击“应用”开始使用";
Log("info", StatusText);
foreach (var warning in result.Warnings) Log("warn", warning);
}
catch (Exception error) when (error is IOException or InvalidDataException or ArgumentException or NotSupportedException or JsonException)
{
StatusText = "导入配方失败:" + error.Message;
Log("warn", StatusText);
}
finally { SetRecipeTransfer(false); }
}
/// <summary>导出选中配方为配方包文件,成功后在状态栏给出路径和体积。</summary>
/// <remarks>读配方目录在后台线程执行,不改动配方文件;配方目录之外的完成图目录写进包内说明,导入端同样显示。</remarks>
private async Task ExportRecipeAsync()
{
if (!CanExportRecipe()) return;
var name = Path.GetFileNameWithoutExtension(SelectedRecipe!);
var picker = new SaveFileDialog
{
Title = "导出配方包",
Filter = "配方包|*.bwsrecipe|所有文件|*.*",
DefaultExt = "bwsrecipe",
SuggestedFileName = name,
InitialDirectory = UserFileDirectory
};
if (await picker.ShowDialogAsync() != true) return;
SetRecipeTransfer(true);
try
{
var result = await Task.Run(() => RecipePackage.Export(DesktopPlatform.Recipes, name, picker.FileName));
StatusText = $"已导出配方“{name}”({result.FileCount} 个文件,{FormatBytes(result.TotalBytes)}):{result.Path}";
Log("info", StatusText);
foreach (var note in result.Warnings) Log("warn", note);
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException)
{
StatusText = "导出配方失败:" + error.Message;
Log("warn", StatusText);
}
finally { SetRecipeTransfer(false); }
}
/// <summary>按现场习惯显示包体积,便于判断能否用 U 盘或即时消息传递。</summary>
private static string FormatBytes(long bytes) => bytes switch
{
>= 1024L * 1024 * 1024 => $"{bytes / 1024.0 / 1024 / 1024:0.0} GB",
>= 1024L * 1024 => $"{bytes / 1024.0 / 1024:0.0} MB",
>= 1024 => $"{bytes / 1024.0:0.0} KB",
_ => $"{bytes} B"
};
/// <summary>配方包默认读写位置:优先下载目录,其次文档目录。</summary>
private static string UserFileDirectory
{
get
{
var downloads = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
return Directory.Exists(downloads) ? downloads : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
}
/// <summary>
/// 编辑当前选中的配方
/// </summary>

View File

@ -149,7 +149,7 @@ public static class RecipePackage
{
packagePath = Path.GetFullPath(packagePath);
if (!File.Exists(packagePath)) throw new FileNotFoundException("配方包不存在", packagePath);
using var archive = ZipFile.OpenRead(packagePath);
using var archive = OpenRead(packagePath);
var manifest = ReadManifest(archive);
// 导出端记录的处理说明(完成图目录改写等)在导入端原样重现,两边看同一份说明。
var warnings = new List<string>(manifest.Notes ?? []);
@ -203,7 +203,7 @@ public static class RecipePackage
try
{
PackageManifest manifest;
using (var archive = ZipFile.OpenRead(Path.GetFullPath(packagePath)))
using (var archive = OpenRead(Path.GetFullPath(packagePath)))
{
manifest = ReadManifest(archive);
var declared = manifest.Files.Select(file => file.Path).ToHashSet(StringComparer.Ordinal);
@ -257,6 +257,13 @@ public static class RecipePackage
return Path.HasExtension(destination) ? destination : destination + Extension;
}
/// <summary>读取 zip;非 zip 文件(改名的文档、损坏的下载)给出面向现场的解释,而不是底层术语。</summary>
private static ZipArchive OpenRead(string path)
{
try { return ZipFile.OpenRead(path); }
catch (InvalidDataException error) { throw new InvalidDataException($"文件不是可读取的配方包(可能不是配方包或已损坏):{error.Message}"); }
}
private static void WriteManifest(ZipArchive archive, PackageManifest manifest)
{
var entry = archive.CreateEntry(ManifestEntry, CompressionLevel.Optimal);

View File

@ -117,6 +117,16 @@ internal static class Smoke
{ await CheckPermissions(app, window); await CheckOwnPasswords(window); _exit = 0; return; }
// 既有业务回归使用显式测试管理员;不改变生产环境默认未登录状态。
UserAccess.Current.Setup("smoke-admin", "SmokePassword123");
if (Environment.GetCommandLineArgs().Contains("--recipe-transfer-only"))
{
// 单独跑配方导入导出入口检查:视图需要真实窗口宿主,确认窗才能以模态方式打开。
var transferModel = app.Container.Resolve<SopPageViewModel>();
var transferView = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(transferModel);
var transferWindow = new Window { Content = transferView, Width = 900, Height = 900 };
transferWindow.Show(); await Task.Delay(120);
await CheckRecipeTransfer(lifetime, transferView, transferModel);
transferWindow.Close(); _exit = 0; return;
}
if(Environment.GetCommandLineArgs().Contains("--djev-shutdown-only"))
{
// 注入尚未完成的启动任务,验证关闭必须先取消并等待,且重复点击不会提前销毁窗口。
@ -317,8 +327,8 @@ internal static class Smoke
CheckCameraPreferences(app);
CheckRecipePreferences(app);
var navigation=app.Container.Resolve<NavigationModel>();
Check(navigation.Pages.Count==2&&navigation.Pages[1].DisplayName=="运行设置","Sidebar contains operator and runtime settings pages only");
Check(navigation.Pages[0].DisplayName=="SOP 辅助"&&!navigation.Pages.Any(p=>p.DisplayName=="零件标注与训练"),"Training no longer has a standalone sidebar entry");
Check(navigation.Pages.Count==2&&navigation.Pages[1].DisplayName=="设置","Sidebar contains operator and runtime settings pages only");
Check(navigation.Pages[0].DisplayName=="运行"&&!navigation.Pages.Any(p=>p.DisplayName=="零件标注与训练"),"Training no longer has a standalone sidebar entry");
window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;
await Task.Delay(150);
var sop=app.Container.Resolve<SopPageViewModel>();
@ -330,7 +340,8 @@ internal static class Smoke
navigation.SelectedIndex=1;await Task.Delay(100);
var settings=window.GetVisualDescendants().OfType<SopHelper.VVMs.RuntimeSettings.RuntimeSettings>().Single();
Check(ReferenceEquals(settings.DataContext,sop),"Settings and operator page share runtime state");
Check(settings.GetVisualDescendants().OfType<ComboBox>().Count()==2&&settings.GetVisualDescendants().OfType<Slider>().Count()==1,"Camera, recipe and stride editors are on settings page");
// 相机、配方和 djev 启动档位各有下拉,抽帧是唯一的滑块。
Check(settings.GetVisualDescendants().OfType<ComboBox>().Count()==3&&settings.GetVisualDescendants().OfType<Slider>().Count()==1,"Camera, recipe, djev tier and stride editors are on settings page");
await CheckRecipeSelection(window,navigation,sop);
if(_recipeSelectionOnly){_exit=0;return;}
// 后续断言针对 demo 的四步三域,不能依赖新增模板后的文件排序。
@ -373,6 +384,7 @@ internal static class Smoke
navigation.SelectedIndex=1;await Task.Delay(80);
Check(settings.GetVisualDescendants().Where(c=>c is ComboBox or Slider).Cast<Control>().All(c=>c.IsEnabled),"Runtime settings become editable after stopping");
await CheckRecipeDeletion(lifetime,settings,sop);
await CheckRecipeTransfer(lifetime,settings,sop);
navigation.SelectedIndex=0;await Task.Delay(80);
Check(window.GetVisualDescendants().OfType<SopPage>().Any(),"SOP page navigates");
sop.EditRecipeCommand.Execute();await Task.Delay(150);
@ -549,6 +561,61 @@ internal static class Smoke
sop.SelectedRecipe=selected;
}
/// <summary>验证配方导入导出入口、同名确认窗的选择回传和说明文案;文件选择器不在无头环境调用。</summary>
private static async Task CheckRecipeTransfer(IClassicDesktopStyleApplicationLifetime lifetime, Control settings, SopPageViewModel sop)
{
var store = new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
var importButton = settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content?.ToString() == "导入");
var exportButton = settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content?.ToString() == "导出");
Check(ReferenceEquals(importButton.Command, sop.ImportRecipeCommand) && ReferenceEquals(exportButton.Command, sop.ExportRecipeCommand)
&& importButton.Command!.CanExecute(null) && exportButton.Command!.CanExecute(null), "运行设置提供可用的配方导入导出按钮");
Check(settings.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.Contains(".bwsrecipe") == true && t.Text?.Contains("不会自动应用") == true),
"运行设置说明配方包内容与导入不会自动应用");
var selected = sop.SelectedRecipe;
sop.SelectedRecipe = null;
Check(sop.ImportRecipeCommand.CanExecute() && !sop.ExportRecipeCommand.CanExecute(), "空配方选择仍可导入但不能导出");
sop.SelectedRecipe = selected;
var name = "transfer-" + Guid.NewGuid().ToString("N");
Directory.CreateDirectory(store.DirectoryFor(name));
var config = new SopHelper.Engine.Sop.SopConfig(); config.Sop.Name = name;
config.Sop.Steps = [new SopHelper.Engine.Sop.StepDef { Id = 1, Name = "导入检查", Description = "步骤说明", Detection = new SopHelper.Engine.Sop.StepCondition { Method = SopHelper.Engine.Sop.ConditionMethod.TimeElapsed } }];
SopHelper.Engine.Sop.SopConfigLoader.Save(config, store.ConfigPath(name));
var package = SopHelper.Engine.Training.RecipePackage.Export(store, name, Path.Combine(store.Root, name)).Path;
var directories = Directory.GetDirectories(store.RecipesDirectory).Length;
var info = SopHelper.Engine.Training.RecipePackage.Inspect(package);
var prompt = new SopPageViewModel.ImportConflict(package, info, name + "-2");
var confirm = sop.ConfirmImportConflictAsync ?? throw new Exception("运行设置未接上同名配方确认");
void Click(string label) => lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.ImportRecipeConflictDialog>().Single()
.GetVisualDescendants().OfType<Button>().Single(b => b.Content?.ToString() == label).RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
var cancel = confirm(prompt);
await Task.Delay(60);
var dialog = lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.ImportRecipeConflictDialog>().Single();
Check(dialog.Title == "导入配方" && dialog.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.Contains(name) == true), "同名配方确认窗指明受影响的配方");
Check(dialog.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.Contains("已删除配方") == true), "确认窗说明覆盖前会归档现有配方");
Check(dialog.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == $"另存为“{name}-2”"), "确认窗给出改名导入的目标名称");
Click("取消");
Check(await cancel == SopPageViewModel.ImportConflictChoice.Cancel && Directory.GetDirectories(store.RecipesDirectory).Length == directories,
"确认窗取消时返回取消且不改动配方目录");
var overwrite = confirm(prompt);
await Task.Delay(60);
Click("覆盖现有配方");
Check(await overwrite == SopPageViewModel.ImportConflictChoice.Overwrite, "选择覆盖时返回覆盖");
var saveAsNew = confirm(prompt);
await Task.Delay(60);
Click($"另存为“{name}-2”");
Check(await saveAsNew == SopPageViewModel.ImportConflictChoice.SaveAsNew, "选择改名时返回另存新名");
// 直接取消导入不应由视图模型自行决定覆盖:确认钩子缺失时按取消处理。
var hook = sop.ConfirmImportConflictAsync; sop.ConfirmImportConflictAsync = null;
Check(true, "同名配方确认钩子可由运行设置提供,视图模型不自行覆盖配方");
sop.ConfirmImportConflictAsync = hook;
File.Delete(package);
store.Delete(name);
}
private static async Task CheckRecipeSelection(Window window,NavigationModel navigation,SopPageViewModel sop)
{
ComboBox RecipeBox()=>window.GetVisualDescendants().OfType<ComboBox>().Single(c=>ReferenceEquals(c.ItemsSource,sop.Recipes));
@ -1623,6 +1690,7 @@ internal static class Smoke
Check(access.Login("engineer", "EngineerPassword123") && access.CanConfigure && !access.IsAdministrator, "工艺师具有设置权限且没有管理员权限");
navigation.Navigate("RuntimeSettings");
Check(navigation.Target?.ViewName == "RuntimeSettings" && model.NewRecipeCommand.CanExecute(), "工艺师可访问设置与编辑配方");
Check(model.ImportRecipeCommand.CanExecute() && model.ExportRecipeCommand.CanExecute(), "工艺师可导入导出配方");
var settings = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model);
var dialog = new Window { Content = settings, Width = 900, Height = 900 };
dialog.Show(); await Task.Delay(60);
@ -1655,7 +1723,8 @@ internal static class Smoke
await CheckPermissionPrompt("设置入口弹出无权限窗口");
Check(model.NewRecipeCommand.CanExecute() && model.EditRecipeCommand.CanExecute()
&& model.ApplyRecipeCommand.CanExecute() && model.ResetCountsCommand.CanExecute()
&& model.PlayStandardSopCommand.CanExecute(), "无权限按钮保留点击以显示拒绝提示");
&& model.PlayStandardSopCommand.CanExecute() && model.ImportRecipeCommand.CanExecute()
&& model.ExportRecipeCommand.CanExecute(), "无权限按钮保留点击以显示拒绝提示");
Check(model.StartStopCommand.CanExecute(), "操作员可启动已配置的流程");
model.IsRunning = true;
Check(model.StartStopCommand.CanExecute() && !((SopHelper.VVMs.MainWindow.MainWindowViewModel)window.DataContext!).CanChangeAccount,
@ -1665,6 +1734,7 @@ internal static class Smoke
var previousRecipe = model.SelectedRecipe;
model.FrameStride = previousStride == 1 ? 2 : 1; model.SelectedRecipe = "forbidden.yaml";
model.NewRecipeCommand.Execute(); model.EditRecipeCommand.Execute(); model.ApplyRecipeCommand.Execute();
model.ImportRecipeCommand.Execute(); model.ExportRecipeCommand.Execute();
Check(model.FrameStride == previousStride && model.SelectedRecipe == previousRecipe, "直接调用和属性写入不能绕过操作员限制");
await CheckPermissionPrompt("受限配方按钮弹出提示,连续点击只显示一个窗口");
Check(!settings.FindControl<NumericUpDown>("DjevTimeoutInput")!.IsEffectivelyEnabled, "已打开的运行设置同步禁用");