-
Notifications
You must be signed in to change notification settings - Fork 3
/
Main.cs
471 lines (413 loc) · 14.8 KB
/
Main.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
using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
[assembly: AssemblyTitle("heightmap2stl-gui")]
[assembly: AssemblyProduct("heightmap2stl-gui")]
[assembly: AssemblyVersion("1.3.4.0")]
[assembly: AssemblyFileVersion("1.3.4.0")]
namespace app
{
public partial class Main : Form
{
private const string DefaultXms = "64m";
private const string DefaultXmx = "8g";
private const string EmbeddedResourceName = "app.heightmap2stl.jar";
private Process _p;
private bool _autoBackup = true;
private string _lastCustom;
public Main()
{
InitializeComponent();
}
private void Main_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
}
private void Main_DragDrop(object sender, DragEventArgs e)
{
SetInputPath((e.Data.GetData(DataFormats.FileDrop) as string[])?.FirstOrDefault());
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Initial output path
SetOutputPath(GetOutputPath());
// Version
Text += $" {GetVersion()}";
Log($"Version: {GetVersion()}");
// Autobackup
if (Boolean.TryParse(ConfigurationManager.AppSettings["AutoBackup"], out _autoBackup))
{
chkAutoBackup.Checked = _autoBackup;
Log($"AutoBackup: {_autoBackup}");
}
}
private Version GetVersion() => Assembly.GetEntryAssembly().GetName().Version;
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
KillChildProcess();
}
private void btnCreate_Click(object sender, EventArgs e)
{
ClearLog();
if (CheckForJavaInPath() == false)
{
Log("JAVA cannot be found. Download/Install from https://java.com");
return;
}
if (GetInputFile() == null)
{
Log("Error: Heightmap Source is empty");
return;
}
var rawFileName = GetInputFile();
var outDirectory = GetOutputPath();
Log($"Input File: {rawFileName}");
Log($"Output Path: {outDirectory}");
var stlFile = new FileInfo(Path.Combine(outDirectory,
Path.GetFileNameWithoutExtension(rawFileName.FullName) + ".stl"));
Log($"Autobackup: {_autoBackup}");
if (_autoBackup)
{
var backupStlFile = new FileInfo(Path.Combine(
// Directory
outDirectory,
// FileName
Path.GetFileNameWithoutExtension(stlFile.Name) +
Regex.Replace(stlFile.LastWriteTime.ToString("s"), "[^a-zA-Z0-9]+", "-") +
stlFile.Extension
));
if (stlFile.Exists && !backupStlFile.Exists)
{
stlFile.MoveTo(backupStlFile.FullName);
Log($"Info: A STL file with the name {stlFile.Name} already existed, and was renamed to {backupStlFile}");
}
}
if (EnsureHeightmap2StlBinary())
{
btnCreate.Enabled = false;
btnCancel.Enabled = true;
Task.Factory.StartNew(RunExport).ContinueWith((ancestor, _) =>
{
btnCreate.Enabled = true;
btnCancel.Enabled = false;
if (ancestor.IsCompleted)
{
Log($"Created STL file {stlFile.FullName}");
}
},
null,
TaskScheduler.FromCurrentSynchronizationContext());
}
}
private void RunExport()
{
var rawFileName = GetInputFile();
_p = new Process();
_p.StartInfo.WorkingDirectory = GetOutputPath();
_p.StartInfo.FileName = "java.exe";
_p.StartInfo.Arguments = string.Join(" ",
JavaSystemProperties(),
"-jar",
$"\"{GetAppTempPath()}\"",
$"\"{rawFileName.FullName}\"",
numModelHeight.Text,
numBaseHeight.Text
);
_p.StartInfo.CreateNoWindow = true;
_p.StartInfo.UseShellExecute = false;
_p.StartInfo.RedirectStandardOutput = true;
_p.StartInfo.RedirectStandardError = true;
_p.OutputDataReceived += OnDataReceived;
_p.ErrorDataReceived += OnDataReceived;
_p.Start();
Log(_p.StartInfo.FileName + " " + _p.StartInfo.Arguments);
_p.BeginOutputReadLine();
_p.BeginErrorReadLine();
_p.WaitForExit(360000);
_p.Close();
_p = null;
}
private void OnDataReceived(object sender, DataReceivedEventArgs args)
{
if (args.Data == null)
return;
Log(args.Data);
}
// CrossThreadSafe
private void Log(string text)
{
if (txtLog.InvokeRequired)
{
txtLog.Invoke(new Action<string>(Log), text);
}
else
{
txtLog.AppendText(text + Environment.NewLine);
}
}
// CrossThreadSafe
private void ClearLog()
{
if (txtLog.InvokeRequired)
{
txtLog.Invoke(new Action(ClearLog));
}
else
{
txtLog.Clear();
}
}
private string JavaSystemProperties()
{
var settings = ConfigurationManager.AppSettings;
var validSize = new Regex(@"\d+[kKmMgG]");
var properties = new Dictionary<string, string>();
// Process each setting
var rawXms = settings["Xms"];
if (validSize.IsMatch(rawXms))
{
properties["Xms"] = rawXms;
}
else
{
properties["Xms"] = DefaultXms;
Log("User-supplied Xms is invalid. Using default: " + DefaultXms);
}
var rawXmx = settings["Xmx"];
if (validSize.IsMatch(rawXmx))
{
properties["Xmx"] = rawXmx;
}
else
{
properties["Xmx"] = DefaultXmx;
Log("User-supplied Xmx is invalid. Using default: " + DefaultXmx);
}
// Prefix all the values with -D and combine with spaces
return String.Join(" ", properties.Select(x => "-D" + x.Key + "=" + x.Value));
}
// A standard java install will add java.exe to %PATH%
private bool CheckForJavaInPath()
{
try
{
var psi = new ProcessStartInfo("java.exe", "-version");
psi.UseShellExecute = true;
var process = Process.Start(psi);
process?.WaitForExit(50000);
return process?.ExitCode == 0;
}
catch
{
// ignored
}
return false;
}
private Stream EmbeddedHeightmap2StlBinary()
{
var asm = Assembly.GetEntryAssembly();
return asm.GetManifestResourceStream(EmbeddedResourceName);
}
private bool EnsureHeightmap2StlBinary()
{
string path = GetAppTempPath();
if (File.Exists(path))
{
if (BinaryMatchesEmbeddedVersion(path) == false)
{
Log("Warning: Replacing heightmap2stl.jar at {path}.");
Log($"Current hash: {Md5HashFile(path)}");
Log($"Embedded hash: {EmbeddedHeightmap2StlBinaryHash()}");
File.Delete(path);
CopyEmbeddedHeightmap2StlBinaryToTemp(path);
Log($"Replaced");
}
}
else
{
CopyEmbeddedHeightmap2StlBinaryToTemp(path);
}
return BinaryMatchesEmbeddedVersion(path);
}
private void CopyEmbeddedHeightmap2StlBinaryToTemp(string path)
{
using (Stream app = EmbeddedHeightmap2StlBinary())
using (Stream writer = File.OpenWrite(path))
{
app?.CopyTo(writer);
}
Log($"Deployed heightmap2stl.jar with hash: {Md5HashFile(path)}");
}
private bool BinaryMatchesEmbeddedVersion(string path)
{
return Md5HashFile(path) == EmbeddedHeightmap2StlBinaryHash();
}
private string EmbeddedHeightmap2StlBinaryHash()
{
using (Stream binary = EmbeddedHeightmap2StlBinary())
{
return Md5HashStream(binary);
}
}
private static string GetAppTempPath()
{
return Path.Combine(Environment.GetEnvironmentVariable("TEMP"), "heightmap2stl.jar");
}
private void hostSoftwareSite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start((string)e.Link.Tag);
}
private void btnPick_Click(object sender, EventArgs e)
{
using (FileDialog d = new OpenFileDialog())
{
if (DialogResult.OK != d.ShowDialog()) return;
SetInputPath(d.FileName);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
KillChildProcess();
Log(new string('-', 20));
Log("Warning: User cancelled processing");
}
private void KillChildProcess()
{
_p?.Kill();
}
private static string Md5HashFile(string filePathName)
{
using (var stream = File.OpenRead(filePathName))
return Md5HashStream(stream);
}
private static string Md5HashStream(Stream stream)
{
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "");
}
}
private void btnCustom_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = GetOutputPath();
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
if (!radOutCustom.Checked)
{
radOutCustom.Checked = true;
}
SetOutputPath(dialog.FileName);
}
else
{
if(GetOutputPath() != Environment.CurrentDirectory)
{
SetOutputPath(Environment.CurrentDirectory);
}
}
}
private void radOutput_Click(object sender, EventArgs e)
{
if (radOutCustom.Checked)
{
SetOutputPath(_lastCustom);
if (GetOutputPath() == Environment.CurrentDirectory)
{
Log("Rember to set your custom path");
}
}
UpdateOutputPath();
}
private void SetInputPath(string fileName)
{
txtInputFile.Text = fileName;
UpdateOutputPath();
}
private FileInfo GetInputFile()
{
return
String.IsNullOrEmpty(txtInputFile.Text) ?
null :
new FileInfo(txtInputFile.Text);
}
private void SetOutputPath(string outputPath)
{
txtOutputPath.Text = outputPath;
if (radOutCustom.Checked)
{
_lastCustom = outputPath;
}
}
private string GetOutputPath()
{
if (radOutProgram.Checked)
{
return Environment.CurrentDirectory;
}
// same as input file
if(radOutSource.Checked)
{
// input file might not be set yet, fallback to current directory
var inputFile = GetInputFile();
if (inputFile == null)
{
Log("No Input image specified. Output path will update when input is selected.");
return Environment.CurrentDirectory;
}
// Use the directory of the input file if it's available, otherwise current directory
return inputFile.DirectoryName ?? Environment.CurrentDirectory;
}
if(radOutCustom.Checked)
{
if (string.IsNullOrEmpty(txtOutputPath.Text))
{
return Environment.CurrentDirectory;
}
return txtOutputPath.Text;
}
// Final fallback
return Environment.CurrentDirectory;
}
private void UpdateOutputPath()
{
txtOutputPath.Text = GetOutputPath();
}
private void chkAutoBackup_Click(object sender, EventArgs e)
{
_autoBackup = chkAutoBackup.Checked;
}
}
}
namespace app
{
static class Program
{
[STAThread]
static void Main()
{
// The rest of the program assumes CurrentDirectory is the directory the exe is in
Environment.CurrentDirectory = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
}