将 SOP 导出移至运行设置

This commit is contained in:
wanglei 2026-11-28 20:25:56 +08:00
parent b9c0702fb0
commit c0b9476baf
7 changed files with 61 additions and 48 deletions

View File

@ -98,12 +98,9 @@
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" Classes="Title" />
<TextBlock Text="配方名" Margin="16,0,8,0" Classes="Field" />
<TextBox x:Name="RecipeNameInput" Width="220" IsEnabled="{Binding Recipe.CanEditFileName}" Text="{Binding Recipe.Name, Mode=TwoWay}" ToolTip.Tip="文件名和目录名自动使用配方名;已有配方名称固定" />
<!-- SOP 导出作用于整个配方,放在配方名后以便各页签共用。 -->
<Button Content="导出SOP文件" Margin="8,0,0,0" VerticalAlignment="Center" IsEnabled="{Binding CanTransferSteps}" Click="ExportSopFile" ToolTip.Tip="将步骤和关键帧导出为 Excel 文件" />
<TextBox Width="220" IsEnabled="{Binding Recipe.CanEditFileName}" Text="{Binding Recipe.Name, Mode=TwoWay}" ToolTip.Tip="文件名和目录名自动使用配方名;已有配方名称固定" />
</StackPanel>
<TextBlock Text="{Binding NameValidationMessage}" Foreground="#F0533C" TextWrapping="Wrap" Margin="0,6,0,0" />
<TextBlock Text="{Binding StepTransferStatus}" IsVisible="{Binding StepTransferStatus, Converter={x:Static conv:StringConverters.IsNotNullOrEmpty}}" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
</StackPanel>
<TabControl Grid.Row="1">
<TabItem Header="步骤">
@ -120,6 +117,7 @@
<Button Content="导入步骤" Click="ImportStepsFile" ToolTip.Tip="从步骤文件或完整配方导入,可选择追加或替换" />
<Button Content="导出步骤" Click="ExportStepsFile" ToolTip.Tip="导出全部步骤及关联区域,保留触发、AI判定与复检设置" />
</WrapPanel>
<TextBlock Text="{Binding StepTransferStatus}" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
</StackPanel>
<!-- 增加按钮两侧留白,便于点击。 -->
<Button DockPanel.Dock="Bottom" Content="加步骤" Margin="0,8,0,0" Padding="12,6" Command="{Binding Recipe.AddStepCommand}" />

View File

@ -1,4 +1,4 @@
// 编辑器的步骤交换视图部分:处理步骤交换与 SOP 表格的文件选择、结果提示。
// 编辑器的步骤交换视图部分:处理步骤交换的文件选择和结果提示。
using Avalonia.Controls;
using Avalonia.Interactivity;
@ -67,35 +67,6 @@ public partial class RecipeEditor
}
}
/// <summary>选择 Excel 保存位置并导出当前编辑中的步骤,与步骤交换共用防重入门控。</summary>
private async void ExportSopFile(object? sender, RoutedEventArgs args)
{
if (_stepTransferInProgress || _model is not { CanTransferSteps: true } model || TopLevel.GetTopLevel(this) is not Window owner) return;
_stepTransferInProgress = true;
try
{
var name = string.Concat(model.Recipe.Name.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c));
var file = await owner.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = "导出SOP文件", SuggestedFileName = name + ".xlsx", DefaultExtension = "xlsx", ShowOverwritePrompt = true,
FileTypeChoices = [new("Excel 工作簿") { Patterns = ["*.xlsx"] }]
});
if (file is null || _closing || !ReferenceEquals(model, _model) || !model.CanTransferSteps) return;
var path = file.TryGetLocalPath() ?? throw new IOException("请选择本地保存位置");
if (!Path.GetExtension(path).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
throw new IOException("请使用 .xlsx 文件扩展名");
if (model.IsCurrentRecipeFile(path)) throw new IOException("SOP 导出不能覆盖当前配方文件");
// 在 UI 线程固定步骤数据,后台写文件时不再访问可编辑节点。
var steps = model.Recipe.Steps.Select(step => new SopExcelRow(step.Id, step.Name, step.Description, step.KeyFrameBase64)).ToArray();
await Task.Run(() => SopExcelExport.Save(path, steps));
if (!_closing && ReferenceEquals(model, _model))
model.StepTransferStatus = $"已导出 {steps.Length} 个步骤到 Excel:{Path.GetFileName(path)}";
}
catch (Exception error) { await ShowNotice("导出SOP文件失败", error.Message, false); }
finally { _stepTransferInProgress = false; }
}
private async Task<string?> ChooseStepImportMode(int incoming, int current)
{
if (_closing || _dialog is not null || TopLevel.GetTopLevel(this) is not Window owner) return null;

View File

@ -69,6 +69,8 @@
<Button Classes="settings-action" Content="导入" Command="{Binding ImportRecipeCommand}" ToolTip.Tip="导入 .bwsrecipe,同名时可覆盖(旧配方移入已删除配方目录)或改名。导入后请按本机相机复核区域坐标,再应用。" />
<Button Classes="settings-action" Content="导出" Command="{Binding ExportRecipeCommand}" ToolTip.Tip="将配方定义和标准 SOP 视频打包为 .bwsrecipe 文件。" />
<Button Classes="settings-action" Content="打开文件夹" Command="{Binding OpenRecipeFolderCommand}" />
<!-- 导出的是下拉框选中配方的已保存步骤。 -->
<Button Classes="settings-action" Content="导出SOP文件" Command="{Binding ExportSopCommand}" ToolTip.Tip="将所选配方的步骤和关键帧导出为 Excel 文件。" />
<Button Classes="settings-action" Content="删除" Command="{Binding DeleteRecipeCommand}" Foreground="{StaticResource Ng}" />
</WrapPanel>
</Grid>

View File

@ -1,16 +1,14 @@
using System.IO;
using ClosedXML.Excel;
using SopHelper.Engine.Sop;
namespace SopHelper.VVMs.RecipeEditor;
/// <summary>供 SOP 表格导出线程读取的步骤快照。</summary>
internal sealed record SopExcelRow(int Id, string Name, string Description, string KeyFrameBase64);
namespace SopHelper.VVMs.SopPage;
/// <summary>生成供查阅的 SOP 工作簿,并在生成成功后替换目标文件。</summary>
internal static class SopExcelExport
{
/// <summary>将步骤按执行顺序写入指定路径,关键帧随工作簿保存。</summary>
public static void Save(string path, IReadOnlyList<SopExcelRow> steps)
public static void Save(string path, IReadOnlyList<StepDef> steps)
{
using var workbook = new XLWorkbook();
var sheet = workbook.AddWorksheet("SOP");

View File

@ -169,6 +169,7 @@ public class SopPageViewModel : ViewModelBase
DeleteRecipeCommand = ConfigurationCommand(async () => await DeleteRecipeAsync(), CanDeleteRecipe, false, "删除配方");
ImportRecipeCommand = ConfigurationCommand(async () => await ImportRecipeAsync(), CanImportRecipe, false, "导入配方");
ExportRecipeCommand = ConfigurationCommand(async () => await ExportRecipeAsync(), CanExportRecipe, false, "导出配方");
ExportSopCommand = ConfigurationCommand(async () => await ExportSopAsync(), CanExportRecipe, false, "导出SOP文件");
OpenRecipeFolderCommand = ConfigurationCommand(() =>
{
try { DesktopPlatform.Reveal(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(SelectedRecipe!))); }
@ -334,7 +335,7 @@ public class SopPageViewModel : ViewModelBase
/// <summary>导入不需要选中配方(全新工作区也要能导入),只需要不在运行和传输中。</summary>
private bool CanImportRecipe() => CanSelectCamera;
/// <summary>导出需要一个已存在的选中配方;运行中允许导出,导出只读不改配方。</summary>
/// <summary>导出需要选中已保存的配方,且当前没有运行、相机操作或配方传输。</summary>
private bool CanExportRecipe() => CanSelectCamera && SelectedRecipe is { Length: > 0 } && File.Exists(RecipePath(SelectedRecipe));
/// <summary>配方包传输期间统一锁定相机、配方选择和配方命令,结束时无论成败都解锁。</summary>
@ -435,6 +436,8 @@ public class SopPageViewModel : ViewModelBase
/// <summary>把选中配方导出为单个配方包文件</summary>
public DelegateCommand ExportRecipeCommand { get; private set; } = null!;
/// <summary>从运行设置将选中配方的已保存步骤导出为 Excel。</summary>
public DelegateCommand ExportSopCommand { get; }
/// <summary>从配方包导入配方(不自动应用)</summary>
public DelegateCommand ImportRecipeCommand { get; private set; } = null!;
@ -486,6 +489,7 @@ public class SopPageViewModel : ViewModelBase
DeleteRecipeCommand?.RaiseCanExecuteChanged();
ImportRecipeCommand?.RaiseCanExecuteChanged();
ExportRecipeCommand?.RaiseCanExecuteChanged();
ExportSopCommand?.RaiseCanExecuteChanged();
OpenRecipeFolderCommand?.RaiseCanExecuteChanged();
}
@ -767,6 +771,42 @@ public class SopPageViewModel : ViewModelBase
finally { SetRecipeTransfer(false); }
}
/// <summary>导出选中配方的已保存步骤,保存对话框和后台写盘共用配方传输门控。</summary>
private async Task ExportSopAsync()
{
if (!CanExportRecipe()) return;
var recipePath = RecipePath(SelectedRecipe!);
var name = Path.GetFileNameWithoutExtension(SelectedRecipe!);
SetRecipeTransfer(true);
try
{
var picker = new SaveFileDialog
{
Title = "导出SOP文件", Filter = "Excel 工作簿|*.xlsx", DefaultExt = "xlsx",
SuggestedFileName = name, InitialDirectory = UserFileDirectory
};
if (await picker.ShowDialogAsync() != true) return;
var path = picker.FileName;
if (!Path.GetExtension(path).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
throw new IOException("请使用 .xlsx 文件扩展名");
// 后台只读取打开保存对话框时选中的配方文件,避免依赖界面选择和活动配方。
var count = await Task.Run(() =>
{
var steps = SopConfigLoader.Load(recipePath).Sop.Steps;
SopExcelExport.Save(path, steps);
return steps.Count;
});
StatusText = $"已导出配方“{name}”的 {count} 个步骤:{path}";
}
catch (Exception error)
{
StatusText = "导出SOP文件失败:" + error.Message;
Log("warn", StatusText);
}
finally { SetRecipeTransfer(false); }
}
/// <summary>按现场习惯显示包体积,便于判断能否用 U 盘或即时消息传递。</summary>
private static string FormatBytes(long bytes) => bytes switch
{

View File

@ -436,13 +436,20 @@ internal static class Smoke
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() == "导出");
// Excel 导出紧跟打开文件夹并使用与配方包导出一致的选择条件。
var openFolderButton = settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content?.ToString() == "打开文件夹");
var recipeActions = (WrapPanel)openFolderButton.Parent!;
Check(recipeActions.Children[recipeActions.Children.IndexOf(openFolderButton) + 1] is Button sopButton
&& Equals(sopButton.Content, "导出SOP文件") && ReferenceEquals(sopButton.Command, sop.ExportSopCommand)
&& sop.ExportSopCommand.CanExecute(), "运行设置的打开文件夹后提供 SOP Excel 导出");
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),
Check(ToolTip.GetTip(exportButton)?.ToString()?.Contains(".bwsrecipe") == true
&& ToolTip.GetTip(importButton)?.ToString()?.Contains("再应用") == true,
"运行设置说明配方包内容与导入不会自动应用");
var selected = sop.SelectedRecipe;
sop.SelectedRecipe = null;
Check(sop.ImportRecipeCommand.CanExecute() && !sop.ExportRecipeCommand.CanExecute(), "空配方选择仍可导入但不能导出");
Check(sop.ImportRecipeCommand.CanExecute() && !sop.ExportRecipeCommand.CanExecute() && !sop.ExportSopCommand.CanExecute(), "空配方选择仍可导入但不能导出");
sop.SelectedRecipe = selected;
var name = "transfer-" + Guid.NewGuid().ToString("N");

View File

@ -5,6 +5,7 @@ using ClosedXML.Excel;
using Prism.Dialogs;
using SopHelper.Engine.Sop;
using SopHelper.VVMs.RecipeEditor;
using SopHelper.VVMs.SopPage;
internal static class StepTransferChecks
{
@ -60,11 +61,6 @@ internal static class StepTransferChecks
Check(model.Recipe.Steps.Count == 2 && model.Recipe.SelectedStep is not null && model.StepTransferStatus.Contains("保存"), "导入更新编辑列表和选中项,明确需保存");
var rendered = new RecipeEditor { DataContext = model };
var window = new Window { Content = rendered, Width = 1040, Height = 900 }; window.Show(); window.UpdateLayout();
// 在切换到步骤页签之前核对顶部入口,并确认它紧跟配方名输入框。
var nameInput = rendered.FindControl<TextBox>("RecipeNameInput")!;
var header = (StackPanel)nameInput.Parent!;
var exportButton = rendered.GetVisualDescendants().OfType<Button>().Single(button => button.Content?.ToString() == "导出SOP文件");
Check(ReferenceEquals(header.Children[header.Children.IndexOf(nameInput) + 1], exportButton), "SOP 导出入口紧跟顶部配方名");
var tabs = rendered.GetVisualDescendants().OfType<TabControl>().Single();
tabs.SelectedItem = tabs.Items.OfType<TabItem>().Single(t => t.Header?.ToString() == "步骤"); window.UpdateLayout();
var toolbar = rendered.GetVisualDescendants().OfType<WrapPanel>().Single(panel =>
@ -95,7 +91,8 @@ internal static class StepTransferChecks
const string png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aXuoAAAAASUVORK5CYII=";
Directory.CreateDirectory(root);
var path = Path.Combine(root, "sop-export.xlsx");
SopExcelExport.Save(path, [new(8, "确认", "第一行\n第二行", png), new(2, "=定位", "说明", "")]);
SopExcelExport.Save(path, [new() { Id = 8, Name = "确认", Description = "第一行\n第二行", KeyFrameBase64 = png },
new() { Id = 2, Name = "=定位", Description = "说明" }]);
using var workbook = new XLWorkbook(path);
var sheet = workbook.Worksheet("SOP");
Check(sheet.Range("A1:D1").Cells().Select(cell => cell.GetString())