-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
487 lines (426 loc) · 21.6 KB
/
MainWindow.xaml.cs
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using Ookii.Dialogs.Wpf;
namespace MarlinEasyConfig
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<ConfigParameter> configParameters = new ObservableCollection<ConfigParameter>();
string[] parameterIgnoreList = new string[] { "CONFIGURATION_H_VERSION", "CONFIGURATION_ADV_H_VERSION" };
string[] externalParameterList = new string[] { "HIGH", "LOW", "DISABLE", "ENABLE",
"X_CENTER", "Y_CENTER", "XY_CENTER",
"JAPANESE", "WESTERN", "CYRILLIC",
"NEO_GRBW", "NEO_GRB",
"DXC_AUTO_PARK_MODE",
"_XMAX_", "_YMAX_", "_ZMAX_",
"F_CPU", "SDSS", "SD_DETECT_PIN", "SV_SD_ONBOARD", "SV_USB_FLASH_DRIVE",
"CHOPPER_DEFAULT_12V", "CHOPPER_DEFAULT_19V", "CHOPPER_DEFAULT_24V", "CHOPPER_DEFAULT_36V", "CHOPPER_09STEP_24V", "CHOPPER_PRUSAMK3_24V", "CHOPPER_MARLIN_11"
};
string currentMarlinConfig;
string currentMarlinConfigAdv;
public MainWindow()
{
InitializeComponent();
CompareColumn.Visibility = Visibility.Collapsed;
}
private void Menu_OpenMarlin(object sender, RoutedEventArgs e)
{
var dialog = new VistaFolderBrowserDialog
{
Description = "Please select a Marlin folder.",
UseDescriptionForTitle = true
};
if ((bool)dialog.ShowDialog(this))
{
bool doCompare = ((MenuItem)sender).Name == "MenuItem_Compare";
var configFolder = GetMarlinConfigFolder(dialog.SelectedPath);
var configFile = CheckConfigFile(configFolder);
if (configFile != null)
{
if (doCompare) CompareConfig(configFile);
else ParseConfig(configFile);
var configFileAdv = CheckConfigFile(configFolder, true);
if (configFileAdv != null)
{
if (doCompare) CompareConfig(configFileAdv, true);
else ParseConfig(configFileAdv, true);
}
// regular open mode
if (!doCompare)
{
CompareColumn.Visibility = Visibility.Collapsed;
ConfigTable.ItemsSource = null;
ConfigTable.ItemsSource = configParameters;
MenuItem_Compare.IsEnabled = true;
MenuItem_Transfer.IsEnabled = false;
MenuItem_Restore.IsEnabled = CheckBackupAvailable(configFolder);
currentMarlinConfig = configFile;
currentMarlinConfigAdv = configFileAdv;
}
else // compare mode
{
CompareColumn.Visibility = Visibility.Visible;
MenuItem_Compare.IsEnabled = true;
MenuItem_Transfer.IsEnabled = true;
}
}
}
}
private void Menu_Restore(object sender, RoutedEventArgs e)
{
// load config backup
var configFile = currentMarlinConfig.Replace(".h", ".bak");
if (File.Exists(configFile)) ParseConfig(configFile, false, true);
// load advanced config backup
var configFileAdv = currentMarlinConfigAdv.Replace(".h", ".bak");
if (File.Exists(configFileAdv)) ParseConfig(configFileAdv, true, true);
ConfigTable.Items.Refresh();
}
private string GetMarlinConfigFolder(string path)
{
var platformFile = path + @"\platformio.ini";
if (File.Exists(platformFile) && Directory.Exists(path + @"\Marlin"))
{
path += @"\Marlin";
}
return path;
}
private bool CheckBackupAvailable(string path)
{
var configBak = path + @"\Configuration.bak";
var configAdvBak = path + @"\Configuration_adv.bak";
return File.Exists(configBak) || File.Exists(configAdvBak);
}
private string CheckConfigFile(string path, bool advanced = false, bool backup = false)
{
var configFile = @"\Configuration" + (advanced ? "_adv" : null) + @"." + (backup ? "bak" : "h");
var configFilePath = path + configFile;
if (File.Exists(configFilePath)) return configFilePath;
MessageBox.Show(this, $"Sorry! This does not seem to be a Marlin directory:{Environment.NewLine}{path} does not include \"{configFile}\".", "No Marlin Folder");
return null;
}
private string ReadConfigFile(string file)
{
Regex regexMultiline = new Regex(@"\\\n\s*");
return regexMultiline.Replace(File.ReadAllText(file), "");
}
private string[] ReadConfigFileLines(string file)
{
Regex regexMultiline = new Regex(@"\\\n\s*");
return regexMultiline.Replace(File.ReadAllText(file), "").Split('\n');
}
private void ParseConfig(string configFile, bool advanced = false, bool restore = false)
{
string[] configLines = ReadConfigFileLines(configFile);
foreach (var line in configLines)
{
var cleanedLine = line.TrimStart();
if (!cleanedLine.StartsWith("#define")) continue;
var configLine = new ConfigParameter(cleanedLine, advanced);
if (!parameterIgnoreList.Contains(configLine.Name))
{
if (restore)
{
int existingParameter = configParameters.FindIndex(p => p.Name == configLine.Name);
if (existingParameter >= 0) configParameters[existingParameter] = configLine;
}
else
{
configLine.Index = configParameters.Count;
configParameters.Add(configLine);
}
}
}
}
private void CompareConfig(string configFile, bool advanced = false)
{
string[] configLines = ReadConfigFileLines(configFile);
foreach (var line in configLines)
{
var cleanedLine = line.TrimStart();
if (!cleanedLine.StartsWith("#define")) continue;
var compareConfigParameter = new ConfigParameter(cleanedLine, advanced);
var existingConfigParameterIndex = configParameters.FindIndex(c => c.Name == compareConfigParameter.Name);
if (existingConfigParameterIndex >= 0 && configParameters[existingConfigParameterIndex].CompareTo(compareConfigParameter) == -1)
{
var existingConfigParameter = configParameters[existingConfigParameterIndex];
existingConfigParameter.IsDifferent = true;
existingConfigParameter.DifferentValue = compareConfigParameter.CleanValue(compareConfigParameter.Value);
configParameters[existingConfigParameterIndex] = existingConfigParameter;
}
}
}
private bool ParameterExists(string parameterName)
{
return configParameters.FindIndex(p => p.Name == parameterName) >= 0 || externalParameterList.Contains(parameterName);
}
public bool IsMathFormula(string expr)
{
var split = expr.Split(" ");
Regex regexVariable = new Regex(@"^[A-Z0-9_]*$");
Regex regexMathAndNum = new Regex(@"^[\d\(\)\+\-\*\/\.]*$");
foreach (var item in split)
{
var cleanedItem = item.ReplaceAll(new[] { "(", ")", "+", "-", "*", "/" }, "");
if (regexMathAndNum.IsMatch(cleanedItem)) continue;
if (regexVariable.IsMatch(cleanedItem) && !ParameterExists(cleanedItem))
{
return false;
}
}
return true;
}
private bool IsFloatOrInt(string value) => int.TryParse(value, out int intValue) || float.TryParse(value, out float floatValue) || IsMathFormula(value);
private void ConfigTable_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditAction == DataGridEditAction.Commit)
{
var column = e.Column as DataGridBoundColumn;
if (column != null)
{
var bindingSource = (column.Binding as Binding).Path;
var bindingPath = (column.Binding as Binding).Path.Path;
if (bindingPath == "Value")
{
int rowIndex = ((ConfigParameter)e.Row.Item).Index;//e.Row.GetIndex();
var el = e.EditingElement as TextBox;
var elText = el.Text.Trim();
var parameter = configParameters[rowIndex];
switch (parameter.Type)
{
case ParameterType.String:
//el.Text = elText.Trim(new[] { '"', '\'' });
break;
case ParameterType.Array:
if (!new Regex(@"^{.+}").Match(elText).Success && !ParameterExists(elText))
{
MessageBox.Show(this, $"Sorry! {parameter.Name} is of type array:{Environment.NewLine}Value needs to be surrounded by \"{{\" and \"}}\" or another parameter.", "Value Error");
el.Text = parameter.Value;
e.Cancel = true;
}
else
{
el.Text = parameter.CleanValue(elText);
}
break;
case ParameterType.Boolean:
var lowerVal = elText.ToLower();
if (lowerVal != "false" && lowerVal != "true" && !ParameterExists(elText))
{
MessageBox.Show(this, $"Sorry! {parameter.Name} is of type bool:{Environment.NewLine}Only \"true\", \"false\" or another parameter accepted.", "Value Error");
el.Text = parameter.Value;
e.Cancel = true;
}
else
{
el.Text = parameter.CleanValue(lowerVal);
}
break;
case ParameterType.Definition:
if (!string.IsNullOrEmpty(elText))
{
MessageBox.Show(this, $"Sorry! {parameter.Name} is only a definition:{Environment.NewLine}No value allowed.", "Value Error");
el.Text = null;
e.Cancel = true;
}
break;
case ParameterType.Number:
var newVal = elText.Replace(",", ".");
Regex regexMathSpacers = new Regex(@"(\s*([\(\)\+\-\*\/])\s*)");
newVal = regexMathSpacers.Replace(newVal.Trim(), " $2 ").Trim();
if (!IsFloatOrInt(newVal) && !ParameterExists(elText))
{
MessageBox.Show(this, $"Sorry! {parameter.Name} is of type Number:{Environment.NewLine}Only integers, floats, other parameters and mathematic expressions accepted.", "Value Error");
el.Text = parameter.Value;
e.Cancel = true;
}
else
{
// remove whitespace if value is a single number with a sign (like a negative integer)
if (newVal.Count(char.IsWhiteSpace) == 1) newVal = newVal.Replace(" ", "");
// finally set new value
el.Text = parameter.CleanValue(newVal);
}
break;
default:
break;
}
}
}
}
}
private void ContextMenuCopyClicked(object sender, RoutedEventArgs e, ConfigParameter config)
{
if (config != null) Clipboard.SetData("MarlinEasyConfigParameter", config);
}
private void ContextMenuPasteClicked(object sender, RoutedEventArgs e, DataGridRow gridRow)
{
if (Clipboard.ContainsData("MarlinEasyConfigParameter"))
{
var rowIndex = gridRow.GetIndex();
if (rowIndex < 0) return;
var configNamePasted = (Clipboard.GetData("MarlinEasyConfigParameter") as ConfigParameter).Name;
var configParamByIndex = configParameters[rowIndex];
if (configParamByIndex.Name == configNamePasted) return;
configParamByIndex.Value = configNamePasted;
configParameters[rowIndex] = configParamByIndex;
gridRow.Item = configParamByIndex;
ConfigTable.Items.Refresh();
}
}
private void ConfigTable_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
DataGridCell cell;
DataGridRow row;
var dep = DataGridMiscHelpers.FindVisualParentAsDataGridSubComponent((DependencyObject)e.OriginalSource);
if (dep == null)
{
e.Handled = true;
return;
}
DataGridMiscHelpers.FindCellAndRow(dep, out cell, out row);
string header = cell?.Column?.Header.ToString();
if (dep is DataGridColumnHeader || dep is DataGridRow || (header != "Name" && header != "Value"))
{
e.Handled = true;
return;
}
ContextCopy.IsEnabled = header == "Name";
ContextPaste.IsEnabled = header == "Value" && Clipboard.ContainsData("MarlinEasyConfigParameter");
ContextCopy.Click += (sender, e) => ContextMenuCopyClicked(sender, e, row.Item as ConfigParameter);
ContextPaste.Click += (sender, e) => ContextMenuPasteClicked(sender, e, row);
}
private void Menu_Transfer(object sender, RoutedEventArgs e)
{
foreach (var param in configParameters)
{
if (!string.IsNullOrEmpty(param.DifferentValue) && param.Value != param.DifferentValue)
{
param.Value = param.DifferentValue;
}
}
ConfigTable.Items.Refresh();
}
private bool ReplaceInConfig(string configFile)
{
if (!string.IsNullOrEmpty(configFile))
{
string conf = ReadConfigFile(configFile);
foreach (var parameter in configParameters)
{
// ignore multiline commented defines (* in front), match name of variable, value and comment (if available)
string pattern = @"^(\s*#define\s+)(" + parameter.Name + @")(?:\s+)(.*?)(?: *(/{2}.+)|\n)"; // {1} = define, {2} = variable, {3} = value, {4} = comment
var newValue = parameter.Value;
if (parameter.Type == ParameterType.Definition) continue;
if (parameter.Type == ParameterType.String) newValue = '"' + parameter.CleanValue(newValue).TrimEnd('\\') + '"';
conf = Regex.Replace(conf, pattern, m => string.IsNullOrEmpty(m.Groups[3].Value) ? m.Value : m.Value?.ReplaceFirst(m.Groups[3].Value, newValue ), RegexOptions.Multiline);
}
File.Move(configFile, configFile.Replace(".h", ".bak"), true);
File.WriteAllText(configFile, conf);
return true;
}
return false;
}
private void MenuItem_Save(object sender, RoutedEventArgs e)
{
// regular config file
ReplaceInConfig(currentMarlinConfig);
// advanced config file
ReplaceInConfig(currentMarlinConfigAdv);
// enable restore
MenuItem_Restore.IsEnabled = true;
}
private void Input_Search_TextChanged(object sender, TextChangedEventArgs e)
{
var txt = (TextBox)sender;
var txtSearch = txt.Text.ToLower();
foreach (var param in configParameters) param.Filter(txtSearch);
ConfigTable.Items.Refresh();
}
private void MenuItem_Info(object sender, RoutedEventArgs e)
{
string messageBoxCaption = "Information";
string messageBoxText = string.Join(Environment.NewLine + Environment.NewLine,
$"MarlinEasyConfig is created by 48DESIGN GmbH - New Media Agency Karlsruhe, Germany. More information about us can be found at vierachtdesign.com",
"The source code can be found at <a href=\"https://github.com/48design/MarlinEasyConfig\">github.com/48design/MarlinEasyConfig</a>",
"MarlinEasyConfig uses the class library \"Ookii.Dialogs.Wpf\" for special dialogs");
string messageBoxLicences = string.Join(Environment.NewLine,
"Marlin firmware : GPLv3 License",
"Ookii.Dialogs.Wpf : BSD 3 - Clause License");
if (TaskDialog.OSSupportsTaskDialogs)
{
using (TaskDialog dialog = new TaskDialog())
{
dialog.WindowTitle = messageBoxCaption;
dialog.MainInstruction = "MarlinEasyConfig is a configuration tool for the famous Marlin 3D printer firmware to make editing Marlin configurations an easy task.";
dialog.Content = messageBoxText;
dialog.ExpandedControlText = "Show licences";
dialog.ExpandedInformation = messageBoxLicences;
dialog.Footer = "Source code at <a href=\"https://github.com/48design/MarlinEasyConfig\">github.com/48design/MarlinEasyConfig</a>.";
dialog.FooterIcon = TaskDialogIcon.Information;
dialog.EnableHyperlinks = true;
TaskDialogButton licenceOneButton = new TaskDialogButton("Ookii.Dialogs.Wpf licence");
TaskDialogButton licenceTwoButton = new TaskDialogButton("Marlin licence");
TaskDialogButton okButton = new TaskDialogButton(ButtonType.Ok);
dialog.Buttons.Add(licenceOneButton);
dialog.Buttons.Add(licenceTwoButton);
dialog.Buttons.Add(okButton);
dialog.HyperlinkClicked += new EventHandler<HyperlinkClickedEventArgs>(TaskDialog_HyperLinkClicked);
TaskDialogButton button = dialog.ShowDialog(this);
if (button == licenceOneButton)
{
Process.Start(new ProcessStartInfo
{
FileName = "https://github.com/ookii-dialogs/ookii-dialogs-wpf",
UseShellExecute = true
});
}
else if(button == licenceTwoButton)
{
Process.Start(new ProcessStartInfo
{
FileName = "https://github.com/MarlinFirmware/Marlin/",
UseShellExecute = true
});
}
}
}
else
{
MessageBox.Show(messageBoxText, messageBoxCaption, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.Yes);
}
}
private void TaskDialog_HyperLinkClicked(object sender, HyperlinkClickedEventArgs e)
{
Process.Start(new ProcessStartInfo
{
FileName = e.Href,
UseShellExecute = true
});
}
private void Menu_Exit(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show($"Do you want to close MarlinEasyConfig?{Environment.NewLine}Unsaved changes may be lost.", "Exit", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
Application.Current.Shutdown();
}
}
}
}