mattercontrol/CustomWidgets/ExportPrintItemPage.cs

450 lines
13 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg;
2014-06-19 16:09:38 -07:00
using MatterHackers.Agg.PlatformAbstract;
2014-01-29 19:09:30 -08:00
using MatterHackers.Agg.UI;
2017-03-15 16:17:06 -07:00
using MatterHackers.DataConverters3D;
2014-01-29 19:09:30 -08:00
using MatterHackers.GCodeVisualizer;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.Library;
using MatterHackers.MatterControl.PrinterCommunication.Io;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.Queue.OptionsMenu;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.PolygonMesh;
2014-01-29 19:09:30 -08:00
namespace MatterHackers.MatterControl
{
public class ExportPrintItemPage : WizardPage
2015-04-08 15:20:10 -07:00
{
private CheckBox showInFolderAfterSave;
private CheckBox applyLeveling;
private PrintItemWrapper printItemWrapper;
private string gcodePathAndFilenameToSave;
private bool partIsGCode = false;
private string documentsPath;
2017-08-08 21:04:20 -07:00
private EventHandler unregisterEvents;
public ExportPrintItemPage(PrintItemWrapper printItemWrapper)
: base(unlocalizedTextForTitle: "File export options:")
2015-04-08 15:20:10 -07:00
{
this.printItemWrapper = printItemWrapper;
if (Path.GetExtension(printItemWrapper.FileLocation).ToUpper() == ".GCODE")
{
partIsGCode = true;
}
2014-01-29 19:09:30 -08:00
2015-04-08 15:20:10 -07:00
this.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;
this.Name = "Export Item Window";
2015-04-08 15:20:10 -07:00
CreateWindowContent();
2017-08-08 21:04:20 -07:00
PrinterSettings.PrintLevelingEnabledChanged.RegisterEvent((s, e) => CreateWindowContent(), ref unregisterEvents);
2015-04-08 15:20:10 -07:00
}
public void CreateWindowContent()
{
bool modelCanBeExported = !printItemWrapper.PrintItem.Protected;
2017-08-08 20:31:34 -07:00
var commonMargin = new BorderDouble(4, 2);
if (modelCanBeExported)
{
// put in stl export
RadioButton exportAsStlButton = new RadioButton("Export as".Localize() + " STL", textColor: ActiveTheme.Instance.PrimaryTextColor);
exportAsStlButton.Name = "Export as STL button";
2017-08-08 20:31:34 -07:00
exportAsStlButton.Margin = commonMargin;
exportAsStlButton.HAnchor = HAnchor.Left;
2015-04-08 15:20:10 -07:00
exportAsStlButton.Cursor = Cursors.Hand;
exportAsStlButton.CheckedStateChanged += (s, e) =>
{
// Set in stl mode
};
contentRow.AddChild(exportAsStlButton);
2015-04-08 15:20:10 -07:00
// put in amf export
2017-08-09 07:49:50 -07:00
RadioButton exportAsAmfButton = new RadioButton("Export as".Localize() + " AMF", textColor: ActiveTheme.Instance.PrimaryTextColor);
exportAsAmfButton.Name = "Export as AMF button";
2017-08-08 20:31:34 -07:00
exportAsAmfButton.Margin = commonMargin;
exportAsAmfButton.HAnchor = HAnchor.Left;
2015-04-08 15:20:10 -07:00
exportAsAmfButton.Cursor = Cursors.Hand;
exportAsAmfButton.Click += (s, e) =>
{
2017-08-09 07:49:50 -07:00
// Set in stl mode
};
contentRow.AddChild(exportAsAmfButton);
2015-04-08 15:20:10 -07:00
}
bool showExportGCodeButton = ActiveSliceSettings.Instance.PrinterSelected || partIsGCode;
2015-04-08 15:20:10 -07:00
if (showExportGCodeButton)
{
2017-08-08 20:31:05 -07:00
Button exportGCode = textImageButtonFactory.Generate("Export as".Localize() + " G-Code");
exportGCode.Name = "Export as GCode Button";
2017-08-08 20:31:34 -07:00
exportGCode.Margin = commonMargin;
exportGCode.HAnchor = HAnchor.Left;
2015-04-08 15:20:10 -07:00
exportGCode.Cursor = Cursors.Hand;
exportGCode.Click += (s, e) =>
2015-04-08 15:20:10 -07:00
{
this.Parent.CloseOnIdle();
UiThread.RunOnIdle(() =>
{
FileDialog.SaveFileDialog(
new SaveFileDialogParams("Export GCode|*.gcode", title: "Export GCode")
{
Title = "MatterControl: Export File",
ActionButtonLabel = "Export",
FileName = Path.GetFileNameWithoutExtension(printItemWrapper.Name)
},
(saveParams) =>
{
if (!string.IsNullOrEmpty(saveParams.FileName))
{
ExportGcodeCommandLineUtility(saveParams.FileName);
}
});
});
};
contentRow.AddChild(exportGCode);
2014-06-23 13:18:51 -07:00
foreach (ExportGcodePlugin plugin in PluginFinder.CreateInstancesOf<ExportGcodePlugin>())
2016-03-17 08:57:58 -07:00
{
if (plugin.EnabledForCurrentPart(printItemWrapper))
{
// Create export button for each Plugin found
string exportButtonText = plugin.GetButtonText().Localize();
Button pluginButton = textImageButtonFactory.Generate(exportButtonText);
pluginButton.HAnchor = HAnchor.Left;
pluginButton.Margin = commonMargin;
pluginButton.Cursor = Cursors.Hand;
pluginButton.Click += (s, e) =>
2016-03-17 08:57:58 -07:00
{
this.Parent.CloseOnIdle();
UiThread.RunOnIdle(() =>
{
// Open a SaveFileDialog. If Save is clicked, slice the part if needed and pass the plugin the
// path to the gcode file and the target save path
FileDialog.SaveFileDialog(
new SaveFileDialogParams(plugin.GetExtensionFilter())
2016-03-17 08:57:58 -07:00
{
Title = "MatterControl: Export File",
FileName = printItemWrapper.Name,
ActionButtonLabel = "Export"
},
(saveParam) =>
{
string extension = Path.GetExtension(saveParam.FileName);
if (extension == "")
{
saveParam.FileName += plugin.GetFileExtension();
}
if (partIsGCode)
{
try
{
plugin.Generate(printItemWrapper.FileLocation, saveParam.FileName);
}
catch (Exception exception)
{
UiThread.RunOnIdle(() =>
{
StyledMessageBox.ShowMessageBox(null, exception.Message, "Couldn't save file".Localize());
});
}
}
else
{
SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
printItemWrapper.SlicingDone += (printItem, eventArgs) =>
{
PrintItemWrapper sliceItem = (PrintItemWrapper)printItem;
if (File.Exists(sliceItem.GetGCodePathAndFileName()))
{
try
{
plugin.Generate(sliceItem.GetGCodePathAndFileName(), saveParam.FileName);
}
catch (Exception exception)
{
UiThread.RunOnIdle(() =>
{
StyledMessageBox.ShowMessageBox(null, exception.Message, "Couldn't save file".Localize());
});
}
}
};
}
});
});
}; // End exportButton Click handler
contentRow.AddChild(pluginButton);
}
2015-04-08 15:20:10 -07:00
}
}
contentRow.AddChild(new VerticalSpacer());
2015-04-08 15:20:10 -07:00
// If print leveling is enabled then add in a check box 'Apply Leveling During Export' and default checked.
if (showExportGCodeButton && ActiveSliceSettings.Instance.GetValue<bool>(SettingsKey.print_leveling_enabled))
2015-04-08 15:20:10 -07:00
{
applyLeveling = new CheckBox("Apply leveling to G-Code during export".Localize(), ActiveTheme.Instance.PrimaryTextColor, 10)
{
Checked = true,
HAnchor = HAnchor.Left,
Cursor = Cursors.Hand
};
contentRow.AddChild(applyLeveling);
2015-04-08 15:20:10 -07:00
}
// TODO: make this work on the mac and then delete this if
if (OsInformation.OperatingSystem == OSType.Windows
|| OsInformation.OperatingSystem == OSType.X11)
{
showInFolderAfterSave = new CheckBox("Show file in folder after save".Localize(), ActiveTheme.Instance.PrimaryTextColor, 10)
{
HAnchor = HAnchor.Left,
Cursor = Cursors.Hand
};
contentRow.AddChild(showInFolderAfterSave);
2015-04-08 15:20:10 -07:00
}
if (!showExportGCodeButton)
{
2017-08-08 20:31:05 -07:00
var noGCodeMessage = new TextWidget(
"Note".Localize() + ": " + "To enable GCode export, select a printer profile.".Localize(),
textColor: ActiveTheme.Instance.PrimaryTextColor,
pointSize: 10);
noGCodeMessage.HAnchor = HAnchor.Left;
contentRow.AddChild(noGCodeMessage);
2015-04-08 15:20:10 -07:00
}
var exportButton = textImageButtonFactory.Generate("Export".Localize());
exportButton.Click += (s, e) =>
{
2017-08-09 07:49:50 -07:00
//FileDialog.SaveFileDialog(
// new SaveFileDialogParams("Save as AMF|*.amf", initialDirectory: documentsPath)
// {
// Title = "MatterControl: Export File",
// ActionButtonLabel = "Export",
// FileName = printItemWrapper.Name
// },
// (saveParams) =>
// {
// Task.Run(() => SaveAmf(saveParams.FileName));
// });
this.Parent.CloseOnIdle();
UiThread.RunOnIdle(() =>
{
string title = "MatterControl: " + "Export File".Localize();
FileDialog.SaveFileDialog(
new SaveFileDialogParams("Save as STL|*.stl")
{
Title = title,
ActionButtonLabel = "Export",
FileName = printItemWrapper.Name
},
(saveParams) =>
{
if (saveParams.FileName != null)
{
Task.Run(() =>
{
if (SaveStl(new FileSystemFileItem(printItemWrapper.FileLocation), saveParams.FileName))
{
ShowFileIfRequested(saveParams.FileName);
}
else
{
UiThread.RunOnIdle(() =>
{
StyledMessageBox.ShowMessageBox(null, "Export failed".Localize(), title);
});
}
});
}
});
});
};
footerRow.AddChild(exportButton);
footerRow.AddChild(new HorizontalSpacer());
footerRow.AddChild(cancelButton);
2015-04-08 15:20:10 -07:00
}
public void ExportGcodeCommandLineUtility(String nameOfFile)
{
try
{
if (!string.IsNullOrEmpty(nameOfFile))
{
gcodePathAndFilenameToSave = nameOfFile;
string extension = Path.GetExtension(gcodePathAndFilenameToSave);
if (extension == "")
{
File.Delete(gcodePathAndFilenameToSave);
gcodePathAndFilenameToSave += ".gcode";
}
string sourceExtension = Path.GetExtension(printItemWrapper.FileLocation).ToUpper();
if (MeshFileIo.ValidFileExtensions().Contains(sourceExtension))
{
SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
printItemWrapper.SlicingDone += sliceItem_Done;
}
else if (partIsGCode)
{
SaveGCodeToNewLocation(printItemWrapper.FileLocation, gcodePathAndFilenameToSave);
}
}
}
catch
{
}
}
private void SaveGCodeToNewLocation(string gcodeFilename, string dest)
2015-04-08 15:20:10 -07:00
{
try
2015-04-08 15:20:10 -07:00
{
GCodeFileStream gCodeFileStream = new GCodeFileStream(GCodeFile.Load(gcodeFilename, CancellationToken.None));
bool addLevelingStream = ActiveSliceSettings.Instance.GetValue<bool>(SettingsKey.print_leveling_enabled) && applyLeveling.Checked;
var queueStream = new QueuedCommandsStream(gCodeFileStream);
// this is added to ensure we are rewriting the G0 G1 commands as needed
GCodeStream finalStream = addLevelingStream
? new ProcessWriteRegexStream(new PrintLevelingStream(queueStream, false), queueStream)
: new ProcessWriteRegexStream(queueStream, queueStream);
using (StreamWriter file = new StreamWriter(dest))
2015-04-08 15:20:10 -07:00
{
string nextLine = finalStream.ReadLine();
while (nextLine != null)
2015-04-08 15:20:10 -07:00
{
if (nextLine.Trim().Length > 0)
2015-04-08 15:20:10 -07:00
{
file.WriteLine(nextLine);
2015-04-08 15:20:10 -07:00
}
nextLine = finalStream.ReadLine();
2015-04-08 15:20:10 -07:00
}
}
ShowFileIfRequested(dest);
2015-04-08 15:20:10 -07:00
}
catch (Exception e)
2015-04-08 15:20:10 -07:00
{
UiThread.RunOnIdle(() =>
{
StyledMessageBox.ShowMessageBox(null, e.Message, "Couldn't save file".Localize());
});
2015-04-08 15:20:10 -07:00
}
}
private void ShowFileIfRequested(string filename)
{
if (OsInformation.OperatingSystem == OSType.Windows)
2014-01-29 19:09:30 -08:00
{
2015-04-08 15:20:10 -07:00
if (showInFolderAfterSave.Checked)
2014-01-29 19:09:30 -08:00
{
#if IS_WINDOWS_FORMS
2015-04-08 15:20:10 -07:00
WindowsFormsAbstract.ShowFileInFolder(filename);
#endif
2014-01-29 19:09:30 -08:00
}
}
2015-04-08 15:20:10 -07:00
}
private bool SaveAmf(ILibraryContentStream source, string filePathToSave)
{
try
{
if (!string.IsNullOrEmpty(filePathToSave))
{
string extension = Path.GetExtension(filePathToSave);
if (extension == "")
{
File.Delete(filePathToSave);
filePathToSave += ".amf";
}
if (Path.GetExtension(printItemWrapper.FileLocation).ToUpper() == Path.GetExtension(filePathToSave).ToUpper())
{
File.Copy(printItemWrapper.FileLocation, filePathToSave, true);
return true;
}
else
{
IObject3D item = Object3D.Load(printItemWrapper.FileLocation, CancellationToken.None);
return MeshFileIo.Save(item, filePathToSave);
}
}
}
catch (Exception ex)
{
Trace.WriteLine("Error exporting file: " + ex.Message);
}
return false;
}
2014-11-06 07:16:55 -08:00
private bool SaveStl(ILibraryContentStream source, string filePathToSave)
2014-10-11 15:11:26 -07:00
{
try
{
if (!string.IsNullOrEmpty(filePathToSave))
2014-10-11 15:11:26 -07:00
{
string extension = Path.GetExtension(filePathToSave);
if (extension == "")
2015-04-08 15:20:10 -07:00
{
File.Delete(filePathToSave);
filePathToSave += ".stl";
}
if (Path.GetExtension(printItemWrapper.FileLocation).ToUpper() == Path.GetExtension(filePathToSave).ToUpper())
{
File.Copy(printItemWrapper.FileLocation, filePathToSave, true);
return true;
}
else
{
IObject3D loadedItem = Object3D.Load(printItemWrapper.FileLocation, CancellationToken.None);
return MeshFileIo.Save(new List<MeshGroup> { loadedItem.Flatten() }, filePathToSave);
2015-04-08 15:20:10 -07:00
}
2014-10-11 15:11:26 -07:00
}
}
catch (Exception ex)
{
Trace.WriteLine("Error exporting file: " + ex.Message);
}
return false;
2014-10-11 15:11:26 -07:00
}
2014-01-29 19:09:30 -08:00
2015-04-08 15:20:10 -07:00
private void sliceItem_Done(object sender, EventArgs e)
{
PrintItemWrapper sliceItem = (PrintItemWrapper)sender;
2014-01-29 19:09:30 -08:00
printItemWrapper.SlicingDone -= sliceItem_Done;
2015-04-08 15:20:10 -07:00
SaveGCodeToNewLocation(sliceItem.GetGCodePathAndFileName(), gcodePathAndFilenameToSave);
}
2017-08-08 21:04:20 -07:00
public override void OnClosed(ClosedEventArgs e)
{
printItemWrapper.SlicingDone -= sliceItem_Done;
unregisterEvents?.Invoke(this, null);
base.OnClosed(e);
}
2015-04-08 15:20:10 -07:00
}
}