forked from MatterHackers/MatterControl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatterControlApplication.cs
385 lines (329 loc) · 15.3 KB
/
MatterControlApplication.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
/*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PartPreviewWindow;
using MatterHackers.MatterControl.PluginSystem;
using MatterHackers.MatterControl.PrinterCommunication;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.VectorMath;
namespace MatterHackers.MatterControl
{
public class MatterControlApplication : SystemWindow
{
string[] commandLineArgs = null;
bool firstDraw = true;
bool ShowMemoryUsed = false;
bool DoCGCollectEveryDraw = false;
public bool RestartOnClose = false;
public MatterControlApplication(double width, double height)
: base(width, height)
{
CrashTracker.Reset();
this.commandLineArgs = Environment.GetCommandLineArgs();
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
foreach(string command in commandLineArgs)
{
string commandUpper = command.ToUpper();
switch (commandUpper)
{
case "TEST":
Testing.TestingDispatch testDispatch = new Testing.TestingDispatch();
testDispatch.RunTests();
return;
case "CLEAR_CACHE":
AboutPage.DeleteCacheData();
break;
case "SHOW_MEMORY":
ShowMemoryUsed = true;
break;
case "DO_GC_COLLECT_EVERY_DRAW":
ShowMemoryUsed = true;
DoCGCollectEveryDraw = true;
break;
}
}
//WriteTestGCodeFile();
#if !DEBUG
if (File.Exists("RunUnitTests.txt"))
#endif
{
#if IS_WINDOWS_FORMS
Clipboard.SetSystemClipboardFunctions(System.Windows.Forms.Clipboard.GetText, System.Windows.Forms.Clipboard.SetText, System.Windows.Forms.Clipboard.ContainsText);
#endif
MatterHackers.PolygonMesh.UnitTests.UnitTests.Run();
MatterHackers.RayTracer.UnitTests.Run();
MatterHackers.Agg.Tests.UnitTests.Run();
MatterHackers.VectorMath.Tests.UnitTests.Run();
MatterHackers.Agg.UI.Tests.UnitTests.Run();
// you can turn this on to debug some bounds issues
//GuiWidget.DebugBoundsUnderMouse = true;
}
GuiWidget.DefaultEnforceIntegerBounds = true;
//TextWidget.GlobalPointSizeScaleRatio = 1.63;
this.AddChild(ApplicationWidget.Instance);
this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off
#if false // this is to test freeing gcodefile memory
Button test = new Button("test");
test.Click += (sender, e) =>
{
//MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile();
//gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode");
SystemWindow window = new SystemWindow(100, 100);
window.ShowAsSystemWindow();
};
allControls.AddChild(test);
#endif
this.AnchorAll();
UseOpenGL = true;
string version = "1.1";
Title = "MatterControl {0}".FormatWith(version);
if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
{
Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra);
}
UiThread.RunOnIdle(CheckOnPrinter);
MinimumSize = new Vector2(590, 630);
string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition");
if (desktopPosition != null && desktopPosition != "")
{
string[] sizes = desktopPosition.Split(',');
//If the desktop position is less than -10,-10, override
int xpos = Math.Max(int.Parse(sizes[0]), -10);
int ypos = Math.Max(int.Parse(sizes[1]), -10);
DesktopPosition = new Point2D(xpos, ypos);
}
ShowAsSystemWindow();
}
private static void WriteMove(StringBuilder gcodeStringBuilder, Vector2 center)
{
gcodeStringBuilder.AppendLine("G1 X" + center.x.ToString() + " Y" + center.y.ToString());
}
public static void WriteTestGCodeFile()
{
StringBuilder gcodeStringBuilder = new StringBuilder();
int loops = 15;
int steps = 20;
double radius = 90;
Vector2 center = new Vector2(0, 0);
gcodeStringBuilder.AppendLine("G28 ; home all axes");
gcodeStringBuilder.AppendLine("G90 ; use absolute coordinates");
gcodeStringBuilder.AppendLine("G21 ; set units to millimeters");
gcodeStringBuilder.AppendLine("G92 E0");
gcodeStringBuilder.AppendLine("G1 F7800.000");
//gcodeStringBuilder.AppendLine("G1 Z" + (30).ToString());
WriteMove(gcodeStringBuilder, center);
for (int loop = 0; loop < loops; loop++)
{
for (int step = 0; step < steps; step++)
{
Vector2 nextPosition = new Vector2(radius, 0);
nextPosition.Rotate(MathHelper.Tau / steps * step);
WriteMove(gcodeStringBuilder, center + nextPosition);
}
}
gcodeStringBuilder.AppendLine("M84 ; disable motors");
System.IO.File.WriteAllText("PerformanceTest.gcode", gcodeStringBuilder.ToString());
}
void CheckOnPrinter(object state)
{
PrinterConnectionAndCommunication.Instance.OnIdle();
UiThread.RunOnIdle(CheckOnPrinter);
}
public override void OnParentChanged(EventArgs e)
{
if (File.Exists("RunUnitTests.txt"))
{
//DiagnosticWidget diagnosticView = new DiagnosticWidget(this);
}
base.OnParentChanged(e);
// now that we are all set up lets load our plugins and allow them their chance to set things up
FindAndInstantiatePlugins();
}
private void FindAndInstantiatePlugins()
{
#if false
string pluginDirectory = Path.Combine("..", "..", "..", "MatterControlPlugins", "bin");
#if DEBUG
pluginDirectory = Path.Combine(pluginDirectory, "Debug");
#else
pluginDirectory = Path.Combine(pluginDirectory, "Release");
#endif
if (!Directory.Exists(pluginDirectory))
{
string dataPath = DataStorage.ApplicationDataStorage.Instance.ApplicationUserDataPath;
pluginDirectory = Path.Combine(dataPath, "Plugins");
}
// TODO: this should look in a plugin folder rather than just the application directory (we probably want it in the user folder).
PluginFinder<MatterControlPlugin> pulginFinder = new PluginFinder<MatterControlPlugin>(pluginDirectory);
#else
PluginFinder<MatterControlPlugin> pulginFinder = new PluginFinder<MatterControlPlugin>();
#endif
string oemName = ApplicationSettings.Instance.GetOEMName();
foreach (MatterControlPlugin plugin in pulginFinder.Plugins)
{
string pluginInfo = plugin.GetPluginInfoJSon();
Dictionary<string, string> nameValuePairs = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(pluginInfo);
if (nameValuePairs != null && nameValuePairs.ContainsKey("OEM"))
{
if (nameValuePairs["OEM"] == oemName)
{
plugin.Initialize(this);
}
}
else
{
plugin.Initialize(this);
}
}
}
Stopwatch totalDrawTime = new Stopwatch();
int drawCount = 0;
Gaming.Game.DataViewGraph msGraph = new Gaming.Game.DataViewGraph(new Vector2(20, 500), 50, 50, 0, 200);
public override void OnDraw(Graphics2D graphics2D)
{
totalDrawTime.Restart();
GuiWidget.DrawCount = 0;
base.OnDraw(graphics2D);
totalDrawTime.Stop();
if (ShowMemoryUsed)
{
long memory = GC.GetTotalMemory(false);
this.Title = "Allocated = {0:n0} : {1}ms, d{2} Size = {3}x{4}, onIdle = {5}, drawCount = {6}".FormatWith(memory, totalDrawTime.ElapsedMilliseconds, drawCount++, this.Width, this.Height, UiThread.Count, GuiWidget.DrawCount);
if (DoCGCollectEveryDraw)
{
GC.Collect();
}
}
if (firstDraw)
{
UiThread.RunOnIdle(DoAutoConnectIfRequired);
firstDraw = false;
foreach (string arg in commandLineArgs)
{
if (Path.GetExtension(arg).ToUpper() == ".STL")
{
QueueData.Instance.AddItem(new PrintItemWrapper(new DataStorage.PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
}
}
}
//msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds);
//msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D);
}
public void DoAutoConnectIfRequired(object state)
{
ActivePrinterProfile.CheckForAndDoAutoConnect();
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
if (GuiWidget.DebugBoundsUnderMouse)
{
Invalidate();
}
base.OnMouseMove(mouseEvent);
}
[STAThread]
public static void Main()
{
// Make sure we have the right woring directory as we assume everything relative to the executable.
Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));
Datastore.Instance.Initialize();
// try and open our window matching the last size that we had for it.
string windowSize = ApplicationSettings.Instance.get("WindowSize");
int width = 600;
int height = 660;
if (windowSize != null && windowSize != "")
{
string[] sizes = windowSize.Split(',');
width = Math.Max(int.Parse(sizes[0]), 600);
height = Math.Max(int.Parse(sizes[1]), 600);
}
new MatterControlApplication(width, height);
}
public override void OnClosed(EventArgs e)
{
PrinterConnectionAndCommunication.Instance.Disable();
//Close connection to the local datastore
Datastore.Instance.Exit();
PrinterConnectionAndCommunication.Instance.HaltConnectionThread();
SlicingQueue.Instance.ShutDownSlicingThread();
if (RestartOnClose)
{
string appPathAndFile = System.Reflection.Assembly.GetExecutingAssembly().Location;
string pathToAppFolder = Path.GetDirectoryName(appPathAndFile);
ProcessStartInfo runAppLauncherStartInfo = new ProcessStartInfo();
runAppLauncherStartInfo.Arguments = "\"{0}\" \"{1}\"".FormatWith(appPathAndFile, 1000);
runAppLauncherStartInfo.FileName = Path.Combine(pathToAppFolder, "Launcher.exe");
runAppLauncherStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
runAppLauncherStartInfo.CreateNoWindow = true;
Process.Start(runAppLauncherStartInfo);
}
base.OnClosed(e);
}
string unableToExitMessage = "Oops! You cannot exit while a print is active.".Localize();
string unableToExitTitle = "Unable to Exit".Localize();
string savePartsSheetExitAnywayMessage = "You are currently saving a parts sheet, are you sure you want to exit?".Localize();
string confirmExit = "Confirm Exit".Localize();
public override void OnClosing(out bool CancelClose)
{
// save the last size of the window so we can restore it next time.
ApplicationSettings.Instance.set("WindowSize", string.Format("{0},{1}", Width, Height));
ApplicationSettings.Instance.set("DesktopPosition", string.Format("{0},{1}", DesktopPosition.x, DesktopPosition.y));
//Save a snapshot of the prints in queue
QueueData.Instance.SaveDefaultQueue();
if (PrinterConnectionAndCommunication.Instance.PrinterIsPrinting)
{
StyledMessageBox.ShowMessageBox(unableToExitMessage, unableToExitTitle);
CancelClose = true;
}
else if (PartsSheet.IsSaving())
{
if (!StyledMessageBox.ShowMessageBox(savePartsSheetExitAnywayMessage, confirmExit, StyledMessageBox.MessageType.YES_NO))
{
CancelClose = true;
}
else
{
base.OnClosing(out CancelClose);
}
}
else
{
base.OnClosing(out CancelClose);
}
}
}
}