-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCableRoutingViewModel.cs
More file actions
344 lines (303 loc) · 11.8 KB
/
Copy pathCableRoutingViewModel.cs
File metadata and controls
344 lines (303 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage;
using ModerBox.CableRouting;
using ReactiveUI;
using System;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;
using static ModerBox.Common.Util;
namespace ModerBox.ViewModels;
public class CableRoutingViewModel : ViewModelBase
{
public ReactiveCommand<Unit, Unit> SelectConfigFile { get; }
public ReactiveCommand<Unit, Unit> SelectBaseImage { get; }
public ReactiveCommand<Unit, Unit> SelectOutputPath { get; }
public ReactiveCommand<Unit, Unit> CreateSampleConfig { get; }
public ReactiveCommand<Unit, Unit> RunRouting { get; }
private string _configFilePath = string.Empty;
public string ConfigFilePath
{
get => _configFilePath;
set => this.RaiseAndSetIfChanged(ref _configFilePath, value);
}
private string _baseImagePath = string.Empty;
public string BaseImagePath
{
get => _baseImagePath;
set => this.RaiseAndSetIfChanged(ref _baseImagePath, value);
}
private string _outputPath = string.Empty;
public string OutputPath
{
get => _outputPath;
set => this.RaiseAndSetIfChanged(ref _outputPath, value);
}
private string _logOutput = string.Empty;
public string LogOutput
{
get => _logOutput;
set => this.RaiseAndSetIfChanged(ref _logOutput, value);
}
private bool _isRunning;
public bool IsRunning
{
get => _isRunning;
set => this.RaiseAndSetIfChanged(ref _isRunning, value);
}
private int _progress;
public int Progress
{
get => _progress;
set => this.RaiseAndSetIfChanged(ref _progress, value);
}
private int _progressMax = 100;
public int ProgressMax
{
get => _progressMax;
set => this.RaiseAndSetIfChanged(ref _progressMax, value);
}
public CableRoutingViewModel()
{
SelectConfigFile = ReactiveCommand.CreateFromTask(SelectConfigFileTask);
SelectBaseImage = ReactiveCommand.CreateFromTask(SelectBaseImageTask);
SelectOutputPath = ReactiveCommand.CreateFromTask(SelectOutputPathTask);
CreateSampleConfig = ReactiveCommand.CreateFromTask(CreateSampleConfigTask);
RunRouting = ReactiveCommand.CreateFromTask(RunRoutingTask);
}
private async Task SelectConfigFileTask()
{
try
{
var file = await DoOpenFilePickerAsync(new FilePickerOpenOptions
{
Title = "选择配置文件",
AllowMultiple = false,
FileTypeFilter = new[]
{
new FilePickerFileType("JSON配置文件") { Patterns = new[] { "*.json" } },
new FilePickerFileType("所有文件") { Patterns = new[] { "*.*" } }
}
});
if (file != null)
{
ConfigFilePath = file.TryGetLocalPath() ?? file.Path.ToString();
// 尝试加载配置并自动填充其他路径
var config = CableRoutingService.LoadConfig(ConfigFilePath);
if (config != null)
{
var configDir = System.IO.Path.GetDirectoryName(ConfigFilePath) ?? "";
if (!string.IsNullOrEmpty(config.BaseImagePath))
{
BaseImagePath = System.IO.Path.IsPathRooted(config.BaseImagePath)
? config.BaseImagePath
: System.IO.Path.Combine(configDir, config.BaseImagePath);
}
if (!string.IsNullOrEmpty(config.OutputPath))
{
OutputPath = System.IO.Path.IsPathRooted(config.OutputPath)
? config.OutputPath
: System.IO.Path.Combine(configDir, config.OutputPath);
}
AppendLog($"✅ 已加载配置文件,包含 {config.Points.Count} 个点位");
}
}
}
catch (Exception ex)
{
AppendLog($"❌ 选择配置文件失败: {ex.Message}");
}
}
private async Task SelectBaseImageTask()
{
try
{
var file = await DoOpenFilePickerAsync(new FilePickerOpenOptions
{
Title = "选择底图",
AllowMultiple = false,
FileTypeFilter = new[]
{
new FilePickerFileType("图片文件") { Patterns = new[] { "*.jpg", "*.jpeg", "*.png", "*.bmp" } },
new FilePickerFileType("所有文件") { Patterns = new[] { "*.*" } }
}
});
if (file != null)
{
BaseImagePath = file.TryGetLocalPath() ?? file.Path.ToString();
}
}
catch (Exception ex)
{
AppendLog($"❌ 选择底图失败: {ex.Message}");
}
}
private async Task SelectOutputPathTask()
{
try
{
var file = await DoSaveFilePickerAsync(new FilePickerSaveOptions
{
Title = "选择输出路径",
DefaultExtension = "png",
SuggestedFileName = "result.png",
FileTypeChoices = new[]
{
new FilePickerFileType("PNG图片") { Patterns = new[] { "*.png" } },
new FilePickerFileType("JPEG图片") { Patterns = new[] { "*.jpg", "*.jpeg" } }
}
});
if (file != null)
{
OutputPath = file.TryGetLocalPath() ?? file.Path.ToString();
}
}
catch (Exception ex)
{
AppendLog($"❌ 选择输出路径失败: {ex.Message}");
}
}
private async Task CreateSampleConfigTask()
{
try
{
var file = await DoSaveFilePickerAsync(new FilePickerSaveOptions
{
Title = "保存示例配置",
DefaultExtension = "json",
SuggestedFileName = "cable_routing_config.json",
FileTypeChoices = new[]
{
new FilePickerFileType("JSON配置文件") { Patterns = new[] { "*.json" } }
}
});
if (file != null)
{
var path = file.TryGetLocalPath() ?? file.Path.ToString();
CableRoutingService.CreateSampleConfig(path);
ConfigFilePath = path;
AppendLog($"✅ 已创建示例配置文件: {path}");
AppendLog(" 请编辑配置文件中的点位数据后再运行");
}
}
catch (Exception ex)
{
AppendLog($"❌ 创建示例配置失败: {ex.Message}");
}
}
private async Task RunRoutingTask()
{
if (string.IsNullOrEmpty(ConfigFilePath))
{
AppendLog("❌ 请先选择配置文件");
return;
}
IsRunning = true;
Progress = 0;
LogOutput = string.Empty;
AppendLog("=" + new string('=', 59));
AppendLog("🔌 电缆走向自动化绘制程序");
AppendLog("=" + new string('=', 59));
try
{
await Task.Run(() =>
{
var config = CableRoutingService.LoadConfig(ConfigFilePath);
if (config == null)
{
AppendLog("❌ 无法加载配置文件");
return;
}
// 覆盖配置中的底图路径
if (!string.IsNullOrEmpty(BaseImagePath))
{
config.BaseImagePath = BaseImagePath;
}
// 单任务模式下可覆盖输出路径
if (!string.IsNullOrEmpty(OutputPath) && !config.IsMultiTask)
{
config.OutputPath = OutputPath;
}
// 处理相对路径(相对于配置文件目录)
var configDir = System.IO.Path.GetDirectoryName(ConfigFilePath) ?? "";
if (!string.IsNullOrEmpty(configDir))
{
if (!System.IO.Path.IsPathRooted(config.BaseImagePath))
{
config.BaseImagePath = System.IO.Path.Combine(configDir, config.BaseImagePath);
}
foreach (var task in config.GetEffectiveTasks())
{
if (!System.IO.Path.IsPathRooted(task.OutputPath))
{
task.OutputPath = System.IO.Path.Combine(configDir, task.OutputPath);
}
}
}
var service = new CableRoutingService();
var results = service.ExecuteAll(config, msg =>
{
AppendLog(msg);
Progress = Math.Min(Progress + 10, 90);
});
Progress = 100;
AppendLog("");
AppendLog("=" + new string('=', 59));
AppendLog("📊 输出汇总");
AppendLog("=" + new string('=', 59));
var successCount = results.Count(r => r.Success);
AppendLog($" 任务总数: {results.Count} 成功: {successCount}");
foreach (var result in results)
{
if (result.Success)
{
AppendLog($" ✅ {result.OutputPath}");
AppendLog($" 路径: {result.GetRouteDescription()}");
AppendLog($" 总长: {result.TotalLength:F2} 像素");
}
else
{
AppendLog($" ❌ {result.OutputPath}: {result.ErrorMessage}");
}
}
AppendLog("=" + new string('=', 59));
// 打开第一个成功的输出文件所在目录
var firstSuccess = results.FirstOrDefault(r => r.Success);
if (firstSuccess != null)
{
firstSuccess.OutputPath.OpenFileWithExplorer();
}
});
}
catch (Exception ex)
{
AppendLog($"❌ 执行出错: {ex.Message}");
}
finally
{
IsRunning = false;
}
}
private void AppendLog(string message)
{
LogOutput += message + Environment.NewLine;
}
private static async Task<IStorageFile?> DoOpenFilePickerAsync(FilePickerOpenOptions options)
{
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop ||
desktop.MainWindow?.StorageProvider is not { } provider)
throw new NullReferenceException("Missing StorageProvider instance.");
var files = await provider.OpenFilePickerAsync(options);
return files?.Count >= 1 ? files[0] : null;
}
private static async Task<IStorageFile?> DoSaveFilePickerAsync(FilePickerSaveOptions options)
{
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop ||
desktop.MainWindow?.StorageProvider is not { } provider)
throw new NullReferenceException("Missing StorageProvider instance.");
return await provider.SaveFilePickerAsync(options);
}
}